anstyle_termcolor/
lib.rs

1//! Convert between [termcolor](https://lib.rs/termcolor) and [generic styling types][anstyle]
2
3#![cfg_attr(docsrs, feature(doc_auto_cfg))]
4#![warn(missing_docs)]
5#![warn(clippy::print_stderr)]
6#![warn(clippy::print_stdout)]
7
8/// Adapt generic styling to [`termcolor`]
9pub fn to_termcolor_spec(style: anstyle::Style) -> termcolor::ColorSpec {
10    let fg = style.get_fg_color().map(to_termcolor_color);
11    let bg = style.get_bg_color().map(to_termcolor_color);
12    let effects = style.get_effects();
13
14    let mut style = termcolor::ColorSpec::new();
15    style.set_fg(fg);
16    style.set_bg(bg);
17    style.set_bold(effects.contains(anstyle::Effects::BOLD));
18    style.set_dimmed(effects.contains(anstyle::Effects::DIMMED));
19    style.set_italic(effects.contains(anstyle::Effects::ITALIC));
20    style.set_underline(effects.contains(anstyle::Effects::UNDERLINE));
21    style
22}
23
24/// Adapt generic colors to [`termcolor`]
25pub fn to_termcolor_color(color: anstyle::Color) -> termcolor::Color {
26    match color {
27        anstyle::Color::Ansi(ansi) => ansi_to_termcolor_color(ansi),
28        anstyle::Color::Ansi256(xterm) => xterm_to_termcolor_color(xterm),
29        anstyle::Color::Rgb(rgb) => rgb_to_termcolor_color(rgb),
30    }
31}
32
33fn ansi_to_termcolor_color(color: anstyle::AnsiColor) -> termcolor::Color {
34    match color {
35        anstyle::AnsiColor::Black => termcolor::Color::Black,
36        anstyle::AnsiColor::Red => termcolor::Color::Red,
37        anstyle::AnsiColor::Green => termcolor::Color::Green,
38        anstyle::AnsiColor::Yellow => termcolor::Color::Yellow,
39        anstyle::AnsiColor::Blue => termcolor::Color::Blue,
40        anstyle::AnsiColor::Magenta => termcolor::Color::Magenta,
41        anstyle::AnsiColor::Cyan => termcolor::Color::Cyan,
42        anstyle::AnsiColor::White => termcolor::Color::White,
43        anstyle::AnsiColor::BrightBlack => termcolor::Color::Black,
44        anstyle::AnsiColor::BrightRed => termcolor::Color::Red,
45        anstyle::AnsiColor::BrightGreen => termcolor::Color::Green,
46        anstyle::AnsiColor::BrightYellow => termcolor::Color::Yellow,
47        anstyle::AnsiColor::BrightBlue => termcolor::Color::Black,
48        anstyle::AnsiColor::BrightMagenta => termcolor::Color::Magenta,
49        anstyle::AnsiColor::BrightCyan => termcolor::Color::Cyan,
50        anstyle::AnsiColor::BrightWhite => termcolor::Color::White,
51    }
52}
53
54fn xterm_to_termcolor_color(color: anstyle::Ansi256Color) -> termcolor::Color {
55    termcolor::Color::Ansi256(color.0)
56}
57
58fn rgb_to_termcolor_color(color: anstyle::RgbColor) -> termcolor::Color {
59    termcolor::Color::Rgb(color.0, color.1, color.2)
60}
61
62#[doc = include_str!("../README.md")]
63#[cfg(doctest)]
64pub struct ReadmeDoctests;