1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
use super::{
cursor::CharCursor,
graphic_rendition::{self, Sgr},
};
fn cursor_skip_space(cursor: &mut CharCursor) {
// skip: !"#$%&'()*+,-./ (SPACE)
cursor.read_while(|c| matches!(c, '\u{0020}'..='\u{002f}'));
}
/// ANSI Escape Sequence.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Escape {
Csi(Csi),
}
impl Escape {
const ESC: char = '\u{001b}';
fn parse(cursor: &mut CharCursor) -> Option<Self> {
cursor.read_char(Self::ESC)?;
cursor_skip_space(cursor);
if Csi::peek(cursor) {
Csi::parse(cursor).map(Self::Csi)
} else {
None
}
}
}
/// Control sequence.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Csi {
Sgr(Vec<Sgr>),
}
impl Csi {
const START: char = '[';
fn peek(cursor: &mut CharCursor) -> bool {
cursor.peek_char(Self::START)
}
fn read_params<'a>(cursor: &mut CharCursor<'a>) -> Option<(char, Vec<&'a str>)> {
let mut start = cursor.position();
let mut end = start;
let mut params = Vec::new();
cursor.read_while(|c| {
match c {
';' => {
params.push(start..end);
start = end + c.len_utf8();
end = start;
true
}
// 0–9:;<=>?
'\u{0030}'..='\u{003f}' => {
end += c.len_utf8();
true
}
_ => false,
}
});
if start != end {
params.push(start..end);
}
cursor_skip_space(cursor);
// read method name
match cursor.read()? {
c @ '\u{0040}'..='\u{007e}' => {
let params = params.drain(..).map(|r| cursor.get(r).unwrap()).collect();
Some((c, params))
}
_ => None,
}
}
fn parse(cursor: &mut CharCursor) -> Option<Self> {
cursor.read_char(Self::START)?;
let (method, params) = Self::read_params(cursor)?;
match method {
'm' => {
let params: Vec<usize> = params
.iter()
.map(|p| p.parse())
.collect::<Result<_, _>>()
.ok()?;
let sgrs = graphic_rendition::parse_sgrs(params.iter().copied());
Some(Self::Sgr(sgrs))
}
_ => None,
}
}
}
/// Read the next sequence in the given slice.
/// Returns the content before the escape sequence, the escape sequence itself, and everything following it.
/// The escape sequence can be `None` if it's invalid.
/// If the slice doesn't contain an escape sequence the entire string slice will be returned as the first item.
///
/// ```
/// # use yew_ansi::*;
/// let (pre, esc, post) = yew_ansi::read_next_sequence("Hello \u{001b}[32mWorld");
/// assert_eq!(pre, "Hello ");
/// assert_eq!(
/// esc,
/// Some(Escape::Csi(Csi::Sgr(vec![
/// Sgr::ColorFgName(ColorName::Green),
/// ])))
/// );
/// assert_eq!(post, "World");
/// ```
pub fn read_next_sequence(s: &str) -> (&str, Option<Escape>, &str) {
s.find(Escape::ESC).map_or((s, None, ""), |index| {
let (pre, post) = s.split_at(index);
let mut cursor = CharCursor::new(post);
let esc = Escape::parse(&mut cursor);
(pre, esc, cursor.remainder())
})
}
/// Parts of a string containing ANSI escape sequences.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Marker<'a> {
/// Raw text without any escape sequences.
Text(&'a str),
/// Parsed escape sequence.
Sequence(Escape),
}
/// Iterator yielding markers in a string.
///
/// Each item is a [`Marker`].
///
/// Returned by [`get_markers`].
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[derive(Clone, Debug)]
pub struct MarkerIter<'a> {
remaining: &'a str,
buf: Option<Marker<'a>>,
}
impl<'a> MarkerIter<'a> {
fn new(s: &'a str) -> Self {
Self {
remaining: s,
buf: None,
}
}
}
impl<'a> Iterator for MarkerIter<'a> {
type Item = Marker<'a>;
fn next(&mut self) -> Option<Self::Item> {
// handle the marker that might have been buffered by last iteration
if let Some(marker) = self.buf.take() {
return Some(marker);
}
while !self.remaining.is_empty() {
let (pre, esc, post) = read_next_sequence(&self.remaining);
self.remaining = post;
let esc_marker = esc.map(Marker::Sequence);
if pre.is_empty() {
if let Some(marker) = esc_marker {
return Some(marker);
}
// nothing to yield right now, this either means we're at the end or we just skipped over an invalid escape sequence.
// explicit "continue" here to make it clear.
continue;
} else {
// store the escape code for the next iteration
self.buf = esc_marker;
return Some(Marker::Text(pre));
}
}
None
}
}
/// Iterate over all [`Marker`]s in given string.
///
/// ```
/// # use yew_ansi::*;
/// let markers = yew_ansi::get_markers("Hello \u{001b}[32mWorld\u{001b}[39;1m!").collect::<Vec<_>>();
/// assert_eq!(
/// markers,
/// vec![
/// Marker::Text("Hello "),
/// Marker::Sequence(Escape::Csi(Csi::Sgr(vec![
/// Sgr::ColorFgName(ColorName::Green),
/// ]))),
/// Marker::Text("World"),
/// Marker::Sequence(Escape::Csi(Csi::Sgr(vec![
/// Sgr::ResetColorFg,
/// Sgr::Bold,
/// ]))),
/// Marker::Text("!"),
/// ]
/// );
/// ```
pub fn get_markers(s: &str) -> MarkerIter {
MarkerIter::new(s)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::graphic_rendition::ColorName;
fn parse(s: &str) -> Option<Escape> {
let s = s.replace("CSI ", "\u{001b} [");
Escape::parse(&mut CharCursor::new(&s))
}
fn parse_sgr(s: &str) -> Vec<Sgr> {
match parse(s) {
Some(Escape::Csi(Csi::Sgr(sgr))) => sgr,
_ => panic!("expected sgr"),
}
}
#[test]
fn parsing() {
assert_eq!(
parse_sgr("CSI 32 m"),
vec![Sgr::ColorFgName(ColorName::Green)]
);
assert_eq!(
parse_sgr("CSI 32;1m"),
vec![Sgr::ColorFgName(ColorName::Green), Sgr::Bold]
);
}
#[test]
fn marking() {
let markers = get_markers("Hello \u{001b} [33mWorld").collect::<Vec<_>>();
assert_eq!(
markers,
vec![
Marker::Text("Hello "),
Marker::Sequence(Escape::Csi(Csi::Sgr(vec![Sgr::ColorFgName(
ColorName::Yellow
)]))),
Marker::Text("World"),
]
)
}
}