#[derive(Debug, Clone, PartialEq)]
pub struct StyleOpt {
pub fg: Option<Fg>,
pub bg: Option<Bg>,
pub sgr: Option<Sgr>,
}
impl StyleOpt {
pub fn new() -> Self {
Self::default()
}
pub fn fg(self, fg: Fg) -> Self {
Self { fg: Some(fg), ..self }
}
pub fn bg(self, bg: Bg) -> Self {
Self { bg: Some(bg), ..self }
}
pub fn sgr(self, sgr: Sgr) -> Self {
Self { sgr: Some(sgr), ..self }
}
}
impl Default for StyleOpt {
fn default() -> StyleOpt {
Self { fg: None, bg: None, sgr: None }
}
}
pub fn stylize(s: &str, opt: &StyleOpt) -> String {
format!("{fg}{bg}{sgr}{text}{reset}",
fg = match opt.fg.as_ref() {
None => "",
Some(fg) => fg.escape_code(),
},
bg = match opt.bg.as_ref() {
None => "",
Some(bg) => bg.escape_code(),
},
sgr = match opt.sgr.as_ref() {
None => "",
Some(sgr) => sgr.escape_code(),
},
text = s,
reset = Fg::Reset.escape_code(),
)
}
#[derive(Debug, Clone, PartialEq)]
pub enum Fg {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
BrightBlack,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
BrightWhite,
Reset,
}
impl Fg {
pub fn escape_code(&self) -> &'static str {
match self {
Self::Black => "\x1b[1;30m",
Self::Red => "\x1b[1;31m",
Self::Green => "\x1b[1;32m",
Self::Yellow => "\x1b[1;33m",
Self::Blue => "\x1b[1;34m",
Self::Magenta => "\x1b[1;35m",
Self::Cyan => "\x1b[1;36m",
Self::White => "\x1b[1;37m",
Self::BrightBlack => "\x1b[1;90m",
Self::BrightRed => "\x1b[1;91m",
Self::BrightGreen => "\x1b[1;92m",
Self::BrightYellow => "\x1b[1;93m",
Self::BrightBlue => "\x1b[1;94m",
Self::BrightMagenta => "\x1b[1;95m",
Self::BrightCyan => "\x1b[1;96m",
Self::BrightWhite => "\x1b[1;97m",
Self::Reset => "\x1b[1;0m",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Bg {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
BrightBlack,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
BrightWhite,
Reset,
}
impl Bg {
pub fn escape_code(&self) -> &'static str {
match self {
Self::Black => "\x1b[1;40m",
Self::Red => "\x1b[1;41m",
Self::Green => "\x1b[1;42m",
Self::Yellow => "\x1b[1;43m",
Self::Blue => "\x1b[1;44m",
Self::Magenta => "\x1b[1;45m",
Self::Cyan => "\x1b[1;46m",
Self::White => "\x1b[1;47m",
Self::BrightBlack => "\x1b[1;100m",
Self::BrightRed => "\x1b[1;101m",
Self::BrightGreen => "\x1b[1;102m",
Self::BrightYellow => "\x1b[1;103m",
Self::BrightBlue => "\x1b[1;104m",
Self::BrightMagenta => "\x1b[1;105m",
Self::BrightCyan => "\x1b[1;106m",
Self::BrightWhite => "\x1b[1;107m",
Self::Reset => "\x1b[1;0m",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Sgr {
Bold,
Faint,
Italic,
Underline,
StrikeThrough,
Reset,
}
impl Sgr {
pub fn escape_code(&self) -> &'static str {
match self {
Self::Bold => "\x1b[1;1m",
Self::Faint => "\x1b[1;2m",
Self::Italic => "\x1b[1;3m",
Self::Underline => "\x1b[1;4m",
Self::StrikeThrough => "\x1b[1;9m",
Self::Reset => "\x1b[1;0m",
}
}
}