Skip to content

Commit

Permalink
Merge pull request #72 from dalance/color256
Browse files Browse the repository at this point in the history
Add 256 colors support
  • Loading branch information
pksunkara authored Aug 10, 2020
2 parents a3caa55 + 9f05773 commit 4638d56
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
17 changes: 17 additions & 0 deletions examples/colors256.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use console::style;

fn main() {
for i in 0..=255 {
print!("{:03} ", style(i).color256(i));
if i % 16 == 15 {
println!("");
}
}

for i in 0..=255 {
print!("{:03} ", style(i).black().on_color256(i));
if i % 16 == 15 {
println!("");
}
}
}
34 changes: 32 additions & 2 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ pub enum Color {
Magenta,
Cyan,
White,
Color256(u8),
}

impl Color {
Expand All @@ -97,6 +98,15 @@ impl Color {
Color::Magenta => 5,
Color::Cyan => 6,
Color::White => 7,
Color::Color256(x) => x as usize,
}
}

#[inline]
fn is_color256(self) -> bool {
match self {
Color::Color256(_) => true,
_ => false,
}
}
}
Expand Down Expand Up @@ -296,6 +306,10 @@ impl Style {
pub fn white(self) -> Style {
self.fg(Color::White)
}
#[inline]
pub fn color256(self, color: u8) -> Style {
self.fg(Color::Color256(color))
}

#[inline]
pub fn bright(mut self) -> Style {
Expand Down Expand Up @@ -335,6 +349,10 @@ impl Style {
pub fn on_white(self) -> Style {
self.bg(Color::White)
}
#[inline]
pub fn on_color256(self, color: u8) -> Style {
self.bg(Color::Color256(color))
}

#[inline]
pub fn on_bright(mut self) -> Style {
Expand Down Expand Up @@ -478,6 +496,10 @@ impl<D> StyledObject<D> {
pub fn white(self) -> StyledObject<D> {
self.fg(Color::White)
}
#[inline]
pub fn color256(self, color: u8) -> StyledObject<D> {
self.fg(Color::Color256(color))
}

#[inline]
pub fn bright(mut self) -> StyledObject<D> {
Expand Down Expand Up @@ -517,6 +539,10 @@ impl<D> StyledObject<D> {
pub fn on_white(self) -> StyledObject<D> {
self.bg(Color::White)
}
#[inline]
pub fn on_color256(self, color: u8) -> StyledObject<D> {
self.bg(Color::Color256(color))
}

#[inline]
pub fn on_bright(mut self) -> StyledObject<D> {
Expand Down Expand Up @@ -568,15 +594,19 @@ macro_rules! impl_fmt {
})
{
if let Some(fg) = self.style.fg {
if self.style.fg_bright {
if fg.is_color256() {
write!(f, "\x1b[38;5;{}m", fg.ansi_num())?;
} else if self.style.fg_bright {
write!(f, "\x1b[38;5;{}m", fg.ansi_num() + 8)?;
} else {
write!(f, "\x1b[{}m", fg.ansi_num() + 30)?;
}
reset = true;
}
if let Some(bg) = self.style.bg {
if self.style.bg_bright {
if bg.is_color256() {
write!(f, "\x1b[48;5;{}m", bg.ansi_num())?;
} else if self.style.bg_bright {
write!(f, "\x1b[48;5;{}m", bg.ansi_num() + 8)?;
} else {
write!(f, "\x1b[{}m", bg.ansi_num() + 40)?;
Expand Down

0 comments on commit 4638d56

Please sign in to comment.