//! ANSI color, style, and painted-display support. //! //! The rest of the crate stores style as data and only turns it into escape //! sequences at explicit formatting boundaries. This module is derived from //! the `yansi` crate. //! Copyright (c) 2017 Sergio Benitez //! use std::borrow::Cow; /// ANSI color type. mod color; /// Styled display wrapper. mod paint; /// ANSI style properties. mod style; pub use color::Color; pub use paint::Filled; pub use paint::Paint; pub use paint::PaintMode; pub use paint::Painted; pub use paint::paint; pub use style::Style; /// Removes ANSI control sequences from text. pub fn strip(input: &str) -> Cow<'_, str> { if !input.as_bytes().contains(&b'\x1b') { return Cow::Borrowed(input); } let mut output = String::with_capacity(input.len()); let mut chars = input.chars().peekable(); while let Some(ch) = chars.next() { if ch != '\x1b' { output.push(ch); continue; } match chars.peek().copied() { Some('[') => { chars.next(); for ch in chars.by_ref() { if ('\u{40}'..='\u{7e}').contains(&ch) { break; } } } Some(']') => { chars.next(); while let Some(ch) = chars.next() { if ch == '\u{7}' { break; } if ch == '\x1b' && chars.peek() == Some(&'\\') { chars.next(); break; } } } Some(_) => { chars.next(); } None => {} } } Cow::Owned(output) } #[cfg(test)] mod tests { use super::*; #[test] fn strip_borrows_plain_text() { let stripped = strip("plain text"); assert!(matches!(stripped, Cow::Borrowed("plain text"))); } #[test] fn strip_removes_csi_sequences() { assert_eq!( strip("\x1b[33mdiff --git a/f b/f\x1b[m").as_ref(), "diff --git a/f b/f" ); } #[test] fn strip_removes_osc_sequences() { assert_eq!( strip("a\x1b]8;;https://example.invalid\x07link\x1b]8;;\x07b").as_ref(), "alinkb" ); } }