crates/tui-core/src/ansi.rs 2.3 KiB raw
1
//! ANSI color, style, and painted-display support.
2
//!
3
//! The rest of the crate stores style as data and only turns it into escape
4
//! sequences at explicit formatting boundaries. This module is derived from
5
//! the `yansi` crate.
6
//! Copyright (c) 2017 Sergio Benitez
7
//!
8
9
use std::borrow::Cow;
10
11
/// ANSI color type.
12
mod color;
13
/// Styled display wrapper.
14
mod paint;
15
/// ANSI style properties.
16
mod style;
17
18
pub use color::Color;
19
pub use paint::Filled;
20
pub use paint::Paint;
21
pub use paint::PaintMode;
22
pub use paint::Painted;
23
pub use paint::paint;
24
pub use style::Style;
25
26
/// Removes ANSI control sequences from text.
27
pub fn strip(input: &str) -> Cow<'_, str> {
28
    if !input.as_bytes().contains(&b'\x1b') {
29
        return Cow::Borrowed(input);
30
    }
31
    let mut output = String::with_capacity(input.len());
32
    let mut chars = input.chars().peekable();
33
34
    while let Some(ch) = chars.next() {
35
        if ch != '\x1b' {
36
            output.push(ch);
37
            continue;
38
        }
39
40
        match chars.peek().copied() {
41
            Some('[') => {
42
                chars.next();
43
                for ch in chars.by_ref() {
44
                    if ('\u{40}'..='\u{7e}').contains(&ch) {
45
                        break;
46
                    }
47
                }
48
            }
49
            Some(']') => {
50
                chars.next();
51
                while let Some(ch) = chars.next() {
52
                    if ch == '\u{7}' {
53
                        break;
54
                    }
55
                    if ch == '\x1b' && chars.peek() == Some(&'\\') {
56
                        chars.next();
57
                        break;
58
                    }
59
                }
60
            }
61
            Some(_) => {
62
                chars.next();
63
            }
64
            None => {}
65
        }
66
    }
67
    Cow::Owned(output)
68
}
69
70
#[cfg(test)]
71
mod tests {
72
    use super::*;
73
74
    #[test]
75
    fn strip_borrows_plain_text() {
76
        let stripped = strip("plain text");
77
78
        assert!(matches!(stripped, Cow::Borrowed("plain text")));
79
    }
80
81
    #[test]
82
    fn strip_removes_csi_sequences() {
83
        assert_eq!(
84
            strip("\x1b[33mdiff --git a/f b/f\x1b[m").as_ref(),
85
            "diff --git a/f b/f"
86
        );
87
    }
88
89
    #[test]
90
    fn strip_removes_osc_sequences() {
91
        assert_eq!(
92
            strip("a\x1b]8;;https://example.invalid\x07link\x1b]8;;\x07b").as_ref(),
93
            "alinkb"
94
        );
95
    }
96
}