Skip to content

Commit

Permalink
Add support for arbitrary ANSI color
Browse files Browse the repository at this point in the history
  • Loading branch information
Asthowen committed Jan 14, 2025
1 parent 95b2de8 commit 9864b35
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Unreleased
- Added methods `ansi_color` and `on_ansi_color` to `Colorize`.

# 3.0.0
- **[BREAKING CHANGE]:** Upgrade MSRV to 1.80 and remove the then unnecessary lazy_static dependency.
Expand Down
4 changes: 4 additions & 0 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub enum Color {
BrightCyan,
BrightWhite,
TrueColor { r: u8, g: u8, b: u8 },
AnsiColor(u8),
}

fn truecolor_support() -> bool {
Expand Down Expand Up @@ -56,6 +57,7 @@ impl Color {
self.closest_color_euclidean().to_fg_str()
}
Color::TrueColor { r, g, b } => format!("38;2;{};{};{}", r, g, b).into(),
Color::AnsiColor(code) => format!("38;5;{}", code).into(),
}
}

Expand All @@ -81,6 +83,7 @@ impl Color {
self.closest_color_euclidean().to_bg_str()
}
Color::TrueColor { r, g, b } => format!("48;2;{};{};{}", r, g, b).into(),
Color::AnsiColor(code) => format!("48;5;{}", code).into(),
}
}

Expand Down Expand Up @@ -195,6 +198,7 @@ impl Color {
b: 255,
},
TrueColor { r, g, b } => TrueColor { r, g, b },
AnsiColor(color) => AnsiColor(color),
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,13 @@ pub trait Colorize {
b: color.b,
})
}
fn ansi_color<T>(self, color: T) -> ColoredString
where
Self: Sized,
T: Into<u8>,
{
self.color(Color::AnsiColor(color.into()))
}
fn color<S: Into<Color>>(self, color: S) -> ColoredString;
// Background Colors
fn on_black(self) -> ColoredString
Expand Down Expand Up @@ -397,6 +404,13 @@ pub trait Colorize {
b: color.b,
})
}
fn on_ansi_color<T>(self, color: T) -> ColoredString
where
Self: Sized,
T: Into<u8>,
{
self.on_color(Color::AnsiColor(color.into()))
}
fn on_color<S: Into<Color>>(self, color: S) -> ColoredString;
// Styles
fn clear(self) -> ColoredString;
Expand Down

0 comments on commit 9864b35

Please sign in to comment.