src/util.rs

249 lines · 7688 bytes

  1//! # Utility functions
  2use std::borrow::Cow;
  3
  4use regex::{Regex, RegexBuilder};
  5use unicode_segmentation::UnicodeSegmentation;
  6use unicode_width::UnicodeWidthStr;
  7
  8use ratatui::style::Style;
  9use ratatui::text::{Line, Span, Text};
 10
 11pub fn split_cow(cow: Cow<'_, str>, idx: usize) -> (Cow<'_, str>, Cow<'_, str>) {
 12    match cow {
 13        Cow::Borrowed(s) => {
 14            let s1 = Cow::Borrowed(&s[idx..]);
 15            let s0 = Cow::Borrowed(&s[..idx]);
 16
 17            (s0, s1)
 18        },
 19        Cow::Owned(mut s) => {
 20            let s1 = Cow::Owned(s.split_off(idx));
 21            let s0 = Cow::Owned(s);
 22
 23            (s0, s1)
 24        },
 25    }
 26}
 27
 28pub fn take_width(s: Cow<'_, str>, width: usize) -> ((Cow<'_, str>, usize), Cow<'_, str>) {
 29    // Find where to split the line.
 30    let mut cur_width = 0;
 31
 32    let mut idx = UnicodeSegmentation::split_word_bound_indices(s.as_ref())
 33        .find_map(|(i, word)| {
 34            let word_width = UnicodeWidthStr::width(word);
 35            if cur_width + word_width > width {
 36                Some(i)
 37            } else {
 38                cur_width += word_width;
 39                None
 40            }
 41        })
 42        .unwrap_or(s.len());
 43
 44    if idx == 0 {
 45        // first word is wider than available; fall back to splitting by width
 46        idx = UnicodeSegmentation::grapheme_indices(s.as_ref(), true)
 47            .find_map(|(i, graph)| {
 48                let graph_width = UnicodeWidthStr::width(graph);
 49                if cur_width + graph_width > width {
 50                    Some(i)
 51                } else {
 52                    cur_width += graph_width;
 53                    None
 54                }
 55            })
 56            .unwrap_or(s.len());
 57    }
 58
 59    let (s0, s1) = split_cow(s, idx);
 60
 61    ((s0, cur_width), s1)
 62}
 63
 64pub struct WrappedLinesIterator<'a> {
 65    iter: std::vec::IntoIter<Cow<'a, str>>,
 66    curr: Option<Cow<'a, str>>,
 67    width: usize,
 68}
 69
 70impl<'a> WrappedLinesIterator<'a> {
 71    fn new<T>(input: T, width: usize) -> Self
 72    where
 73        T: Into<Cow<'a, str>>,
 74    {
 75        let width = width.max(2);
 76
 77        let cows: Vec<Cow<'a, str>> = match input.into() {
 78            Cow::Borrowed(s) => s.lines().map(Cow::Borrowed).collect(),
 79            Cow::Owned(s) => s.lines().map(ToOwned::to_owned).map(Cow::Owned).collect(),
 80        };
 81
 82        WrappedLinesIterator { iter: cows.into_iter(), curr: None, width }
 83    }
 84}
 85
 86impl<'a> Iterator for WrappedLinesIterator<'a> {
 87    type Item = (Cow<'a, str>, usize);
 88
 89    fn next(&mut self) -> Option<Self::Item> {
 90        if self.curr.is_none() {
 91            self.curr = self.iter.next();
 92        }
 93
 94        if let Some(s) = self.curr.take() {
 95            let width = UnicodeWidthStr::width(s.as_ref());
 96
 97            if width <= self.width {
 98                return Some((s, width));
 99            } else {
100                let (prefix, s1) = take_width(s, self.width);
101                self.curr = Some(s1);
102                return Some(prefix);
103            }
104        } else {
105            return None;
106        }
107    }
108}
109
110pub fn wrap<'a, T>(input: T, width: usize) -> WrappedLinesIterator<'a>
111where
112    T: Into<Cow<'a, str>>,
113{
114    WrappedLinesIterator::new(input, width)
115}
116
117pub fn wrapped_text<'a, T>(s: T, width: usize, style: Style) -> Text<'a>
118where
119    T: Into<Cow<'a, str>>,
120{
121    let mut text = Text::default();
122
123    for (line, w) in wrap(s, width) {
124        let space = space_span(width.saturating_sub(w), style);
125        let spans = Line::from(vec![Span::styled(line, style), space]);
126
127        text.lines.push(spans);
128    }
129
130    return text;
131}
132
133pub fn space(width: usize) -> String {
134    " ".repeat(width)
135}
136
137pub fn space_span(width: usize, style: Style) -> Span<'static> {
138    Span::styled(space(width), style)
139}
140
141pub fn space_text(width: usize, style: Style) -> Text<'static> {
142    space_span(width, style).into()
143}
144
145pub fn join_cell_text<'a>(texts: Vec<(Text<'a>, usize)>, join: Span<'a>, style: Style) -> Text<'a> {
146    let height = texts.iter().map(|t| t.0.height()).max().unwrap_or(0);
147    let mut text = Text::from(vec![Line::from(vec![join.clone()]); height]);
148
149    for (mut t, w) in texts.into_iter() {
150        for i in 0..height {
151            if let Some(line) = t.lines.get_mut(i) {
152                text.lines[i].spans.append(&mut line.spans);
153            } else {
154                text.lines[i].spans.push(space_span(w, style));
155            }
156
157            text.lines[i].spans.push(join.clone());
158        }
159    }
160
161    text
162}
163
164fn replace_emoji_in_grapheme(grapheme: &str) -> String {
165    emojis::get(grapheme)
166        .and_then(|emoji| emoji.shortcode())
167        .map(|shortcode| format!(":{shortcode}:"))
168        .unwrap_or_else(|| grapheme.to_owned())
169}
170
171pub fn replace_emojis_in_str(s: &str) -> String {
172    let graphemes = s.graphemes(true);
173    graphemes.map(replace_emoji_in_grapheme).collect()
174}
175
176pub fn replace_emojis_in_span(span: &mut Span) {
177    span.content = Cow::Owned(replace_emojis_in_str(span.content.as_ref()))
178}
179
180pub fn replace_emojis_in_line(line: &mut Line) {
181    for span in &mut line.spans {
182        replace_emojis_in_span(span);
183    }
184}
185
186/// Compile a search pattern, optionally ignoring case.
187pub fn compile_search(pattern: &str, case_insensitive: bool) -> Result<Regex, regex::Error> {
188    RegexBuilder::new(pattern).case_insensitive(case_insensitive).build()
189}
190
191#[cfg(test)]
192pub mod tests {
193    use super::*;
194
195    #[test]
196    fn test_compile_search_case_insensitive() {
197        let re = compile_search("chicken", true).unwrap();
198        assert!(re.is_match("CHICKEN"));
199        assert!(re.is_match("Chicken"));
200        assert!(re.is_match("chicken"));
201
202        let re = compile_search("chicken", false).unwrap();
203        assert!(!re.is_match("CHICKEN"));
204        assert!(!re.is_match("Chicken"));
205        assert!(re.is_match("chicken"));
206    }
207
208    #[test]
209    fn test_wrapped_lines_ascii() {
210        let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye";
211
212        let mut iter = wrap(s, 100);
213        assert_eq!(iter.next(), Some((Cow::Borrowed("hello world!"), 12)));
214        assert_eq!(iter.next(), Some((Cow::Borrowed("abcdefghijklmnopqrstuvwxyz"), 26)));
215        assert_eq!(iter.next(), Some((Cow::Borrowed("goodbye"), 7)));
216        assert_eq!(iter.next(), None);
217
218        let mut iter = wrap(s, 5);
219        assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5)));
220        assert_eq!(iter.next(), Some((Cow::Borrowed(" "), 1)));
221        assert_eq!(iter.next(), Some((Cow::Borrowed("world"), 5)));
222        assert_eq!(iter.next(), Some((Cow::Borrowed("!"), 1)));
223        assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5)));
224        assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5)));
225        assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5)));
226        assert_eq!(iter.next(), Some((Cow::Borrowed("pqrst"), 5)));
227        assert_eq!(iter.next(), Some((Cow::Borrowed("uvwxy"), 5)));
228        assert_eq!(iter.next(), Some((Cow::Borrowed("z"), 1)));
229        assert_eq!(iter.next(), Some((Cow::Borrowed("goodb"), 5)));
230        assert_eq!(iter.next(), Some((Cow::Borrowed("ye"), 2)));
231        assert_eq!(iter.next(), None);
232    }
233
234    #[test]
235    fn test_wrapped_lines_unicode() {
236        let s = "CHICKEN";
237
238        let mut iter = wrap(s, 14);
239        assert_eq!(iter.next(), Some((Cow::Borrowed(s), 14)));
240        assert_eq!(iter.next(), None);
241
242        let mut iter = wrap(s, 5);
243        assert_eq!(iter.next(), Some((Cow::Borrowed("CH"), 4)));
244        assert_eq!(iter.next(), Some((Cow::Borrowed("IC"), 4)));
245        assert_eq!(iter.next(), Some((Cow::Borrowed("KE"), 4)));
246        assert_eq!(iter.next(), Some((Cow::Borrowed("N"), 2)));
247        assert_eq!(iter.next(), None);
248    }
249}