Git Product home page Git Product logo

colored's Introduction

Colored

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);
    "truecolor from tuple".custom_color((0, 255, 136));
    "background truecolor from tuple".on_custom_color((0, 255, 136));
    "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::Colorize;

    // 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)
  • Do note that CLICOLOR_FORCE overrules NO_COLOR, which overrules CLICOLOR
  • 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.

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.

Minimum Supported Rust Version (MSRV)

The current MSRV is 1.70, which is checked and enforced automatically via CI. This version may change in the future in minor version bumps, so if you require a specific Rust version you should use a restricted version requirement such as ~X.Y.

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

colored's People

Contributors

ace4896 avatar becky112358 avatar byron avatar caojen avatar fliegendewurst avatar horgix avatar hwittenborn avatar jonasbn avatar justanothercodemonkey avatar kentfredric avatar kichjang avatar kurtlawrence avatar kylegalloway avatar lingman avatar lukehsiao avatar mackwic avatar madsmtm avatar mahor1221 avatar manonthemat avatar michaelaquilina avatar mlevesquedion avatar mrquantumoff avatar noahp avatar oakchris1955 avatar razican avatar scurest avatar spearman avatar spenserblack avatar twickham avatar waywardmonkeys avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

colored's Issues

How to use with std::io::stdout?

The library works fine when I am using print! or println!. But when writing to stdout, like:

let mut stdout = stdout();
let s = "Hello\n".truecolor(200, 50, 50);
stdout.write(s.as_bytes());
stdout.flush();

I see only regular black-and-white text. How do I get the library to work with stdout?

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.

Force/disable colors by feature flags

like #4 but with feature flags. I am not fan of the Force color by feature flag but I understand this could eventually be needed by a consumer library.

Disable color by feature flag is a must need.

current release doesn't support rust 1.34

Building the current head gives:

error[E0658]: use of unstable library feature 'copied' (see issue #57126)
   --> /home/jlevon/.cargo/registry/src/github.com-1ecc6299db9ec823/colored-1.9.2/src/lib.rs:311:31
    |
311 |         self.fgcolor.as_ref().copied()
    |                               ^^^^^^

error[E0658]: use of unstable library feature 'copied' (see issue #57126)
   --> /home/jlevon/.cargo/registry/src/github.com-1ecc6299db9ec823/colored-1.9.2/src/lib.rs:324:31
    |
324 |         self.bgcolor.as_ref().copied()
    |                               ^^^^^^

If it's intentional that this crate now requires unstable library feature, should the README be updated with the minimal rust version?

Support storing coloured strings in other strings

I'd expected to be able to push a coloured string into another, but it loses the colour:

fn main() {
    let mut s = String::with_capacity(5);
    let msg = "blue";
    s.push_str(&msg.blue());

    println!("{}", msg.blue()); // works
    println!("{}", s); // no colour
}

Is this supported?

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:

 �[90mHello�[0m

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?

non-bold yellow is brown

 println!("{} {} {} {}!",                                                    
             "it".green(),
             "works".blue().bold(),
             "great".bold().yellow(),
             "great".yellow()
             );

untitled

TERM is xterm-256color but linux and xterm have the same effect.
tried in xfce4-terminal 0.8.6-1 on ArchLinux

oh crap i just realized why!
screenshot_2017-07-18_02-46-47

Nevermind! :)
I set it to yellow myself now, but the tooltip is interesting, why would it expect it to be somehow both?
2untitled
3untitled

True colors

Implements:

"hello".palette(23); // 23nth colour of palette
"hello".true_colour(23, 45,  23); // true colour code
"hello".hex_colour("#232332"); // hex colour code

Not working on windows

It is showing numbers rather than color. in this case blue
Capture

Though i have added control::set_virtual_terminal(true); in my source file.
Capture

`ShouldColorize::from_env()` does not look the TERM environment variable

ShouldColorize::from_env() completly ignores wether it runs in an environment that is capable of displaying colors or not and always generates color control codes.

Steps to reproduce:

  1. Write a test program that uses colored.
  2. Start the program with TERM=dumb ./my-test-program

Expected behavior:

  1. The output in uncolored.

Observed behavior:

  1. The output is colored.

Transposed lines in README

The README contains the lines

"purple and magenta are the same".purple().magenta();
"you can specify color by string".color("blue").on_color("red");
"and so are normal and clear".normal().clear();

The first and third were originally adjacent. The insertion of the second in the middle broke the continuity between them. Maybe transpose the second and third line?

Support windows

You already have this as a TODO, but I'm submitting it as an issue so I can watch for it to be closed. :)

Dark grey color

Hello!
I'm using this code "\x1b[90m" to create a dark grey color in the terminal.
How can I make such color using this library?

[Help] What's wrong with this?

I've checked almost everything, but it just doesn't work.

extern crate colored;

use colored::*;

fn main() {
    println!("abc123".green());
}

Readme wrong about should colorise?

Readme states the following:

You can use have even finer control by using the colored::control::should_colorize methods.

However there is no such thing I think, one has to use:

colored::control::set_override(...);

Create and use our own custom colors

We should be able to make our own colors, and use them wherever we want.
Example:

use colored::*;

fn main() {
let greyish = make_color!(100, 100, 100); //In this, 'make_color!' macro is the syntax to make a new color, which we can use anywhere by:
println!("{}", "Hello".greyish()); // So that we don't have to keep typing 'truecolor(....)' and so on...
}

Felt it would be nice..

Enable Colors on Mac Terminal

I'm struggling to get colors working on Mac OS (Catalina) when running through Terminal. I can get other CLIs with colors to display (e.g. ls, git, etc.), but colors coming from the colored package don't show up.

image

If I run the same thing through VS Code's terminal, the colors do show up.

image

Are you aware of any settings I need play with to get this working or limitations of the default terminal? I have tried these with no luck:

  • CLICOLOR
  • CLICOLOR_FORCE
  • NO_COLOR

I'm using the following:

[dependencies]
colored = "2.0.0"

Thanks and I'm really enjoying the crate!

Blanket implementation for `T: ToString`?

Why not implement this?

impl<T: ToString> Colorize for T {
    fn foo(&self) -> ColoredString { Colorize::foo(&self.to_string()) }
}

Note that this will also automatically cover all types that implement Display due to ToString's blanket implementation.

This way, you can, e.g.

println!("{} + {} = {}", 1.blue(), 2.red(), 3.green());

(and many other types)

Commit 4af2de0 breaks coloring

I use colored in a small tool that generates my shell prompt (rusty-prompt).
After updating colored from 1.8.0 to 1.9.0 I noticed that my shell prompt was not colored anymore, neither in bash nor in zsh. I then compiled rusty-prompt against all commits between 1.8.0 and 1.9.0 of colored and figured out that this commit broke the coloring for me: 4af2de0 .
The reason seems to be that colored now wrongly detects my terminal as TTY.

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/

Tests fail to run due to rspec upgrade

When I run a cargo test after cloning this repository, I get this:

   Compiling colored v1.5.2 (file:///...../colored)
error[E0432]: unresolved import `rspec::context::*`
  --> src/control.rs:95:9
   |
95 |     use rspec::context::*;
   |         ^^^^^^^^^^^^^^^^^^ Could not find `context` in `rspec`

error[E0433]: failed to resolve. Could not find `formatter` in `rspec`
   --> src/control.rs:105:29
    |
105 |         let mut formatter = rspec::formatter::Simple::new(stdout);
    |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Could not find `formatter` in `rspec`

error[E0425]: cannot find function `describe` in this scope
   --> src/control.rs:106:26
    |
106 |         let mut runner = describe("ShouldColorize", |ctx| {
    |                          ^^^^^^^^ not found in this scope
    |
help: possible candidates are found in other modules, you can import them into scope
    |     fn clicolor_behavior() use rspec::block::describe;
    |     fn clicolor_behavior() use rspec::describe;

error: aborting due to previous error(s)

error: Could not compile `colored`.
Build failed, waiting for other jobs to finish...
error: build failed

Travis build also fails due to this.

I might take a look at it if I find the time, but don't take this as a promise 🙂

Colors don't work when saving to variable in bash

Hello, I've got problem with coloring after saving program output to variable, thats my code

use colored::*;

fn main() {
    println!("{}", "hello world".red());
}

and then it's wrapped using bash script

output=$(program)
echo -e "${output}"

and it prints out hello world without colors. ansi_term crate works.

hidden = reversed

the hidden() call actually maps to inverse image/reversed, e.g., 0x1b[7m

Awesome api btw!

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

Just thank you.

Please close this issue asap you read. Really great library.

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.

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
}

`set_override` doesn't react immediately

Hi! I'm using set_override to disable color output for my tests at their start and use unset_override at their end. Time to time tests could fail. The reason is I'm still getting colored output. Could this issue be related to Ordering::Relaxed memory ordering used in override methods?

reverse vs. reversed

The method is .reverse(), while the object is Styles::Reversed. All of the other styles, including dimmed, have the same spelling in both cases. Moreover, the documentation does not mention the difference, as it only mentions reversed. This makes it very hard to discover the .reverse() method.

I would recommend adding the .reversed() method which does the same thing as .reverse(), or at least clarifying the situation in the documentation.

Feature Request: Ability to set the style dynamically

I can read the style on a ColoredString and analyze it, but there's no way to easily copy that style to another string, or build up a style dynamically before setting it.

I'd like to see a 'set_style' function on the Colorize trait. It would be even nicer if the 'add' method on Style were made public so I can create my own styles before calling set_style.

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 ✨

Update crates.io?

Hi - I was about to fix the conditional dependency on winconsole, but I see it's already fixed. Could you update the crates.io version with at least that fix?

Specs are not followed regarding tty check

Currently, colored makes no check on whether the output is a tty. This goes at odds with the specs: https://bixense.com/clicolors/

CLICOLOR != 0 ANSI colors are supported and should be used when the program isn’t piped.

I propose to implement coloring exactly the way the specs suggest to do it (example in python):

def has_colors():
    if ((os.getenv("CLICOLOR", "1") != "0" and sys.stdout.isatty()) or
        os.getenv("CLICOLOR_FORCE", "0") != "0"):
        return True
    else:
        return False

I'll try to provide a PR later as well, if there are no objections to the plan.

Text that was not handled by format! does not get painted

Hi, I have a strange issue. First of those two ways does not work, the second does (paints text with green as expected).

use colored::{Colorize, Color};

fn main() {
    let mut buffer = String::with_capacity(400);
    buffer.push_str(&*"supposed to be green text".color(Color::BrightGreen));                            // does not work
    buffer.push_str(format!("{}", "supposed to be green text".color(Color::BrightGreen)).as_str());      // works
    println!("{}", buffer);
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.