use crate::ui::overlay::prompt::TextInput;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FindState {
pub input: TextInput,
pub matches: Vec<usize>,
pub current: Option<usize>,
}
impl FindState {
pub fn new() -> Self {
FindState::default()
}
pub fn query(&self) -> &str {
self.input.value()
}
pub fn count(&self) -> usize {
self.matches.len()
}
pub fn position(&self) -> String {
if self.query().is_empty() {
return String::new();
}
if self.matches.is_empty() {
return "no matches".to_string();
}
match self.current {
Some(at) => format!("{}/{}", at + 1, self.matches.len()),
None => format!("{} matches", self.matches.len()),
}
}
pub fn refresh(&mut self, source: &str) {
let previous = self.current_offset();
self.matches = find_all(source, self.query());
self.current = match previous {
Some(offset) => {
self.matches
.iter()
.position(|&m| m >= offset)
.or(if self.matches.is_empty() {
None
} else {
Some(0)
})
}
None if self.matches.is_empty() => None,
None => Some(0),
};
}
pub fn current_offset(&self) -> Option<usize> {
self.matches.get(self.current?).copied()
}
pub fn step(&mut self, forward: bool) -> Option<usize> {
if self.matches.is_empty() {
return None;
}
let count = self.matches.len();
self.current = Some(match self.current {
Some(at) if forward => (at + 1) % count,
Some(at) => (at + count - 1) % count,
None if forward => 0,
None => count - 1,
});
self.current_offset()
}
}
pub fn is_case_sensitive(query: &str) -> bool {
query.chars().any(char::is_uppercase)
}
pub fn find_all(haystack: &str, query: &str) -> Vec<usize> {
if query.is_empty() {
return Vec::new();
}
if is_case_sensitive(query) {
return haystack.match_indices(query).map(|(at, _)| at).collect();
}
let folded_query = query.to_lowercase();
let mut out = Vec::new();
let mut from = 0usize;
while from < haystack.len() {
let Some(rest) = haystack.get(from..) else {
from += 1;
continue;
};
let Some(at) = rest.to_lowercase().find(&folded_query) else {
break;
};
let Some(real) = recover_offset(rest, at) else {
break;
};
out.push(from + real);
from += real + query.len().max(1);
}
out
}
fn recover_offset(original: &str, folded_offset: usize) -> Option<usize> {
let mut folded = 0usize;
for (at, c) in original.char_indices() {
if folded >= folded_offset {
return Some(at);
}
folded += c.to_lowercase().map(char::len_utf8).sum::<usize>();
}
(folded >= folded_offset).then_some(original.len())
}
pub fn matches_in_line(line: &str, query: &str) -> Vec<(usize, usize)> {
find_all(line, query)
.into_iter()
.filter_map(|at| {
let end = recover_end(line, at, query)?;
Some((at, end))
})
.collect()
}
fn recover_end(line: &str, at: usize, query: &str) -> Option<usize> {
let rest = line.get(at..)?;
let wanted = query.to_lowercase().chars().count();
let mut folded = 0usize;
for (offset, c) in rest.char_indices() {
if folded >= wanted {
return Some(at + offset);
}
folded += c.to_lowercase().count();
}
Some(line.len())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_lower_case_query_matches_either_case() {
assert_eq!(find_all("Token and token", "token"), vec![0, 10]);
}
#[test]
fn an_upper_case_query_means_it() {
assert!(is_case_sensitive("Token"));
assert_eq!(find_all("Token and token", "Token"), vec![0]);
}
#[test]
fn matches_do_not_overlap() {
assert_eq!(find_all("aaaa", "aa"), vec![0, 2]);
}
#[test]
fn an_empty_query_matches_nothing() {
assert!(find_all("anything", "").is_empty());
}
#[test]
fn offsets_are_into_the_original_text() {
let source = "başlık ve Başlık";
let found = find_all(source, "başlık");
assert_eq!(found.len(), 2);
for at in found {
assert!(
source.is_char_boundary(at),
"offset {at} is not a character boundary"
);
}
assert_eq!(&source[found_second(source)..], "Başlık");
}
fn found_second(source: &str) -> usize {
find_all(source, "başlık")[1]
}
#[test]
fn stepping_wraps_in_both_directions() {
let mut find = FindState::new();
for c in "token".chars() {
find.input
.apply(crate::ui::overlay::prompt::TextEdit::Insert(c));
}
find.refresh("token a token b token");
assert_eq!(find.count(), 3);
assert_eq!(find.current, Some(0));
find.step(true);
find.step(true);
assert_eq!(find.current, Some(2));
find.step(true);
assert_eq!(find.current, Some(0), "the last match wraps to the first");
find.step(false);
assert_eq!(find.current, Some(2));
}
#[test]
fn typing_another_character_keeps_the_reader_where_they_were() {
let source = "alpha beta alphabet";
let mut find = FindState::new();
for c in "alpha".chars() {
find.input
.apply(crate::ui::overlay::prompt::TextEdit::Insert(c));
}
find.refresh(source);
find.step(true);
assert_eq!(find.current_offset(), Some(11));
find.input
.apply(crate::ui::overlay::prompt::TextEdit::Insert('b'));
find.refresh(source);
assert_eq!(find.current_offset(), Some(11));
}
#[test]
fn the_position_says_what_there_is_to_say() {
let mut find = FindState::new();
assert_eq!(find.position(), "");
for c in "zzz".chars() {
find.input
.apply(crate::ui::overlay::prompt::TextEdit::Insert(c));
}
find.refresh("nothing here");
assert_eq!(find.position(), "no matches");
find.input
.apply(crate::ui::overlay::prompt::TextEdit::Clear);
for c in "e".chars() {
find.input
.apply(crate::ui::overlay::prompt::TextEdit::Insert(c));
}
find.refresh("one two three");
assert_eq!(find.position(), "1/3");
}
#[test]
fn line_matches_are_column_ranges_into_the_line() {
let line = "see the Token and the token";
let found = matches_in_line(line, "token");
assert_eq!(found.len(), 2);
assert_eq!(&line[found[0].0..found[0].1], "Token");
assert_eq!(&line[found[1].0..found[1].1], "token");
}
}