diff options
author | Dan Davison <dandavison7@gmail.com> | 2021-11-12 20:48:40 -0500 |
---|---|---|
committer | Dan Davison <dandavison7@gmail.com> | 2021-11-22 13:18:15 -0500 |
commit | 65d856498e491c5fbf82999eb1c14944b9232617 (patch) | |
tree | 8c349d02691ef43a006a3edd1fa4552146d7a954 | |
parent | 48173248dac85d6d6871554030e4a07e06c9ecdd (diff) |
Parse styles from a string containing ANSI sequences
-rw-r--r-- | src/ansi/mod.rs | 15 |
1 files changed, 15 insertions, 0 deletions
diff --git a/src/ansi/mod.rs b/src/ansi/mod.rs index 643b47f0..5f90c536 100644 --- a/src/ansi/mod.rs +++ b/src/ansi/mod.rs @@ -3,6 +3,7 @@ mod iterator; use std::borrow::Cow; +use ansi_term::Style; use itertools::Itertools; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; @@ -64,6 +65,20 @@ pub fn truncate_str<'a, 'b>(s: &'a str, display_width: usize, tail: &'b str) -> Cow::from(format!("{}{}", result, result_tail)) } +pub fn parse_style_sections(s: &str) -> Vec<(ansi_term::Style, &str)> { + let mut sections = Vec::new(); + let mut curr_style = Style::default(); + for element in AnsiElementIterator::new(s) { + match element { + Element::Text(start, end) => sections.push((curr_style, &s[start..end])), + Element::Csi(style, _, _) => curr_style = style, + _ => {} + } + } + sections +} + +// Return the first CSI element, if any, as an `ansi_term::Style`. pub fn parse_first_style(s: &str) -> Option<ansi_term::Style> { AnsiElementIterator::new(s).find_map(|el| match el { Element::Csi(style, _, _) => Some(style), |