├── .gitattributes ├── .gitignore ├── .git-blame-ignore-revs ├── Dockerfile ├── examples ├── as_error.rs ├── custom_colors.rs ├── dynamic_colors.rs ├── nested_colors.rs ├── most_simple.rs └── control.rs ├── src ├── snapshots │ ├── colored__customcolors__tests__main.snap │ ├── colored__tests__it_works_no_color.snap │ └── colored__tests__it_works.snap ├── formatters.rs ├── error.rs ├── customcolors.rs ├── control.rs ├── color.rs ├── style.rs └── lib.rs ├── .github ├── dependabot.yml └── workflows │ ├── publish.yml │ └── test.yml ├── .devcontainer └── devcontainer.json ├── Cargo.toml ├── tests └── ansi_term_compat.rs ├── CHANGELOG.md ├── README.md └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | *.snap linguist-language=Text 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | *.bk 4 | -------------------------------------------------------------------------------- /.git-blame-ignore-revs: -------------------------------------------------------------------------------- 1 | # pedantic clippy fixes 2 | 58a06a44c7640a83a65df6c5afae5ed8f0014fd0 3 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM rust:latest 2 | 3 | ENV SRC_DIR /src 4 | RUN mkdir $SRC_DIR 5 | WORKDIR $SRC_DIR 6 | VOLUME $SRC_DIR 7 | 8 | CMD ["/bin/bash"] 9 | 10 | -------------------------------------------------------------------------------- /examples/as_error.rs: -------------------------------------------------------------------------------- 1 | extern crate colored; 2 | 3 | use colored::Colorize; 4 | use std::error::Error; 5 | 6 | fn main() -> Result<(), Box> { 7 | Err("ERROR".red())? 8 | } 9 | -------------------------------------------------------------------------------- /src/snapshots/colored__customcolors__tests__main.snap: -------------------------------------------------------------------------------- 1 | --- 2 | source: src/customcolors.rs 3 | expression: "\"Greetings from Ukraine\".custom_color(my_color)" 4 | --- 5 | Greetings from Ukraine 6 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 2 | version: 2 3 | updates: 4 | - package-ecosystem: cargo 5 | directory: "/" 6 | schedule: 7 | interval: monthly 8 | -------------------------------------------------------------------------------- /examples/custom_colors.rs: -------------------------------------------------------------------------------- 1 | use colored::{Colorize, CustomColor}; 2 | fn main() { 3 | let my_color = CustomColor::new(0, 120, 120); 4 | println!("{}", "Greetings from Ukraine".custom_color(my_color)); 5 | println!("{}", "Slava Ukraini!".on_custom_color(my_color)); 6 | println!("{}", "Hello World!".on_custom_color((0, 120, 120))); 7 | } 8 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Rust", 3 | "image": "mcr.microsoft.com/vscode/devcontainers/rust:1", 4 | "customizations": { 5 | "vscode": { 6 | "extensions": ["rust-lang.rust-analyzer"] 7 | } 8 | }, 9 | "postCreateCommand": "cargo install cargo-insta", 10 | "remoteUser": "vscode" 11 | } 12 | -------------------------------------------------------------------------------- /src/formatters.rs: -------------------------------------------------------------------------------- 1 | 2 | use color::Color; 3 | use style::Style; 4 | 5 | pub trait ColoringFormatter { 6 | fn format(out: String, fg: Color, bg: Color, style: Style) -> String; 7 | } 8 | 9 | pub struct NoColor; 10 | 11 | impl ColoringFormatter for NoColor { 12 | fn format(out: String, _fg: Color, _bg: Color, _style: Style) -> String { 13 | out 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /examples/dynamic_colors.rs: -------------------------------------------------------------------------------- 1 | extern crate colored; 2 | use colored::{Color, Colorize}; 3 | 4 | fn main() { 5 | // the easy way 6 | "blue string yo".color("blue"); 7 | 8 | // this will default to white 9 | "white string".color("zorglub"); 10 | 11 | // the safer way via a Result 12 | let color_res = "zorglub".parse(); // <- this returns a Result 13 | "red string".color(color_res.unwrap_or(Color::Red)); 14 | } 15 | -------------------------------------------------------------------------------- /examples/nested_colors.rs: -------------------------------------------------------------------------------- 1 | extern crate colored; 2 | 3 | use colored::Colorize; 4 | 5 | /* 6 | * This example use colored strings in a nested way (at line 14). It shows that colored is able to 7 | * keep the correct color on the “!lalalala” part. 8 | */ 9 | 10 | fn main() { 11 | let world = "world".bold(); 12 | let hello_world = format!("Hello, {world}!"); 13 | println!("{hello_world}"); 14 | let hello_world = format!("Hello, {world}!lalalala").red(); 15 | println!("{hello_world}"); 16 | } 17 | -------------------------------------------------------------------------------- /src/snapshots/colored__tests__it_works_no_color.snap: -------------------------------------------------------------------------------- 1 | --- 2 | source: src/lib.rs 3 | expression: buf 4 | --- 5 | toto 6 | toto 7 | toto 8 | blue style **** 9 | toto 10 | yeah ! Red bold ! 11 | yeah ! Yellow bold ! 12 | toto 13 | toto 14 | toto 15 | toto 16 | ****** 17 | test clearing 18 | red cleared 19 | bold cyan cleared 20 | ****** 21 | Bg tests 22 | toto 23 | toto 24 | toto 25 | toto 26 | toto 27 | toto 28 | ****** 29 | toto 30 | toto 31 | toto 32 | toto 33 | toto 34 | toto 35 | toto 36 | toto 37 | toto 38 | toto 39 | toto 40 | toto 41 | 42 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use super::ColoredString; 2 | use std::{error::Error, fmt}; 3 | 4 | pub struct ColoredStringError(pub ColoredString); 5 | 6 | impl ColoredStringError { 7 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 8 | write!(f, "{}", self.0) 9 | } 10 | } 11 | 12 | impl fmt::Display for ColoredStringError { 13 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 14 | self.fmt(f) 15 | } 16 | } 17 | 18 | impl fmt::Debug for ColoredStringError { 19 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 20 | self.fmt(f) 21 | } 22 | } 23 | 24 | impl Error for ColoredStringError {} 25 | -------------------------------------------------------------------------------- /examples/most_simple.rs: -------------------------------------------------------------------------------- 1 | extern crate colored; 2 | 3 | use colored::Colorize; 4 | 5 | fn main() { 6 | // TADAA ! 7 | println!( 8 | "{} {} {}!", 9 | "it".green(), 10 | "works".blue().bold(), 11 | "great".bold().yellow() 12 | ); 13 | 14 | println!("{}", String::from("this also works!").green().bold()); 15 | 16 | let mut s = String::new(); 17 | s.push_str(&"why not ".red().to_string()); 18 | s.push_str(&"push things ".blue().to_string()); 19 | s.push_str(&"a little further ?".green().to_string()); 20 | println!("{s}"); 21 | 22 | let s = format!("{} {} {}", "this".red(), "is".blue(), "easier".green()); 23 | println!("{s}"); 24 | } 25 | -------------------------------------------------------------------------------- /src/snapshots/colored__tests__it_works.snap: -------------------------------------------------------------------------------- 1 | --- 2 | source: src/lib.rs 3 | expression: buf 4 | --- 5 | toto 6 | toto 7 | toto 8 | blue style **** 9 | toto 10 | yeah ! Red bold ! 11 | yeah ! Yellow bold ! 12 | toto 13 | toto 14 | toto 15 | toto 16 | ****** 17 | test clearing 18 | red cleared 19 | bold cyan cleared 20 | ****** 21 | Bg tests 22 | toto 23 | toto 24 | toto 25 | toto 26 | toto 27 | toto 28 | ****** 29 | toto 30 | toto 31 | toto 32 | toto 33 | toto 34 | toto 35 | toto 36 | toto 37 | toto 38 | toto 39 | toto 40 | toto 41 | 42 | -------------------------------------------------------------------------------- /src/customcolors.rs: -------------------------------------------------------------------------------- 1 | /// Custom color structure, it will generate a true color in the result 2 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 3 | pub struct CustomColor { 4 | /// Red 5 | pub r: u8, 6 | /// Green 7 | pub g: u8, 8 | /// Blue 9 | pub b: u8, 10 | } 11 | 12 | /// This only makes custom color creation easier. 13 | impl CustomColor { 14 | /// Create a new custom color 15 | #[must_use] 16 | pub const fn new(r: u8, g: u8, b: u8) -> Self { 17 | Self { r, g, b } 18 | } 19 | } 20 | 21 | impl From<(u8, u8, u8)> for CustomColor { 22 | fn from((r, g, b): (u8, u8, u8)) -> Self { 23 | Self::new(r, g, b) 24 | } 25 | } 26 | 27 | #[cfg(test)] 28 | mod tests { 29 | use crate::*; 30 | #[cfg_attr(feature = "no-color", ignore)] 31 | #[test] 32 | fn main() { 33 | let my_color = CustomColor::new(0, 120, 120); 34 | insta::assert_snapshot!("Greetings from Ukraine".custom_color(my_color)); 35 | } 36 | 37 | #[test] 38 | fn from_tuple() { 39 | let tuple = (1u8, 255u8, 0u8); 40 | let cc = CustomColor::from(tuple); 41 | 42 | assert_eq!(cc.r, tuple.0); 43 | assert_eq!(cc.g, tuple.1); 44 | assert_eq!(cc.b, tuple.2); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "colored" 3 | description = "The most simple way to add colors in your terminal" 4 | version = "3.0.0" 5 | edition = "2021" 6 | authors = ["Thomas Wickham "] 7 | license = "MPL-2.0" 8 | homepage = "https://github.com/mackwic/colored" 9 | repository = "https://github.com/mackwic/colored" 10 | readme = "README.md" 11 | keywords = ["color", "string", "term", "ansiterm", "ansi_term", "term-painter"] 12 | rust-version = "1.80" 13 | 14 | [features] 15 | # with this feature, no color will ever be written 16 | no-color = [] 17 | 18 | 19 | [target.'cfg(windows)'.dependencies.windows-sys] 20 | version = ">=0.48,<=0.60" 21 | features = ["Win32_Foundation", "Win32_System_Console"] 22 | 23 | [dev-dependencies] 24 | ansiterm = "0.12" 25 | insta = "1" 26 | rspec = "1" 27 | 28 | [lints.rust] 29 | unsafe_code = "warn" 30 | deprecated = "warn" 31 | 32 | [lints.clippy] 33 | complexity = "warn" 34 | correctness = "warn" 35 | nursery = "warn" 36 | pedantic = "warn" 37 | perf = "warn" 38 | style = "warn" 39 | suspicious = "warn" 40 | 41 | # Could be enabled in the future 42 | too_many_lines = { level = "allow", priority = 10 } 43 | unwrap_used = { level = "allow", priority = 10 } 44 | expect_used = { level = "allow", priority = 10 } 45 | wildcard_imports = { level = "allow", priority = 10 } 46 | 47 | # not necessary 48 | module_name_repetitions = { level = "allow", priority = 10 } 49 | missing_const_for_fn = { level = "allow", priority = 10 } 50 | -------------------------------------------------------------------------------- /examples/control.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_must_use)] 2 | extern crate colored; 3 | use colored::Colorize; 4 | 5 | #[cfg(not(windows))] 6 | fn main() { 7 | both(); 8 | } 9 | 10 | #[cfg(windows)] 11 | fn main() { 12 | both(); 13 | 14 | // additional control setting using windows set_virtual_terminal 15 | colored::control::set_virtual_terminal(true); 16 | println!("{}", "stdout: Virtual Terminal is in use".bright_green()); 17 | colored::control::set_virtual_terminal(false); 18 | println!( 19 | "{}", 20 | "stderr: Virtual Terminal is NOT in use, escape chars should be visible".bright_red() 21 | ); 22 | colored::control::set_virtual_terminal(true); 23 | println!( 24 | "{}", 25 | "stdout: Virtual Terminal is in use AGAIN and should be green!".bright_green() 26 | ); 27 | colored::control::set_virtual_terminal(true); 28 | 29 | // again with stderr 30 | eprintln!("{}", "stderr: Virtual Terminal is in use".bright_green()); 31 | colored::control::set_virtual_terminal(false); 32 | eprintln!( 33 | "{}", 34 | "stderr: Virtual Terminal is NOT in use, escape chars should be visible".bright_red() 35 | ); 36 | colored::control::set_virtual_terminal(true); 37 | eprintln!( 38 | "{}", 39 | "stderr: Virtual Terminal is in use AGAIN and should be green!".bright_green() 40 | ); 41 | } 42 | 43 | fn both() { 44 | // this will be yellow if your environment allow it 45 | println!("{}", "some warning".yellow()); 46 | // now , this will be always yellow 47 | colored::control::set_override(true); 48 | println!("{}", "some warning".yellow()); 49 | // now, this will be never yellow 50 | colored::control::set_override(false); 51 | println!("{}", "some warning".yellow()); 52 | // let the environment decide again 53 | colored::control::unset_override(); 54 | } 55 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | on: 3 | push: 4 | branches: [master] 5 | permissions: 6 | contents: write 7 | 8 | jobs: 9 | publish: 10 | name: Publish 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout repository 14 | uses: actions/checkout@v3 15 | - name: Get local crate version 16 | id: local-version 17 | run: cargo metadata --no-deps --format-version=1 | jq -r '.packages[0].version' | echo "VERSION=$(cat)" >> "${GITHUB_OUTPUT}" 18 | - name: Get crates.io crate version 19 | id: remote-version 20 | run: curl 'https://index.crates.io/co/lo/colored' | jq -r '.vers' | tail -n 1 | echo "VERSION=$(cat)" >> "${GITHUB_OUTPUT}" 21 | - name: Check if crates.io version is older than local version 22 | id: needs-update 23 | run: | 24 | if ! printf '%s\n' "${{ steps.local-version.outputs.VERSION }}" "${{ steps.remote-version.outputs.VERSION }}" | sort -V | tail -n 1 | grep -Fw "${{ steps.remote-version.outputs.VERSION }}"; then 25 | echo "UPDATE=true" >> "${GITHUB_OUTPUT}" 26 | else 27 | echo "UPDATE=false" >> "${GITHUB_OUTPUT}" 28 | fi 29 | - name: Install parse-changelog 30 | if: steps.needs-update.outputs.UPDATE == 'true' 31 | uses: taiki-e/install-action@parse-changelog 32 | - name: Create GitHub release 33 | if: steps.needs-update.outputs.UPDATE == 'true' 34 | run: gh release create "v${{ steps.local-version.outputs.VERSION }}" -t "v${{ steps.local-version.outputs.VERSION }}" -n "$(parse-changelog CHANGELOG.md "${{ steps.local-version.outputs.VERSION }}")" 35 | env: 36 | GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" 37 | - name: Publish to crates.io 38 | if: steps.needs-update.outputs.UPDATE == 'true' 39 | run: cargo publish 40 | env: 41 | CARGO_REGISTRY_TOKEN: "${{ secrets.CARGO_REGISTRY_TOKEN }}" 42 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | on: pull_request 3 | env: 4 | CLICOLOR_FORCE: 1 5 | COLORTERM: "truecolor" 6 | 7 | jobs: 8 | cargo-fmt: 9 | name: cargo-fmt@stable 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout repository 13 | uses: actions/checkout@v4 14 | - name: Install Rust stable 15 | uses: dtolnay/rust-toolchain@master 16 | with: 17 | toolchain: stable 18 | components: rustfmt 19 | - name: Run formatting checks 20 | run: cargo fmt --check 21 | 22 | cargo-clippy: 23 | name: "${{ matrix.os }}:cargo-clippy@stable" 24 | runs-on: "${{ matrix.os }}-latest" 25 | strategy: 26 | matrix: 27 | os: ["ubuntu", "windows", "macos"] 28 | steps: 29 | - name: Checkout repository 30 | uses: actions/checkout@v4 31 | - name: Install Rust stable 32 | uses: dtolnay/rust-toolchain@master 33 | with: 34 | toolchain: stable 35 | components: clippy 36 | - name: Run clippy checks 37 | run: cargo clippy --all-features -- -D warnings 38 | 39 | cargo-test: 40 | name: "${{ matrix.os }}:cargo-test@${{ matrix.version }}" 41 | runs-on: "${{ matrix.os }}-latest" 42 | strategy: 43 | matrix: 44 | os: ["ubuntu", "windows", "macos"] 45 | version: ["stable", "beta", "1.80"] 46 | steps: 47 | - name: Checkout repository 48 | uses: actions/checkout@v4 49 | - name: Install Rust ${{ matrix.version }} 50 | uses: dtolnay/rust-toolchain@master 51 | with: 52 | toolchain: ${{ matrix.version }} 53 | - name: Run tests 54 | run: cargo test 55 | 56 | check-semver: 57 | name: Check semver compatibility 58 | if: github.base_ref == 'master' 59 | runs-on: ubuntu-latest 60 | steps: 61 | - name: Checkout repository 62 | uses: actions/checkout@v4 63 | - name: Check semver 64 | uses: obi1kenobi/cargo-semver-checks-action@v2 65 | -------------------------------------------------------------------------------- /tests/ansi_term_compat.rs: -------------------------------------------------------------------------------- 1 | #![cfg(not(feature = "no-color"))] 2 | #![allow(unused_imports)] 3 | 4 | extern crate ansiterm; 5 | extern crate colored; 6 | 7 | use ansiterm::*; 8 | use colored::*; 9 | 10 | macro_rules! test_simple_color { 11 | ($string:expr, $colored_name:ident, $ansiterm_name:ident) => { 12 | #[test] 13 | fn $colored_name() { 14 | let s = format!("{} {}", $string, stringify!($colored_name)); 15 | assert_eq!( 16 | s.$colored_name().to_string(), 17 | Colour::$ansiterm_name.paint(s).to_string() 18 | ) 19 | } 20 | }; 21 | } 22 | 23 | mod compat_colors { 24 | use super::ansiterm::*; 25 | use super::colored::*; 26 | 27 | test_simple_color!("test string", black, Black); 28 | test_simple_color!("test string", red, Red); 29 | test_simple_color!("test string", green, Green); 30 | test_simple_color!("test string", yellow, Yellow); 31 | test_simple_color!("test string", blue, Blue); 32 | test_simple_color!("test string", magenta, Purple); 33 | test_simple_color!("test string", cyan, Cyan); 34 | test_simple_color!("test string", white, White); 35 | } 36 | 37 | macro_rules! test_simple_style { 38 | ($string:expr, $colored_style:ident, $ansiterm_style:ident) => { 39 | #[test] 40 | fn $colored_style() { 41 | let s = format!("{} {}", $string, stringify!($colored_style)); 42 | assert_eq!( 43 | s.$colored_style().to_string(), 44 | ansiterm::Style::new() 45 | .$ansiterm_style() 46 | .paint(s) 47 | .to_string() 48 | ) 49 | } 50 | }; 51 | } 52 | 53 | mod compat_styles { 54 | use super::ansiterm; 55 | use super::ansiterm::*; 56 | use super::colored; 57 | use super::colored::*; 58 | 59 | test_simple_style!("test string", bold, bold); 60 | test_simple_style!("test string", dimmed, dimmed); 61 | test_simple_style!("test string", italic, italic); 62 | test_simple_style!("test string", underline, underline); 63 | test_simple_style!("test string", blink, blink); 64 | test_simple_style!("test string", reversed, reverse); 65 | test_simple_style!("test string", hidden, hidden); 66 | } 67 | 68 | macro_rules! test_simple_bgcolor { 69 | ($string:expr, $colored_name:ident, $ansiterm_name:ident) => { 70 | #[test] 71 | fn $colored_name() { 72 | let s = format!("{} {}", $string, stringify!($colored_name)); 73 | assert_eq!( 74 | s.$colored_name().to_string(), 75 | ansiterm::Style::default() 76 | .on(ansiterm::Colour::$ansiterm_name) 77 | .paint(s) 78 | .to_string() 79 | ) 80 | } 81 | }; 82 | } 83 | 84 | mod compat_bgcolors { 85 | use super::ansiterm; 86 | use super::ansiterm::*; 87 | use super::colored; 88 | use super::colored::*; 89 | 90 | test_simple_bgcolor!("test string", on_black, Black); 91 | test_simple_bgcolor!("test string", on_red, Red); 92 | test_simple_bgcolor!("test string", on_green, Green); 93 | test_simple_bgcolor!("test string", on_yellow, Yellow); 94 | test_simple_bgcolor!("test string", on_blue, Blue); 95 | test_simple_bgcolor!("test string", on_magenta, Purple); 96 | test_simple_bgcolor!("test string", on_cyan, Cyan); 97 | test_simple_bgcolor!("test string", on_white, White); 98 | } 99 | 100 | mod compat_complex { 101 | use super::ansiterm; 102 | use super::ansiterm::*; 103 | use super::colored; 104 | use super::colored::*; 105 | 106 | #[test] 107 | fn complex1() { 108 | let s = "test string"; 109 | let ansi = Colour::Red.on(Colour::Black).bold().italic().paint(s); 110 | assert_eq!( 111 | ansi.to_string(), 112 | s.red().bold().italic().on_black().to_string() 113 | ); 114 | } 115 | 116 | #[test] 117 | fn complex2() { 118 | let s = "test string"; 119 | let ansi = Colour::Green.on(Colour::Yellow).underline().paint(s); 120 | assert_eq!( 121 | ansi.to_string(), 122 | s.green().on_yellow().underline().to_string() 123 | ); 124 | } 125 | } 126 | 127 | mod compat_overrides { 128 | use super::ansiterm; 129 | use super::ansiterm::*; 130 | use super::colored; 131 | use super::colored::*; 132 | 133 | #[test] 134 | fn overrides1() { 135 | let s = "test string"; 136 | let ansi = Colour::Red.on(Colour::Black).on(Colour::Blue).paint(s); 137 | assert_eq!(ansi.to_string(), s.red().on_blue().to_string()); 138 | } 139 | 140 | #[test] 141 | fn overrides2() { 142 | let s = "test string"; 143 | let ansi = Colour::Green.on(Colour::Yellow).paint(s); 144 | assert_eq!( 145 | ansi.to_string(), 146 | s.green().on_yellow().green().on_yellow().to_string() 147 | ); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Unreleased 2 | - Added methods `ansi_color` and `on_ansi_color` to `Colorize`. 3 | 4 | # 3.0.0 5 | - **[BREAKING CHANGE]:** Upgrade MSRV to 1.80 and remove the then unnecessary lazy_static dependency. 6 | 7 | # 2.2.0 8 | - Updated top-level docs to include a note about `ColoredString`\'s role in the `Colorize` pipeline as well as link to it to suggest learning more about how to manipulate existing `ColoredString`\'s. 9 | - Changes to `ColoredString`: 10 | - Expose fields. 11 | - **[DEPRECATION]:** Deprecated methods `fgcolor`, `bgcolor`, and `style` due to their obsolescence in the face of the exposing of their represented fields. 12 | - Add methods for clearing specific elements of `fgcolor`, `bgcolor`, and `style`. 13 | - Change Default implementation to be via derive as Style now implements Default (see changes to Style below). 14 | - Add implementation of `DerefMut`. 15 | - Updated docs to reflect the above changes as well as generally greatly expand them. 16 | - Changes to `Style`: 17 | - Implemented `Default` for `Style` (returns `CLEAR`). This exposes a method by which users can create plain `Style`\'s from scratch. 18 | - Implemented `From` for `Style`. This lets users easily create `Style`\'s from specific styles. 19 | - Exposed previously private method `add`. 20 | - Created method `remove` which essentially does the opposite. 21 | - Added builder-style methods in the vein of `Colorize` to add stylings (e.g. `bold`, `underline`, `italic`, `strikethrough`). 22 | - Implemented bitwise operators `BitAnd`, `BitOr`, `BitXor`, and `Not` as well as their representative assignment operators. You can also use a `Styles` as an operand for these. 23 | - Implemented `FromIterator` for Style. 24 | - Changes to `Styles`: 25 | - Implemented bitwise operators `BitAnd`, `BitOr`, `BitXor`, and `Not` which all combine `Styles`\'s and output `Style`\'s. These can also take a `Style` as an operand. 26 | - Added additional testing for all of the above changes. 27 | - Added methods `with_style` and `with_color_and_style` to `Colorize`. 28 | 29 | # 2.1.0 30 | * Impl From for ColoredString by @mahor1221 in https://github.com/colored-rs/colored/pull/126 31 | * Allow conversion from ColoredString to Error by @spenserblack in https://github.com/colored-rs/colored/pull/86 32 | * Suggestion for minor documentation clarification by @jonasbn in https://github.com/colored-rs/colored/pull/98 33 | * Remove unnecessary is_terminal dependency by @Oakchris1955 in https://github.com/colored-rs/colored/pull/149 34 | - Document crate MSRV of `1.70`. 35 | 36 | # 2.0.4 37 | - Switch from `winapi` to `windows-sys`. 38 | 39 | # 2.0.3 40 | - Document crate MSRV of `1.63`. 41 | 42 | # 2.0.2 43 | - Fix typo in `src/control.rs`. 44 | - Replace `atty` dependency with `is-terminal`. 45 | 46 | # 2.0.1 (July 3, 2023) 47 | - Add edition for future compatibility. 48 | - Implement custom colors that can be stored in a variable. 49 | 50 | # 2.0.0 (July 14, 2020) 51 | - Add support for true colours. 52 | - Alter `Color` interface to return `Cow<'static, str>` 53 | 54 | # 1.9.3 (February 24, 2020) 55 | - Fix compilation regression for 1.34.0. Thanks @jlevon for reporting. 56 | 57 | # 1.9.2 (January 11, 2020) 58 | - Exposed `ColoredString` data through methods for purposes of interrogating the applied colours. 59 | - Increased documentation. 60 | 61 | # 1.9.1 (December 31, 2019) 62 | 63 | - Remove deprecated `try!` macro in codebase 64 | - Reduce allocations in `ColoredString` impl (PR#65) 65 | - Added `"purple"` as match in `impl FromStr for Color` (PR#71) 66 | 67 | # 1.9.0 (November 11, 2019) 68 | 69 | - **[POSSIBLE_BREAKING CHANGE]:** Replace `winconsole` with `winapi`: 70 | - Changes `set_virtual_terminal` function signature. 71 | - Update dependencies 72 | - Add Dockerfile 73 | - Respect tty discovery for CLICOLOR 74 | 75 | # 1.8.0 (April 30, 2019) 76 | 77 | - FEAT: support Windows 10 colors 78 | 79 | # 1.7.0 (January, 2019) 80 | - TECH: update lazy\_static 81 | - FEAT: introduce respect for the `NO_COLOR` environment variable 82 | 83 | # 1.6.1 (July 9, 2018) 84 | - TECH: update lazy\_static 85 | - CHORE: fix typos in README and documentation 86 | 87 | # 1.6.0 (October 31, 2017) 88 | - FEAT: introduced bright colors. `"hello".bright_blue().on_bright_red();` 89 | - FEAT: introduced strikethrough styling. `"hello".strikethrough();` 90 | 91 | # 1.5.3 (September 28, 2017) 92 | 93 | - FEAT: derive Copy and Clone for `Color` 94 | - FEAT: derive Clone for `ColoredString` 95 | 96 | # 1.5.2 (July 6, 2017) 97 | 98 | - FIX: method `Colorize::reversed` has been added. `Colorize::reverse` was a typo, that we will keep 99 | for compatibility 100 | 101 | # 1.5.1 (May 9, 2017) 102 | 103 | - Update lazy\_static to 0.2. 104 | 105 | # 1.5.0 (May 1, 2017) 106 | 107 | - FEAT: support for `"hello".color("blue")` (dynamic colors) 108 | 109 | # 1.3.2 (Nov 26, 2016) 110 | 111 | - FIX: usage of nested ColoredString again, no more style broken mid-line 112 | 113 | # 1.3.1 (Oct 14, 2016) 114 | 115 | - FIX: usage of ColoredString in a nested way broke the styling mid-line 116 | 117 | # 1.3.0 (Jul 31, 2016) 118 | 119 | - Provide various options for disabling the coloring in an API-compatible way 120 | 121 | # 1.2.0 (Mar 30, 2016) 122 | 123 | - Support the different formatting options, like padding and alignment 124 | 125 | # 1.1.0 (Mar 15, 2016) 126 | 127 | - Respect the CLICOLOR/CLICOLOR\_FORCE behavior. See [this specs](http://bixense.com/clicolors/) 128 | 129 | # 1.0.1 (Mar 14, 2016) 130 | 131 | - Add a CHANGLOG 132 | - Fix crate dependencies: move `ansi_term` in dev\_dependencies 133 | 134 | # 1.0.0 (Mar 13, 2016) 135 | 136 | - Initial release 137 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Colored 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/colored.svg?maxAge=2592000)](https://crates.io/crates/colored) [![Crates.io](https://img.shields.io/crates/l/colored.svg?maxAge=2592000)](https://github.com/mackwic/colored/blob/master/LICENSE) 4 | 5 | Coloring terminal so simple, you already know how to do it! 6 | 7 | ```rust 8 | "this is blue".blue(); 9 | "this is red".red(); 10 | "this is red on blue".red().on_blue(); 11 | "this is also red on blue".on_blue().red(); 12 | "you can use truecolor values too!".truecolor(0, 255, 136); 13 | "background truecolor also works :)".on_truecolor(135, 28, 167); 14 | "truecolor from tuple".custom_color((0, 255, 136)); 15 | "background truecolor from tuple".on_custom_color((0, 255, 136)); 16 | "bright colors are welcome as well".on_bright_blue().bright_red(); 17 | "you can also make bold text".bold(); 18 | println!("{} {} {}", "or use".cyan(), "any".italic().yellow(), "string type".cyan()); 19 | "or change advice. This is red".yellow().blue().red(); 20 | "or clear things up. This is default color and style".red().bold().clear(); 21 | "purple and magenta are the same".purple().magenta(); 22 | "and so are normal and clear".normal().clear(); 23 | "you can specify color by string".color("blue").on_color("red"); 24 | "you can also use hex colors".color("#0057B7").on_color("#fd0"); 25 | String::from("this also works!").green().bold(); 26 | format!("{:30}", "format works as expected. This will be padded".blue()); 27 | format!("{:.3}", "and this will be green but truncated to 3 chars".green()); 28 | ``` 29 | 30 | ## How to use 31 | 32 | Add this in your `Cargo.toml`: 33 | 34 | ```toml 35 | [dependencies] 36 | colored = "3" 37 | ``` 38 | 39 | and add this to your `lib.rs` or `main.rs`: 40 | 41 | ```rust 42 | extern crate colored; // not needed in Rust 2018+ 43 | 44 | use colored::Colorize; 45 | 46 | // test the example with `cargo run --example most_simple` 47 | fn main() { 48 | // TADAA! 49 | println!("{} {} !", "it".green(), "works".blue().bold()); 50 | } 51 | ``` 52 | 53 | ## Features 54 | 55 | - Safe rust, easy to use, minimal dependencies, complete test suite 56 | - Respect the `CLICOLOR`/`CLICOLOR_FORCE` behavior (see [the specs](http://bixense.com/clicolors/)) 57 | - Respect the `NO_COLOR` behavior (see [the specs](https://no-color.org/)) 58 | - Do note that `CLICOLOR_FORCE` overrules `NO_COLOR`, which overrules `CLICOLOR` 59 | - Works on Linux, MacOS, and Windows (Powershell) 60 | 61 | #### Colors: 62 | 63 | - black 64 | - red 65 | - green 66 | - yellow 67 | - blue 68 | - magenta (or purple) 69 | - cyan 70 | - white 71 | 72 | Bright colors: prepend the color by `bright_`. So easy. 73 | Background colors: prepend the color by `on_`. Simple as that. 74 | Bright Background colors: prepend the color by `on_bright_`. Not hard at all. 75 | 76 | #### Truecolors 77 | 78 | Colored has support for truecolors where you can specify any arbitrary rgb value. 79 | 80 | This feature will only work correctly in terminals which support true colors (i.e. most modern terminals). 81 | 82 | 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. 83 | 84 | #### Styles: 85 | 86 | - bold 87 | - underline 88 | - italic 89 | - dimmed 90 | - reversed 91 | - blink 92 | - hidden 93 | - strikethrough 94 | 95 | You can clear color _and_ style anytime by using `normal()` or `clear()` 96 | 97 | #### Advanced Control: 98 | 99 | ##### Dynamic color from str 100 | 101 | As `Color` implements `FromStr`, `From<&str>`, and `From`, you can easily cast a string into a color like that: 102 | 103 | ```rust 104 | // the easy way 105 | "blue string yo".color("blue"); 106 | 107 | // this will default to white 108 | "white string".color("zorglub"); 109 | 110 | // the safer way via a Result 111 | let color_res : Result = "zorglub".parse(); 112 | "red string".color(color_res.unwrap_or(Color::Red)); 113 | ``` 114 | 115 | 116 | ##### Colorization control 117 | 118 | If you want to disable any coloring at compile time, you can simply do so by 119 | using the `no-color` feature. 120 | 121 | For example, you can do this in your `Cargo.toml` to disable color in tests: 122 | 123 | ```toml 124 | [features] 125 | # this effectively enable the feature `no-color` of colored when testing with 126 | # `cargo test --features dumb_terminal` 127 | dumb_terminal = ["colored/no-color"] 128 | ``` 129 | 130 | You can have even finer control by using the 131 | `colored::control::set_override` method. 132 | 133 | ## Todo 134 | 135 | - **More tests ?**: We always welcome more tests! Please contribute! 136 | 137 | ## Credits 138 | 139 | This library wouldn't have been the same without the marvelous ruby gem [colored](https://github.com/defunkt/colored). 140 | 141 | Thanks for the [ansi\_term crate](https://github.com/ogham/rust-ansi-term) for 142 | providing a reference implementation, which greatly helped making this crate 143 | output correct strings. 144 | 145 | ## Minimum Supported Rust Version (MSRV) 146 | The current MSRV is `1.80`, 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`. 147 | 148 | ## License 149 | 150 | [Mozilla Public License 2.0](https://www.mozilla.org/en-US/MPL/2.0/). See the 151 | [LICENSE](https://github.com/mackwic/colored/blob/master/LICENSE) file at the 152 | root of the repository. 153 | 154 | In non legal terms it means that: 155 | - if you fix a bug, you MUST give me the code of the fix (it's only fair) 156 | - if you change/extend the API, you MUST give me the code you changed in the 157 | files under MPL2. 158 | - you CAN'T sue me for anything about this code 159 | - apart from that, you can do almost whatever you want. See the LICENSE file 160 | for details. 161 | 162 | ## Contributors 163 | 164 | - Thomas Wickham: [@mackwic](https://github.com/mackwic) 165 | - Hunter Wittenborn [@hwittenborn](https://github.com/hwittenborn) 166 | - Corey "See More" Richardson: [@cmr](https://github.com/cmr) 167 | - Iban Eguia: [@Razican](https://github.com/Razican) 168 | - Alexis "Horgix" Chotard: [@horgix](https://github.com/horgix) 169 | - Keith Yeung: [@KiChjang](https://github.com/KiChjang) 170 | - Kyle Galloway: [@kylegalloway](https://github.com/kylegalloway) 171 | - Luke Hsiao: [@lukehsiao](https://github.com/lukehsiao) 172 | - kurtlawrence: [@kurtlawrence](https://github.com/kurtlawrence) 173 | -------------------------------------------------------------------------------- /src/control.rs: -------------------------------------------------------------------------------- 1 | //! A couple of functions to enable and disable coloring. 2 | 3 | use std::default::Default; 4 | use std::env; 5 | use std::io::{self, IsTerminal}; 6 | use std::sync::atomic::{AtomicBool, Ordering}; 7 | use std::sync::LazyLock; 8 | 9 | /// Sets a flag to the console to use a virtual terminal environment. 10 | /// 11 | /// This is primarily used for Windows 10 environments which will not correctly colorize 12 | /// the outputs based on ANSI escape codes. 13 | /// 14 | /// The returned `Result` is _always_ `Ok(())`, the return type was kept to ensure backwards 15 | /// compatibility. 16 | /// 17 | /// # Notes 18 | /// > Only available to `Windows` build targets. 19 | /// 20 | /// # Example 21 | /// ```rust 22 | /// use colored::*; 23 | /// control::set_virtual_terminal(false).unwrap(); 24 | /// println!("{}", "bright cyan".bright_cyan()); // will print 'bright cyan' on windows 10 25 | /// 26 | /// control::set_virtual_terminal(true).unwrap(); 27 | /// println!("{}", "bright cyan".bright_cyan()); // will print correctly 28 | /// ``` 29 | /// # Errors 30 | /// This function will return `Ok(())` if the operation was successful. 31 | #[allow(clippy::result_unit_err)] 32 | #[cfg(windows)] 33 | pub fn set_virtual_terminal(use_virtual: bool) -> Result<(), ()> { 34 | use windows_sys::Win32::System::Console::{ 35 | GetConsoleMode, GetStdHandle, SetConsoleMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING, 36 | STD_OUTPUT_HANDLE, 37 | }; 38 | 39 | #[allow(unsafe_code)] // needed here 40 | unsafe { 41 | let handle = GetStdHandle(STD_OUTPUT_HANDLE); 42 | let mut original_mode = 0; 43 | GetConsoleMode(handle, &mut original_mode); 44 | 45 | let enabled = original_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING 46 | == ENABLE_VIRTUAL_TERMINAL_PROCESSING; 47 | 48 | match (use_virtual, enabled) { 49 | // not enabled, should be enabled 50 | (true, false) => { 51 | SetConsoleMode(handle, ENABLE_VIRTUAL_TERMINAL_PROCESSING | original_mode) 52 | } 53 | // already enabled, should be disabled 54 | (false, true) => { 55 | SetConsoleMode(handle, ENABLE_VIRTUAL_TERMINAL_PROCESSING ^ original_mode) 56 | } 57 | _ => 0, 58 | }; 59 | } 60 | 61 | Ok(()) 62 | } 63 | 64 | /// A flag for whether coloring should occur. 65 | pub struct ShouldColorize { 66 | clicolor: bool, 67 | clicolor_force: Option, 68 | // XXX we can't use Option because we can't use &mut references to ShouldColorize 69 | has_manual_override: AtomicBool, 70 | manual_override: AtomicBool, 71 | } 72 | 73 | /// Use this to force colored to ignore the environment and always/never colorize 74 | /// See example/control.rs 75 | pub fn set_override(override_colorize: bool) { 76 | SHOULD_COLORIZE.set_override(override_colorize); 77 | } 78 | 79 | /// Remove the manual override and let the environment decide if it's ok to colorize 80 | /// See example/control.rs 81 | pub fn unset_override() { 82 | SHOULD_COLORIZE.unset_override(); 83 | } 84 | 85 | /// The persistent [`ShouldColorize`]. 86 | pub static SHOULD_COLORIZE: LazyLock = LazyLock::new(ShouldColorize::from_env); 87 | 88 | impl Default for ShouldColorize { 89 | fn default() -> Self { 90 | Self { 91 | clicolor: true, 92 | clicolor_force: None, 93 | has_manual_override: AtomicBool::new(false), 94 | manual_override: AtomicBool::new(false), 95 | } 96 | } 97 | } 98 | 99 | impl ShouldColorize { 100 | /// Reads environment variables and checks if output is a tty to determine 101 | /// whether colorization should be used or not. 102 | /// `CLICOLOR_FORCE` takes highest priority, followed by `NO_COLOR`, 103 | /// followed by `CLICOLOR` combined with tty check. 104 | #[must_use] 105 | pub fn from_env() -> Self { 106 | Self { 107 | clicolor: Self::normalize_env(env::var("CLICOLOR")).unwrap_or(true) 108 | && io::stdout().is_terminal(), 109 | clicolor_force: Self::resolve_clicolor_force( 110 | env::var("NO_COLOR"), 111 | env::var("CLICOLOR_FORCE"), 112 | ), 113 | ..Self::default() 114 | } 115 | } 116 | 117 | /// Returns if the current coloring is expected. 118 | pub fn should_colorize(&self) -> bool { 119 | if self.has_manual_override.load(Ordering::Relaxed) { 120 | return self.manual_override.load(Ordering::Relaxed); 121 | } 122 | 123 | if let Some(forced_value) = self.clicolor_force { 124 | return forced_value; 125 | } 126 | 127 | self.clicolor 128 | } 129 | 130 | /// Use this to force colored to ignore the environment and always/never colorize 131 | pub fn set_override(&self, override_colorize: bool) { 132 | self.has_manual_override.store(true, Ordering::Relaxed); 133 | self.manual_override 134 | .store(override_colorize, Ordering::Relaxed); 135 | } 136 | 137 | /// Remove the manual override and let the environment decide if it's ok to colorize 138 | pub fn unset_override(&self) { 139 | self.has_manual_override.store(false, Ordering::Relaxed); 140 | } 141 | 142 | /* private */ 143 | 144 | fn normalize_env(env_res: Result) -> Option { 145 | env_res.map_or(None, |string| Some(string != "0")) 146 | } 147 | 148 | fn resolve_clicolor_force( 149 | no_color: Result, 150 | clicolor_force: Result, 151 | ) -> Option { 152 | if Self::normalize_env(clicolor_force) == Some(true) { 153 | Some(true) 154 | } else if Self::normalize_env(no_color).is_some() { 155 | Some(false) 156 | } else { 157 | None 158 | } 159 | } 160 | } 161 | 162 | #[cfg(test)] 163 | mod specs { 164 | use super::*; 165 | use rspec; 166 | use std::env; 167 | 168 | #[test] 169 | fn clicolor_behavior() { 170 | rspec::run(&rspec::describe("ShouldColorize", (), |ctx| { 171 | ctx.specify("::normalize_env", |ctx| { 172 | ctx.it("should return None if error", |()| { 173 | assert_eq!( 174 | None, 175 | ShouldColorize::normalize_env(Err(env::VarError::NotPresent)) 176 | ); 177 | assert_eq!( 178 | None, 179 | ShouldColorize::normalize_env(Err(env::VarError::NotUnicode("".into()))) 180 | ); 181 | }); 182 | 183 | ctx.it("should return Some(true) if != 0", |()| { 184 | Some(true) == ShouldColorize::normalize_env(Ok(String::from("1"))) 185 | }); 186 | 187 | ctx.it("should return Some(false) if == 0", |()| { 188 | Some(false) == ShouldColorize::normalize_env(Ok(String::from("0"))) 189 | }); 190 | }); 191 | 192 | ctx.specify("::resolve_clicolor_force", |ctx| { 193 | ctx.it( 194 | "should return None if NO_COLOR is not set and CLICOLOR_FORCE is not set or set to 0", 195 | |()| { 196 | assert_eq!( 197 | None, 198 | ShouldColorize::resolve_clicolor_force( 199 | Err(env::VarError::NotPresent), 200 | Err(env::VarError::NotPresent) 201 | ) 202 | ); 203 | assert_eq!( 204 | None, 205 | ShouldColorize::resolve_clicolor_force( 206 | Err(env::VarError::NotPresent), 207 | Ok(String::from("0")), 208 | ) 209 | ); 210 | }, 211 | ); 212 | 213 | ctx.it( 214 | "should return Some(false) if NO_COLOR is set and CLICOLOR_FORCE is not enabled", 215 | |()| { 216 | assert_eq!( 217 | Some(false), 218 | ShouldColorize::resolve_clicolor_force( 219 | Ok(String::from("0")), 220 | Err(env::VarError::NotPresent) 221 | ) 222 | ); 223 | assert_eq!( 224 | Some(false), 225 | ShouldColorize::resolve_clicolor_force( 226 | Ok(String::from("1")), 227 | Err(env::VarError::NotPresent) 228 | ) 229 | ); 230 | assert_eq!( 231 | Some(false), 232 | ShouldColorize::resolve_clicolor_force( 233 | Ok(String::from("1")), 234 | Ok(String::from("0")), 235 | ) 236 | ); 237 | }, 238 | ); 239 | 240 | ctx.it( 241 | "should prioritize CLICOLOR_FORCE over NO_COLOR if CLICOLOR_FORCE is set to non-zero value", 242 | |()| { 243 | assert_eq!( 244 | Some(true), 245 | ShouldColorize::resolve_clicolor_force( 246 | Ok(String::from("1")), 247 | Ok(String::from("1")), 248 | ) 249 | ); 250 | assert_eq!( 251 | Some(false), 252 | ShouldColorize::resolve_clicolor_force( 253 | Ok(String::from("1")), 254 | Ok(String::from("0")), 255 | ) 256 | ); 257 | assert_eq!( 258 | Some(true), 259 | ShouldColorize::resolve_clicolor_force( 260 | Err(env::VarError::NotPresent), 261 | Ok(String::from("1")), 262 | ) 263 | ); 264 | }, 265 | ); 266 | }); 267 | 268 | ctx.specify("constructors", |ctx| { 269 | ctx.it("should have a default constructor", |()| { 270 | ShouldColorize::default(); 271 | }); 272 | 273 | ctx.it("should have an environment constructor", |()| { 274 | #[allow(unused_must_use)] 275 | ShouldColorize::from_env(); 276 | }); 277 | }); 278 | 279 | ctx.specify("when only changing clicolors", |ctx| { 280 | ctx.it("clicolor == false means no colors", |()| { 281 | let colorize_control = ShouldColorize { 282 | clicolor: false, 283 | ..ShouldColorize::default() 284 | }; 285 | !colorize_control.should_colorize() 286 | }); 287 | 288 | ctx.it("clicolor == true means colors !", |()| { 289 | let colorize_control = ShouldColorize { 290 | clicolor: true, 291 | ..ShouldColorize::default() 292 | }; 293 | colorize_control.should_colorize() 294 | }); 295 | 296 | ctx.it("unset clicolors implies true", |()| { 297 | ShouldColorize::default().should_colorize() 298 | }); 299 | }); 300 | 301 | ctx.specify("when using clicolor_force", |ctx| { 302 | ctx.it( 303 | "clicolor_force should force to true no matter clicolor", 304 | |()| { 305 | let colorize_control = ShouldColorize { 306 | clicolor: false, 307 | clicolor_force: Some(true), 308 | ..ShouldColorize::default() 309 | }; 310 | 311 | colorize_control.should_colorize() 312 | }, 313 | ); 314 | 315 | ctx.it( 316 | "clicolor_force should force to false no matter clicolor", 317 | |()| { 318 | let colorize_control = ShouldColorize { 319 | clicolor: true, 320 | clicolor_force: Some(false), 321 | ..ShouldColorize::default() 322 | }; 323 | 324 | !colorize_control.should_colorize() 325 | }, 326 | ); 327 | }); 328 | 329 | ctx.specify("using a manual override", |ctx| { 330 | ctx.it("should colorize if manual_override is true, but clicolor is false and clicolor_force also false", |()| { 331 | let colorize_control = ShouldColorize { 332 | clicolor: false, 333 | clicolor_force: None, 334 | has_manual_override: AtomicBool::new(true), 335 | manual_override: AtomicBool::new(true), 336 | }; 337 | 338 | colorize_control.should_colorize(); 339 | }); 340 | 341 | ctx.it("should not colorize if manual_override is false, but clicolor is true or clicolor_force is true", |()| { 342 | let colorize_control = ShouldColorize { 343 | clicolor: true, 344 | clicolor_force: Some(true), 345 | has_manual_override: AtomicBool::new(true), 346 | manual_override: AtomicBool::new(false), 347 | }; 348 | 349 | !colorize_control.should_colorize() 350 | }); 351 | }); 352 | 353 | ctx.specify("::set_override", |ctx| { 354 | ctx.it("should exists", |()| { 355 | let colorize_control = ShouldColorize::default(); 356 | colorize_control.set_override(true); 357 | }); 358 | 359 | ctx.it("set the manual_override property", |()| { 360 | let colorize_control = ShouldColorize::default(); 361 | colorize_control.set_override(true); 362 | { 363 | assert!(colorize_control.has_manual_override.load(Ordering::Relaxed)); 364 | let val = colorize_control.manual_override.load(Ordering::Relaxed); 365 | assert!(val); 366 | } 367 | colorize_control.set_override(false); 368 | { 369 | assert!(colorize_control.has_manual_override.load(Ordering::Relaxed)); 370 | let val = colorize_control.manual_override.load(Ordering::Relaxed); 371 | assert!(!val); 372 | } 373 | }); 374 | }); 375 | 376 | ctx.specify("::unset_override", |ctx| { 377 | ctx.it("should exists", |()| { 378 | let colorize_control = ShouldColorize::default(); 379 | colorize_control.unset_override(); 380 | }); 381 | 382 | ctx.it("unset the manual_override property", |()| { 383 | let colorize_control = ShouldColorize::default(); 384 | colorize_control.set_override(true); 385 | colorize_control.unset_override(); 386 | assert!(!colorize_control.has_manual_override.load(Ordering::Relaxed)); 387 | }); 388 | }); 389 | })); 390 | } 391 | } 392 | -------------------------------------------------------------------------------- /src/color.rs: -------------------------------------------------------------------------------- 1 | use std::{borrow::Cow, cmp, env, str::FromStr}; 2 | use Color::{ 3 | AnsiColor, Black, Blue, BrightBlack, BrightBlue, BrightCyan, BrightGreen, BrightMagenta, 4 | BrightRed, BrightWhite, BrightYellow, Cyan, Green, Magenta, Red, TrueColor, White, Yellow, 5 | }; 6 | /// The 8 standard colors. 7 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] 8 | #[allow(missing_docs)] 9 | pub enum Color { 10 | Black, 11 | Red, 12 | Green, 13 | Yellow, 14 | Blue, 15 | Magenta, 16 | Cyan, 17 | White, 18 | BrightBlack, 19 | BrightRed, 20 | BrightGreen, 21 | BrightYellow, 22 | BrightBlue, 23 | BrightMagenta, 24 | BrightCyan, 25 | BrightWhite, 26 | AnsiColor(u8), 27 | TrueColor { r: u8, g: u8, b: u8 }, 28 | } 29 | 30 | fn truecolor_support() -> bool { 31 | let truecolor = env::var("COLORTERM"); 32 | truecolor.is_ok_and(|truecolor| truecolor == "truecolor" || truecolor == "24bit") 33 | } 34 | 35 | #[allow(missing_docs)] 36 | impl Color { 37 | #[must_use] 38 | pub fn to_fg_str(&self) -> Cow<'static, str> { 39 | match *self { 40 | Self::Black => "30".into(), 41 | Self::Red => "31".into(), 42 | Self::Green => "32".into(), 43 | Self::Yellow => "33".into(), 44 | Self::Blue => "34".into(), 45 | Self::Magenta => "35".into(), 46 | Self::Cyan => "36".into(), 47 | Self::White => "37".into(), 48 | Self::BrightBlack => "90".into(), 49 | Self::BrightRed => "91".into(), 50 | Self::BrightGreen => "92".into(), 51 | Self::BrightYellow => "93".into(), 52 | Self::BrightBlue => "94".into(), 53 | Self::BrightMagenta => "95".into(), 54 | Self::BrightCyan => "96".into(), 55 | Self::BrightWhite => "97".into(), 56 | Self::TrueColor { .. } if !truecolor_support() => { 57 | self.closest_color_euclidean().to_fg_str() 58 | } 59 | Self::AnsiColor(code) => format!("38;5;{code}").into(), 60 | Self::TrueColor { r, g, b } => format!("38;2;{r};{g};{b}").into(), 61 | } 62 | } 63 | 64 | #[must_use] 65 | pub fn to_bg_str(&self) -> Cow<'static, str> { 66 | match *self { 67 | Self::Black => "40".into(), 68 | Self::Red => "41".into(), 69 | Self::Green => "42".into(), 70 | Self::Yellow => "43".into(), 71 | Self::Blue => "44".into(), 72 | Self::Magenta => "45".into(), 73 | Self::Cyan => "46".into(), 74 | Self::White => "47".into(), 75 | Self::BrightBlack => "100".into(), 76 | Self::BrightRed => "101".into(), 77 | Self::BrightGreen => "102".into(), 78 | Self::BrightYellow => "103".into(), 79 | Self::BrightBlue => "104".into(), 80 | Self::BrightMagenta => "105".into(), 81 | Self::BrightCyan => "106".into(), 82 | Self::BrightWhite => "107".into(), 83 | Self::AnsiColor(code) => format!("48;5;{code}").into(), 84 | Self::TrueColor { .. } if !truecolor_support() => { 85 | self.closest_color_euclidean().to_bg_str() 86 | } 87 | Self::TrueColor { r, g, b } => format!("48;2;{r};{g};{b}").into(), 88 | } 89 | } 90 | 91 | /// Gets the closest plain color to the `TrueColor` 92 | fn closest_color_euclidean(self) -> Self { 93 | match self { 94 | TrueColor { 95 | r: r1, 96 | g: g1, 97 | b: b1, 98 | } => { 99 | let colors = vec![ 100 | Black, 101 | Red, 102 | Green, 103 | Yellow, 104 | Blue, 105 | Magenta, 106 | Cyan, 107 | White, 108 | BrightBlack, 109 | BrightRed, 110 | BrightGreen, 111 | BrightYellow, 112 | BrightBlue, 113 | BrightMagenta, 114 | BrightCyan, 115 | BrightWhite, 116 | ] 117 | .into_iter() 118 | .map(|c| (c, c.into_truecolor())); 119 | let distances = colors.map(|(c_original, c)| { 120 | if let TrueColor { r, g, b } = c { 121 | let rd = cmp::max(r, r1) - cmp::min(r, r1); 122 | let gd = cmp::max(g, g1) - cmp::min(g, g1); 123 | let bd = cmp::max(b, b1) - cmp::min(b, b1); 124 | let rd: u32 = rd.into(); 125 | let gd: u32 = gd.into(); 126 | let bd: u32 = bd.into(); 127 | let distance = rd.pow(2) + gd.pow(2) + bd.pow(2); 128 | (c_original, distance) 129 | } else { 130 | unimplemented!("{:?} not a TrueColor", c) 131 | } 132 | }); 133 | distances.min_by(|(_, d1), (_, d2)| d1.cmp(d2)).unwrap().0 134 | } 135 | c => c, 136 | } 137 | } 138 | 139 | fn into_truecolor(self) -> Self { 140 | match self { 141 | Black => TrueColor { r: 0, g: 0, b: 0 }, 142 | Red => TrueColor { r: 205, g: 0, b: 0 }, 143 | Green => TrueColor { r: 0, g: 205, b: 0 }, 144 | Yellow => TrueColor { 145 | r: 205, 146 | g: 205, 147 | b: 0, 148 | }, 149 | Blue => TrueColor { r: 0, g: 0, b: 238 }, 150 | Magenta => TrueColor { 151 | r: 205, 152 | g: 0, 153 | b: 205, 154 | }, 155 | Cyan => TrueColor { 156 | r: 0, 157 | g: 205, 158 | b: 205, 159 | }, 160 | White => TrueColor { 161 | r: 229, 162 | g: 229, 163 | b: 229, 164 | }, 165 | BrightBlack => TrueColor { 166 | r: 127, 167 | g: 127, 168 | b: 127, 169 | }, 170 | BrightRed => TrueColor { r: 255, g: 0, b: 0 }, 171 | BrightGreen => TrueColor { r: 0, g: 255, b: 0 }, 172 | BrightYellow => TrueColor { 173 | r: 255, 174 | g: 255, 175 | b: 0, 176 | }, 177 | BrightBlue => TrueColor { 178 | r: 92, 179 | g: 92, 180 | b: 255, 181 | }, 182 | BrightMagenta => TrueColor { 183 | r: 255, 184 | g: 0, 185 | b: 255, 186 | }, 187 | BrightCyan => TrueColor { 188 | r: 0, 189 | g: 255, 190 | b: 255, 191 | }, 192 | BrightWhite => TrueColor { 193 | r: 255, 194 | g: 255, 195 | b: 255, 196 | }, 197 | AnsiColor(color) => AnsiColor(color), 198 | TrueColor { r, g, b } => TrueColor { r, g, b }, 199 | } 200 | } 201 | } 202 | 203 | impl From<&str> for Color { 204 | fn from(src: &str) -> Self { 205 | src.parse().unwrap_or(Self::White) 206 | } 207 | } 208 | 209 | impl From for Color { 210 | fn from(src: String) -> Self { 211 | src.parse().unwrap_or(Self::White) 212 | } 213 | } 214 | 215 | impl FromStr for Color { 216 | type Err = (); 217 | 218 | fn from_str(src: &str) -> Result { 219 | let src = src.to_lowercase(); 220 | 221 | match src.as_ref() { 222 | "black" => Ok(Self::Black), 223 | "red" => Ok(Self::Red), 224 | "green" => Ok(Self::Green), 225 | "yellow" => Ok(Self::Yellow), 226 | "blue" => Ok(Self::Blue), 227 | "magenta" | "purple" => Ok(Self::Magenta), 228 | "cyan" => Ok(Self::Cyan), 229 | "white" => Ok(Self::White), 230 | "bright black" => Ok(Self::BrightBlack), 231 | "bright red" => Ok(Self::BrightRed), 232 | "bright green" => Ok(Self::BrightGreen), 233 | "bright yellow" => Ok(Self::BrightYellow), 234 | "bright blue" => Ok(Self::BrightBlue), 235 | "bright magenta" => Ok(Self::BrightMagenta), 236 | "bright cyan" => Ok(Self::BrightCyan), 237 | "bright white" => Ok(Self::BrightWhite), 238 | s if s.starts_with('#') => parse_hex(&s[1..]).ok_or(()), 239 | _ => Err(()), 240 | } 241 | } 242 | } 243 | 244 | fn parse_hex(s: &str) -> Option { 245 | if s.len() == 6 { 246 | let r = u8::from_str_radix(&s[0..2], 16).ok()?; 247 | let g = u8::from_str_radix(&s[2..4], 16).ok()?; 248 | let b = u8::from_str_radix(&s[4..6], 16).ok()?; 249 | Some(Color::TrueColor { r, g, b }) 250 | } else if s.len() == 3 { 251 | let r = u8::from_str_radix(&s[0..1], 16).ok()?; 252 | let r = r | (r << 4); 253 | let g = u8::from_str_radix(&s[1..2], 16).ok()?; 254 | let g = g | (g << 4); 255 | let b = u8::from_str_radix(&s[2..3], 16).ok()?; 256 | let b = b | (b << 4); 257 | Some(Color::TrueColor { r, g, b }) 258 | } else { 259 | None 260 | } 261 | } 262 | 263 | #[cfg(test)] 264 | mod tests { 265 | pub use super::*; 266 | 267 | mod from_str { 268 | pub use super::*; 269 | 270 | macro_rules! make_test { 271 | ( $( $name:ident: $src:expr => $dst:expr),* ) => { 272 | 273 | $( 274 | #[test] 275 | fn $name() { 276 | let color : Color = $src.into(); 277 | assert_eq!($dst, color) 278 | } 279 | )* 280 | } 281 | } 282 | 283 | make_test!( 284 | black: "black" => Color::Black, 285 | red: "red" => Color::Red, 286 | green: "green" => Color::Green, 287 | yellow: "yellow" => Color::Yellow, 288 | blue: "blue" => Color::Blue, 289 | magenta: "magenta" => Color::Magenta, 290 | purple: "purple" => Color::Magenta, 291 | cyan: "cyan" => Color::Cyan, 292 | white: "white" => Color::White, 293 | brightblack: "bright black" => Color::BrightBlack, 294 | brightred: "bright red" => Color::BrightRed, 295 | brightgreen: "bright green" => Color::BrightGreen, 296 | brightyellow: "bright yellow" => Color::BrightYellow, 297 | brightblue: "bright blue" => Color::BrightBlue, 298 | brightmagenta: "bright magenta" => Color::BrightMagenta, 299 | brightcyan: "bright cyan" => Color::BrightCyan, 300 | brightwhite: "bright white" => Color::BrightWhite, 301 | 302 | invalid: "invalid" => Color::White, 303 | capitalized: "BLUE" => Color::Blue, 304 | mixed_case: "bLuE" => Color::Blue, 305 | 306 | hex3_lower: "#abc" => Color::TrueColor { r: 170, g: 187, b: 204 }, 307 | hex3_upper: "#ABC" => Color::TrueColor { r: 170, g: 187, b: 204 }, 308 | hex3_mixed: "#aBc" => Color::TrueColor { r: 170, g: 187, b: 204 }, 309 | hex6_lower: "#abcdef" => Color::TrueColor { r: 171, g: 205, b: 239 }, 310 | hex6_upper: "#ABCDEF" => Color::TrueColor { r: 171, g: 205, b: 239 }, 311 | hex6_mixed: "#aBcDeF" => Color::TrueColor { r: 171, g: 205, b: 239 }, 312 | hex_too_short: "#aa" => Color::White, 313 | hex_too_long: "#aaabbbccc" => Color::White, 314 | hex_invalid: "#abcxyz" => Color::White 315 | ); 316 | } 317 | 318 | mod from_string { 319 | pub use super::*; 320 | 321 | macro_rules! make_test { 322 | ( $( $name:ident: $src:expr => $dst:expr),* ) => { 323 | 324 | $( 325 | #[test] 326 | fn $name() { 327 | let src = String::from($src); 328 | let color : Color = src.into(); 329 | assert_eq!($dst, color) 330 | } 331 | )* 332 | } 333 | } 334 | 335 | make_test!( 336 | black: "black" => Color::Black, 337 | red: "red" => Color::Red, 338 | green: "green" => Color::Green, 339 | yellow: "yellow" => Color::Yellow, 340 | blue: "blue" => Color::Blue, 341 | magenta: "magenta" => Color::Magenta, 342 | cyan: "cyan" => Color::Cyan, 343 | white: "white" => Color::White, 344 | brightblack: "bright black" => Color::BrightBlack, 345 | brightred: "bright red" => Color::BrightRed, 346 | brightgreen: "bright green" => Color::BrightGreen, 347 | brightyellow: "bright yellow" => Color::BrightYellow, 348 | brightblue: "bright blue" => Color::BrightBlue, 349 | brightmagenta: "bright magenta" => Color::BrightMagenta, 350 | brightcyan: "bright cyan" => Color::BrightCyan, 351 | brightwhite: "bright white" => Color::BrightWhite, 352 | 353 | invalid: "invalid" => Color::White, 354 | capitalized: "BLUE" => Color::Blue, 355 | mixed_case: "bLuE" => Color::Blue, 356 | 357 | hex3_lower: "#abc" => Color::TrueColor { r: 170, g: 187, b: 204 }, 358 | hex3_upper: "#ABC" => Color::TrueColor { r: 170, g: 187, b: 204 }, 359 | hex3_mixed: "#aBc" => Color::TrueColor { r: 170, g: 187, b: 204 }, 360 | hex6_lower: "#abcdef" => Color::TrueColor { r: 171, g: 205, b: 239 }, 361 | hex6_upper: "#ABCDEF" => Color::TrueColor { r: 171, g: 205, b: 239 }, 362 | hex6_mixed: "#aBcDeF" => Color::TrueColor { r: 171, g: 205, b: 239 }, 363 | hex_too_short: "#aa" => Color::White, 364 | hex_too_long: "#aaabbbccc" => Color::White, 365 | hex_invalid: "#abcxyz" => Color::White 366 | ); 367 | } 368 | 369 | mod fromstr { 370 | pub use super::*; 371 | 372 | #[test] 373 | fn parse() { 374 | let color: Result = "blue".parse(); 375 | assert_eq!(Ok(Color::Blue), color); 376 | } 377 | 378 | #[test] 379 | fn error() { 380 | let color: Result = "bloublou".parse(); 381 | assert_eq!(Err(()), color); 382 | } 383 | } 384 | 385 | mod closest_euclidean { 386 | use super::*; 387 | 388 | macro_rules! make_euclidean_distance_test { 389 | ( $test:ident : ( $r:literal, $g: literal, $b:literal ), $expected:expr ) => { 390 | #[test] 391 | fn $test() { 392 | let true_color = Color::TrueColor { 393 | r: $r, 394 | g: $g, 395 | b: $b, 396 | }; 397 | let actual = true_color.closest_color_euclidean(); 398 | assert_eq!(actual, $expected); 399 | } 400 | }; 401 | } 402 | 403 | make_euclidean_distance_test! { exact_black: (0, 0, 0), Color::Black } 404 | make_euclidean_distance_test! { exact_red: (205, 0, 0), Color::Red } 405 | make_euclidean_distance_test! { exact_green: (0, 205, 0), Color::Green } 406 | make_euclidean_distance_test! { exact_yellow: (205, 205, 0), Color::Yellow } 407 | make_euclidean_distance_test! { exact_blue: (0, 0, 238), Color::Blue } 408 | make_euclidean_distance_test! { exact_magenta: (205, 0, 205), Color::Magenta } 409 | make_euclidean_distance_test! { exact_cyan: (0, 205, 205), Color::Cyan } 410 | make_euclidean_distance_test! { exact_white: (229, 229, 229), Color::White } 411 | 412 | make_euclidean_distance_test! { almost_black: (10, 15, 10), Color::Black } 413 | make_euclidean_distance_test! { almost_red: (215, 10, 10), Color::Red } 414 | make_euclidean_distance_test! { almost_green: (10, 195, 10), Color::Green } 415 | make_euclidean_distance_test! { almost_yellow: (195, 215, 10), Color::Yellow } 416 | make_euclidean_distance_test! { almost_blue: (0, 0, 200), Color::Blue } 417 | make_euclidean_distance_test! { almost_magenta: (215, 0, 195), Color::Magenta } 418 | make_euclidean_distance_test! { almost_cyan: (10, 215, 215), Color::Cyan } 419 | make_euclidean_distance_test! { almost_white: (209, 209, 229), Color::White } 420 | } 421 | } 422 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /src/style.rs: -------------------------------------------------------------------------------- 1 | use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not}; 2 | 3 | macro_rules! auto_impl_ref_binop_trait { 4 | (impl $trait_name:ident, $method:ident for $t:ty, $u:ty) => { 5 | impl $trait_name<&$u> for $t { 6 | type Output = <$t as $trait_name<$t>>::Output; 7 | 8 | #[inline] 9 | fn $method(self, rhs: &$u) -> Self::Output { 10 | $trait_name::$method(self, *rhs) 11 | } 12 | } 13 | 14 | impl $trait_name<$u> for &$t { 15 | type Output = <$t as $trait_name<$t>>::Output; 16 | 17 | #[inline] 18 | fn $method(self, rhs: $u) -> Self::Output { 19 | $trait_name::$method(*self, rhs) 20 | } 21 | } 22 | 23 | impl $trait_name<&$u> for &$t { 24 | type Output = <$t as $trait_name<$t>>::Output; 25 | 26 | #[inline] 27 | fn $method(self, rhs: &$u) -> Self::Output { 28 | $trait_name::$method(*self, *rhs) 29 | } 30 | } 31 | }; 32 | } 33 | 34 | macro_rules! impl_assign_op_trait { 35 | ( 36 | $trait:ident, $method:ident for $t:ty, $u:ty, using $used_trait:ident::$used_method:ident 37 | ) => { 38 | impl $trait<$u> for $t { 39 | #[inline] 40 | fn $method(&mut self, other: $u) { 41 | *self = $used_trait::$used_method(&*self, other); 42 | } 43 | } 44 | 45 | impl $trait<&$u> for $t { 46 | #[inline] 47 | fn $method(&mut self, other: &$u) { 48 | *self = $used_trait::$used_method(&*self, other); 49 | } 50 | } 51 | }; 52 | } 53 | 54 | const CLEARV: u8 = 0b0000_0000; 55 | const BOLD: u8 = 0b0000_0001; 56 | const UNDERLINE: u8 = 0b0000_0010; 57 | const REVERSED: u8 = 0b0000_0100; 58 | const ITALIC: u8 = 0b0000_1000; 59 | const BLINK: u8 = 0b0001_0000; 60 | const HIDDEN: u8 = 0b0010_0000; 61 | const DIMMED: u8 = 0b0100_0000; 62 | const STRIKETHROUGH: u8 = 0b1000_0000; 63 | 64 | static STYLES: [(u8, Styles); 8] = [ 65 | (BOLD, Styles::Bold), 66 | (DIMMED, Styles::Dimmed), 67 | (UNDERLINE, Styles::Underline), 68 | (REVERSED, Styles::Reversed), 69 | (ITALIC, Styles::Italic), 70 | (BLINK, Styles::Blink), 71 | (HIDDEN, Styles::Hidden), 72 | (STRIKETHROUGH, Styles::Strikethrough), 73 | ]; 74 | 75 | pub static CLEAR: Style = Style(CLEARV); 76 | 77 | /// A combinatorial style such as bold, italics, dimmed, etc. 78 | /// 79 | /// ## Creation 80 | /// 81 | /// `Style::default()` returns a `Style` with no style switches 82 | /// activated and is the default method of creating a plain `Style`. 83 | /// 84 | /// ## `Style` from a set of `Styles`s / `Styles` iterator 85 | /// 86 | /// `Style` implements `FromIter` which means that it is 87 | /// possible to do the following: 88 | /// 89 | /// ```rust 90 | /// # use colored::*; 91 | /// let style = Style::from_iter([Styles::Bold, Styles::Italic, Styles::Strikethrough]); 92 | /// for styles in [Styles::Bold, Styles::Italic, Styles::Strikethrough] { 93 | /// assert!(style.contains(styles)); 94 | /// } 95 | /// ``` 96 | /// 97 | /// As you can see, this is a good thing to keep in mind, although for 98 | /// most cases, where you're not setting styles dynamically and are 99 | /// simply creating a pre-defined set of styles, using [`Default`] and 100 | /// then using the builder-style methods is likely prettier. 101 | /// 102 | /// ```rust 103 | /// # use colored::*; 104 | /// let many_styles = Style::default() 105 | /// .bold() 106 | /// .underline() 107 | /// .italic() 108 | /// .blink(); 109 | /// ``` 110 | /// 111 | /// ## Implementation of logical bitwise operators 112 | /// 113 | /// `Style` implements bitwise logical operations that operate on 114 | /// the held style switches collectively. By far the most common 115 | /// and useful is the bitwise 'or' operator `|` which combines two 116 | /// styles, merging their combined styles into one. Example: 117 | /// 118 | /// ```rust 119 | /// # use colored::*; 120 | /// let only_bold = Style::from(Styles::Bold); 121 | /// // This line is actually an example of `Styles`'s bitwise logic impls but still. 122 | /// let underline_and_italic = Styles::Underline | Styles::Italic; 123 | /// let all_three = only_bold | underline_and_italic; 124 | /// 125 | /// assert!(all_three.contains(Styles::Bold) 126 | /// && all_three.contains(Styles::Underline) 127 | /// && all_three.contains(Styles::Italic)); 128 | /// ``` 129 | /// 130 | /// This functionality also allows for easily turning off styles 131 | /// of one `Styles` using another by combining the `&` and `!` 132 | /// operators. 133 | /// 134 | /// ```rust 135 | /// # use colored::*; 136 | /// let mut very_loud_style = Style::default() 137 | /// .bold() 138 | /// .underline() 139 | /// .italic() 140 | /// .strikethrough() 141 | /// .hidden(); 142 | /// 143 | /// // Oops! Some of those should not be in there! 144 | /// // This Style now has all styles _except_ the two we don't want 145 | /// // (hidden and strikethough). 146 | /// let remove_mask = 147 | /// !Style::from_iter([Styles::Hidden, Styles::Strikethrough]); 148 | /// very_loud_style &= remove_mask; 149 | /// 150 | /// // `very_loud_style` no longer contains the undesired style 151 | /// // switches... 152 | /// assert!(!very_loud_style.contains(Styles::Hidden) 153 | /// && !very_loud_style.contains(Styles::Strikethrough)); 154 | /// // ...but it retains everything else! 155 | /// assert!(very_loud_style.contains(Styles::Bold)); 156 | /// ``` 157 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] 158 | pub struct Style(u8); 159 | 160 | /// Enum containing all of the available style settings that can be 161 | /// applied to a [`Styles`] and by extension, a colrized type. 162 | /// 163 | /// ## Implementation of bitwise logical operators 164 | /// 165 | /// The implementations of [`BitAnd`], [`BitOr`], [`BitXor`], and 166 | /// [`Not`] are really extensions of [`Style`]'s implementations of 167 | /// the same. [`BitOr`] is great for starting chains of `Styles`'s 168 | /// for creating [`Style`]'s. 169 | /// 170 | /// ``` 171 | /// # use colored::*; 172 | /// let my_styles = 173 | /// // BitOr for Styles (Styles | Styles) = Style 174 | /// Styles::Bold | Styles::Underline 175 | /// // BitOr for Style (Style | Styles) = Style 176 | /// | Styles::Italic; 177 | /// 178 | /// for s in [Styles::Bold, Styles::Underline, Styles::Italic] { 179 | /// assert!(my_styles.contains(s)); 180 | /// } 181 | /// ``` 182 | /// 183 | /// [`Not`] has far fewer use cases but can still find use in 184 | /// turning a `Styles` into a [`Style`] with all styles activated 185 | /// except that `Styles`. 186 | /// 187 | /// ``` 188 | /// # use colored::*; 189 | /// let everything_but_bold = !Styles::Bold; 190 | /// 191 | /// assert!(everything_but_bold.contains(Styles::Underline)); 192 | /// assert!(everything_but_bold.contains(Styles::Strikethrough)); 193 | /// assert!(!everything_but_bold.contains(Styles::Bold)); 194 | /// ``` 195 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] 196 | #[allow(missing_docs)] 197 | pub enum Styles { 198 | Clear, 199 | Bold, 200 | Dimmed, 201 | Underline, 202 | Reversed, 203 | Italic, 204 | Blink, 205 | Hidden, 206 | Strikethrough, 207 | } 208 | 209 | impl Styles { 210 | fn to_str<'a>(self) -> &'a str { 211 | match self { 212 | Self::Clear => "", // unreachable, but we don't want to panic 213 | Self::Bold => "1", 214 | Self::Dimmed => "2", 215 | Self::Italic => "3", 216 | Self::Underline => "4", 217 | Self::Blink => "5", 218 | Self::Reversed => "7", 219 | Self::Hidden => "8", 220 | Self::Strikethrough => "9", 221 | } 222 | } 223 | 224 | fn to_u8(self) -> u8 { 225 | match self { 226 | Self::Clear => CLEARV, 227 | Self::Bold => BOLD, 228 | Self::Dimmed => DIMMED, 229 | Self::Italic => ITALIC, 230 | Self::Underline => UNDERLINE, 231 | Self::Blink => BLINK, 232 | Self::Reversed => REVERSED, 233 | Self::Hidden => HIDDEN, 234 | Self::Strikethrough => STRIKETHROUGH, 235 | } 236 | } 237 | 238 | fn from_u8(u: u8) -> Option> { 239 | if u == CLEARV { 240 | return None; 241 | } 242 | 243 | let res: Vec = STYLES 244 | .iter() 245 | .filter(|&(mask, _)| (0 != (u & mask))) 246 | .map(|&(_, value)| value) 247 | .collect(); 248 | if res.is_empty() { 249 | None 250 | } else { 251 | Some(res) 252 | } 253 | } 254 | } 255 | 256 | impl BitAnd for Styles { 257 | type Output = Style; 258 | 259 | fn bitand(self, rhs: Self) -> Self::Output { 260 | Style(self.to_u8() & rhs.to_u8()) 261 | } 262 | } 263 | 264 | auto_impl_ref_binop_trait!(impl BitAnd, bitand for Styles, Styles); 265 | 266 | impl BitAnd