#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Color {
Ansi(u8),
Palette(u8),
Rgb(u8, u8, u8),
}
impl Color {
pub const BLACK: Self = Self::Ansi(0);
pub const RED: Self = Self::Ansi(1);
pub const GREEN: Self = Self::Ansi(2);
pub const YELLOW: Self = Self::Ansi(3);
pub const BLUE: Self = Self::Ansi(4);
pub const MAGENTA: Self = Self::Ansi(5);
pub const CYAN: Self = Self::Ansi(6);
pub const WHITE: Self = Self::Ansi(7);
pub const GREY: Self = Self::Ansi(8);
fn sgr(self, background: bool) -> String {
match self {
Self::Ansi(n) => {
let base = match (background, n < 8) {
(false, true) => 30,
(false, false) => 90 - 8,
(true, true) => 40,
(true, false) => 100 - 8,
};
(base + u16::from(n.min(15))).to_string()
}
Self::Palette(n) => format!("{};5;{n}", if background { 48 } else { 38 }),
Self::Rgb(r, g, b) => format!("{};2;{r};{g};{b}", if background { 48 } else { 38 }),
}
}
}
const BOLD: u8 = 1;
const DIM: u8 = 1 << 1;
const ITALIC: u8 = 1 << 2;
const UNDERLINE: u8 = 1 << 3;
const REVERSE: u8 = 1 << 4;
const ATTRIBUTES: [(u8, &str); 5] = [
(BOLD, "1"),
(DIM, "2"),
(ITALIC, "3"),
(UNDERLINE, "4"),
(REVERSE, "7"),
];
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Style {
fg: Option<Color>,
bg: Option<Color>,
attributes: u8,
}
impl Style {
#[must_use]
pub const fn new() -> Self {
Self {
fg: None,
bg: None,
attributes: 0,
}
}
#[must_use]
pub const fn fg(mut self, color: Color) -> Self {
self.fg = Some(color);
self
}
#[must_use]
pub const fn bg(mut self, color: Color) -> Self {
self.bg = Some(color);
self
}
#[must_use]
pub const fn bold(self) -> Self {
self.with(BOLD)
}
#[must_use]
pub const fn dim(self) -> Self {
self.with(DIM)
}
#[must_use]
pub const fn italic(self) -> Self {
self.with(ITALIC)
}
#[must_use]
pub const fn underline(self) -> Self {
self.with(UNDERLINE)
}
#[must_use]
pub const fn reverse(self) -> Self {
self.with(REVERSE)
}
const fn with(mut self, bit: u8) -> Self {
self.attributes |= bit;
self
}
#[must_use]
pub fn paint(&self, text: &str) -> String {
let codes = self.codes();
if codes.is_empty() {
text.to_string()
} else {
format!("\x1b[{}m{text}\x1b[0m", codes.join(";"))
}
}
fn codes(&self) -> Vec<String> {
let mut codes: Vec<String> = ATTRIBUTES
.iter()
.filter(|(bit, _)| self.attributes & bit != 0)
.map(|(_, c)| (*c).to_string())
.collect();
codes.extend(self.fg.map(|c| c.sgr(false)));
codes.extend(self.bg.map(|c| c.sgr(true)));
codes
}
}
pub use crate::unicode::WidthMethod;
use crate::ansi::{Token, spans};
use std::sync::atomic::{AtomicBool, Ordering};
static GRAPHEME_WIDTH: AtomicBool = AtomicBool::new(false);
#[must_use]
pub fn width_method() -> WidthMethod {
if GRAPHEME_WIDTH.load(Ordering::Relaxed) {
WidthMethod::GraphemeWidth
} else {
WidthMethod::WcWidth
}
}
pub(crate) fn set_width_method(method: WidthMethod) {
GRAPHEME_WIDTH.store(method == WidthMethod::GraphemeWidth, Ordering::Relaxed);
}
#[must_use]
pub fn width(text: &str) -> usize {
width_method().string_width(text)
}
#[must_use]
pub fn strip_ansi(text: &str) -> String {
spans(text, WidthMethod::WcWidth)
.filter(|(token, _)| matches!(token, Token::Text(..) | Token::Control(_)))
.map(|(_, raw)| raw)
.collect()
}
#[must_use]
pub fn truncate(text: &str, columns: usize) -> String {
let method = width_method();
if method.string_width(text) <= columns {
return text.to_string();
}
let mut out = String::with_capacity(text.len());
let mut room = Some(columns);
for (token, raw) in spans(text, method) {
if keep(token, &mut room) {
out.push_str(raw);
}
}
out + "\x1b[0m"
}
fn keep(token: Token<'_>, room: &mut Option<usize>) -> bool {
match (token, *room) {
(Token::Text(_, w), Some(left)) if w <= left => {
*room = Some(left - w);
true
}
(Token::Text(..), _) => {
*room = None;
false
}
(Token::Control(_), None) => false,
_ => true,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_plain_style_leaves_text_alone() {
assert_eq!(Style::new().paint("hi"), "hi");
}
#[test]
fn styles_become_sgr_codes() {
assert_eq!(
Style::new().bold().fg(Color::RED).paint("x"),
"\x1b[1;31mx\x1b[0m"
);
assert_eq!(
Style::new()
.fg(Color::Ansi(9))
.bg(Color::Ansi(12))
.paint("x"),
"\x1b[91;104mx\x1b[0m"
);
assert_eq!(
Style::new().fg(Color::Palette(208)).paint("x"),
"\x1b[38;5;208mx\x1b[0m"
);
assert_eq!(
Style::new().bg(Color::Rgb(1, 2, 3)).paint("x"),
"\x1b[48;2;1;2;3mx\x1b[0m"
);
assert_eq!(
Style::new().dim().italic().underline().reverse().paint("x"),
"\x1b[2;3;4;7mx\x1b[0m"
);
}
#[test]
fn width_ignores_escape_sequences() {
let s = Style::new().bold().fg(Color::GREEN).paint("héllo");
assert_eq!(width(&s), 5);
assert_eq!(strip_ansi(&s), "héllo");
}
#[test]
fn width_counts_wide_characters_twice() {
assert_eq!(width("字a"), 3);
assert_eq!(width("e\u{301}"), 1);
assert_eq!(
truncate("字字", 3),
"字\x1b[0m",
"a wide character is not split"
);
assert_eq!(width_method(), WidthMethod::WcWidth);
}
#[test]
fn truncation_keeps_styles_and_resets() {
assert_eq!(truncate("hello", 10), "hello");
assert_eq!(truncate("hello", 3), "hel\x1b[0m");
let styled = Style::new().bold().paint("hello");
assert_eq!(strip_ansi(&truncate(&styled, 2)), "he");
assert!(truncate(&styled, 2).ends_with("\x1b[0m"));
}
}