//! Matching a search query against note text: case and Turkish-letter folding, typo //! tolerance, and the search filters (match case, whole word, exact phrase, regex). //! //! Positions are char indices into the original text. Folding maps one char to one //! char, so they line up. use regex::{Regex, RegexBuilder}; /// Most words used from one query; longer queries are cut down. const MAX_TERMS: usize = 16; /// Longest word kept from a query. const MAX_TERM_CHARS: usize = 64; /// Longest query kept as an exact phrase or a regular expression. const MAX_PATTERN_CHARS: usize = 256; /// The search filters. All off is the forgiving default: any case, Turkish letters as /// plain ones, inside words, typos allowed. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Options { /// Letters must match in case (and Turkish letters exactly). pub case: bool, /// Matches must be whole words. pub word: bool, /// The query is one phrase, matched as written. No typos. pub exact: bool, /// The query is a regular expression. pub regex: bool, } impl Options { /// Typos are only forgiven with every filter off; any filter asks for precision. fn typos(self) -> bool { !(self.case || self.word || self.exact) } } /// A compiled query. #[derive(Clone)] pub enum Matcher { Terms { terms: Vec>, opts: Options }, Regex(Regex), } /// Where a word a match needs lies in a word of the text: see [`Matcher::required_words`]. #[derive(Clone, Copy)] pub enum Part { Whole, /// The text's word ends with it. End, /// The text's word starts with it. Start, Inside, } impl Part { /// Whether `word` of a text can hold `piece` this way. pub fn holds(self, word: &[char], piece: &[char]) -> bool { match self { Part::Whole => word == piece, Part::End => word.ends_with(piece), Part::Start => word.starts_with(piece), Part::Inside => word.windows(piece.len()).any(|w| w == piece), } } } /// The query is not a valid regular expression. #[derive(Debug)] pub struct InvalidRegex; /// Whether every match of `hir` is a run of ASCII letters and digits or decimal digits /// (so, inside one word), with assertions that hold at least as often at a word's edges. fn within_word(hir: ®ex_syntax::hir::Hir) -> bool { use regex_syntax::hir::{Class, HirKind, Look}; let alnum = |c: u32| char::from_u32(c).is_some_and(|c| c.is_ascii_alphanumeric()); match hir.kind() { HirKind::Empty => true, HirKind::Literal(lit) => lit.0.iter().all(|&b| alnum(b.into())), HirKind::Class(Class::Unicode(class)) => { class.ranges().iter().all(|r| (r.start()..=r.end()).all(|c| alnum(c.into()))) || class.ranges().iter().all(|r| (r.start()..=r.end()).all(|c| c.is_numeric() && c.is_alphanumeric())) } HirKind::Class(Class::Bytes(_)) => false, HirKind::Look(look) => !matches!(look, Look::WordAsciiNegate | Look::WordUnicodeNegate), HirKind::Repetition(rep) => within_word(&rep.sub), HirKind::Capture(cap) => within_word(&cap.sub), HirKind::Concat(hs) | HirKind::Alternation(hs) => hs.iter().all(within_word), } } /// The words of `piece`, a run of text: those at its edges may run on in the text. None /// when it holds no word. fn piece_words(piece: &[char]) -> Option, Part)>> { let piece: Vec = piece.iter().map(|&c| match_fold(c)).collect(); let mut words = Vec::new(); let mut i = 0; while i < piece.len() { if !piece[i].is_alphanumeric() { i += 1; continue; } let start = i; while i < piece.len() && piece[i].is_alphanumeric() { i += 1; } let part = match (start == 0, i == piece.len()) { (true, true) => Part::Inside, (true, false) => Part::End, (false, true) => Part::Start, (false, false) => Part::Whole, }; words.push((piece[start..i].to_vec(), part)); } (!words.is_empty()).then_some(words) } impl Matcher { /// None when the query holds nothing to search for. pub fn new(query: &str, opts: Options) -> Result, InvalidRegex> { let query = query.trim(); if query.is_empty() { return Ok(None); } if opts.regex { let pattern: String = query.chars().take(MAX_PATTERN_CHARS).collect(); let pattern = if opts.word { format!(r"\b(?:{pattern})\b") } else { pattern }; return RegexBuilder::new(&pattern) .case_insensitive(!opts.case) .size_limit(1 << 20) .build() .map(|re| Some(Self::Regex(re))) .map_err(|_| InvalidRegex); } let fold = |c: char| if opts.case { c } else { match_fold(c) }; let mut terms: Vec> = if opts.exact { let phrase = query.split_whitespace().collect::>().join(" "); vec![phrase.chars().take(MAX_PATTERN_CHARS).map(fold).collect()] } else { query .split(|c: char| !c.is_alphanumeric()) .filter(|w| !w.is_empty()) .map(|w| w.chars().take(MAX_TERM_CHARS).map(fold).collect()) .collect() }; terms.sort(); terms.dedup(); terms.truncate(MAX_TERMS); Ok((!terms.is_empty()).then_some(Self::Terms { terms, opts })) } /// The words a text must hold to match, folded like [`fold_word`], with where each /// lies in a word of the text: any one of the alternatives, each word of it. For an /// exact phrase its words; for a regex those of the literals every match starts /// with. None when nothing is required. pub fn required_words(&self) -> Option, Part)>>> { match self { Self::Terms { terms, opts } if opts.exact => Some(vec![piece_words(terms.first()?)?]), Self::Terms { .. } => None, Self::Regex(re) => { use regex_syntax::hir::literal::{ExtractKind, Extractor}; let hir = regex_syntax::parse(re.as_str()).ok()?; let seq = Extractor::new().kind(ExtractKind::Prefix).extract(&hir); seq.literals()? .iter() .map(|lit| { // Folding only agrees with the regex's own case rules on ASCII. let text = std::str::from_utf8(lit.as_bytes()).ok().filter(|t| t.is_ascii())?; piece_words(&text.chars().collect::>()) }) .collect() } } } /// For a regex whose every match lies inside one word as [`words`] splits text: the /// regex to try on folded words. A text can only match if one of its words matches it. pub fn word_regex(&self) -> Option { let Self::Regex(re) = self else { return None }; let hir = regex_syntax::parse(re.as_str()).ok()?; if !within_word(&hir) { return None; } // Folding lowercases, and maps a few letters to plain ones that are still letters. RegexBuilder::new(re.as_str()).case_insensitive(true).size_limit(1 << 20).build().ok() } /// The options of a term query, None for a regex. pub fn options(&self) -> Option { match self { Self::Terms { opts, .. } => Some(*opts), Self::Regex(_) => None, } } /// The default matcher for `query`, as the palette and `[[` use it. pub fn simple(query: &str) -> Option { Self::new(query, Options::default()).ok().flatten() } /// The cheapest match of each term in `text`, by term (None where it doesn't occur). /// See [`occurrences`] for costs. pub fn term_costs(&self, text: &str) -> Vec> { match self { Self::Terms { terms, opts } => { let hay = fold_text(text, *opts); terms .iter() .map(|t| cheapest(&hay, t, *opts)) .collect() } Self::Regex(re) => vec![re.find_iter(text).any(|m| !m.is_empty()).then_some(0)], } } /// The terms, when every match lies inside one word as [`words`] splits text, so /// the query can be matched word by word: not for case, phrase or regex searches. pub fn word_terms(&self) -> Option<&[Vec]> { match self { Self::Terms { terms, opts } if !opts.case && !opts.exact => Some(terms), _ => None, } } /// The cheapest match of `term` (one of [`word_terms`](Self::word_terms)) inside /// one folded `word`. The cheapest match of a term in a text is the cheapest in /// any of its words. pub fn word_cost(&self, term: &[char], word: &[char]) -> Option { let Self::Terms { opts, .. } = self else { return None }; cheapest(word, term, *opts) } /// Char ranges `(start, end)` of the matches in `text`, merged and sorted. pub fn ranges(&self, text: &str) -> Vec<(usize, usize)> { let mut ranges: Vec<(usize, usize)> = match self { Self::Terms { terms, opts } => { let hay = fold_text(text, *opts); terms .iter() .flat_map(|t| occurrences(&hay, t, *opts)) .map(|(s, e, _)| (s, e)) .collect() } Self::Regex(re) => { // Byte offsets to char indices. let (mut ranges, mut byte, mut char) = (Vec::new(), 0, 0); for m in re.find_iter(text).filter(|m| !m.is_empty()) { char += text[byte..m.start()].chars().count(); byte = m.start(); ranges.push((char, char + m.as_str().chars().count())); } ranges } }; ranges.sort_unstable(); let mut merged: Vec<(usize, usize)> = Vec::new(); for (start, end) in ranges { match merged.last_mut() { Some(last) if start <= last.1 => last.1 = last.1.max(end), _ => merged.push((start, end)), } } merged } } /// Lowercase form of one char. fn fold(c: char) -> char { if c.is_ascii() { return c.to_ascii_lowercase(); } c.to_lowercase().next().unwrap_or(c) } /// One char as the default search compares it: lowercase, Turkish letters as plain ones. fn match_fold(c: char) -> char { match fold(c) { 'ı' => 'i', 'ş' => 's', 'ğ' => 'g', 'ç' => 'c', 'ö' => 'o', 'ü' => 'u', c => c, } } /// A title folded for matching: lowercase, with Turkish letters as their plain forms, /// so "izmir" finds "İzmir" and "isik", "ışık" and "Işık" find each other. pub fn title_fold(title: &str) -> String { title.chars().map(match_fold).collect() } /// The words of `text` as [`Matcher::word_cost`] takes them: runs of letters and /// digits, folded like the default search folds them. pub fn words(text: &str) -> impl Iterator { text.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()) } /// One word folded for [`Matcher::word_cost`]. pub fn fold_word(word: &str) -> Box<[char]> { word.chars().map(match_fold).collect() } fn fold_text(text: &str, opts: Options) -> Vec { if opts.case { text.chars().collect() } else { text.chars().map(match_fold).collect() } } /// Typos a term of `len` chars may have and still match: none up to 4 chars (except one /// swap of neighbours, see [`occurrences`]), one up to 8, two beyond. Short words with any /// other typo match too much else. fn max_typos(len: usize) -> usize { match len { 0..=4 => 0, 5..=8 => 1, _ => 2, } } /// Where `term` occurs in `hay` (both already folded). Exact occurrences (whole words /// only with `opts.word`), or, when there are none and typos are allowed, word /// beginnings within [`max_typos`] edits of the term (insertions, deletions, /// substitutions and swapped neighbours). The `usize` is the match's cost: 0 exact at a /// word start, 1 exact inside a word, 1 + typos otherwise. fn occurrences(hay: &[char], term: &[char], opts: Options) -> Vec<(usize, usize, usize)> { let mut found = Vec::new(); each_occurrence(hay, term, opts, |o| { found.push(o); true }); found } /// The cheapest of [`occurrences`], without collecting them: 0 ends the search. fn cheapest(hay: &[char], term: &[char], opts: Options) -> Option { let mut best: Option = None; each_occurrence(hay, term, opts, |(_, _, cost)| { best = Some(best.map_or(cost, |b| b.min(cost))); cost > 0 }); best } /// Calls `f` with each of [`occurrences`] until it returns false. fn each_occurrence(hay: &[char], term: &[char], opts: Options, mut f: impl FnMut((usize, usize, usize)) -> bool) { let n = term.len(); if n == 0 { return; } let word_start = |i: usize| i == 0 || !hay[i - 1].is_alphanumeric(); let word_end = |i: usize| i == hay.len() || !hay[i].is_alphanumeric(); let mut any = false; if n <= hay.len() { for start in 0..=hay.len() - n { let end = start + n; if hay[start] != term[0] || hay[start..end] != term[..] { continue; } if opts.word && !(word_start(start) && word_end(end)) { continue; } any = true; if !f((start, end, usize::from(!word_start(start)))) { return; } } } if any || !opts.typos() { return; } let d = max_typos(n); // Short words only forgive swapped neighbours: "mlik" finds "milk". let swap_only = d == 0; if swap_only && n < 3 { return; } let mut i = 0; while i < hay.len() { if !hay[i].is_alphanumeric() { i += 1; continue; } let mut end = i; while end < hay.len() && hay[end].is_alphanumeric() { end += 1; } if swap_only { let word = &hay[i..end]; let swapped = word.len() >= n && (1..n).any(|k| { word[k - 1] == term[k] && word[k] == term[k - 1] && term[k] != term[k - 1] && (0..n).all(|x| x == k || x == k - 1 || word[x] == term[x]) }); if swapped && !f((i, i + n, 2)) { return; } } else if let Some((typos, len)) = Some(&hay[i..end.min(i + n + d)]).filter(|w| shares_enough(term, w, d)).and_then(|w| prefix_distance(term, w, d)) && !f((i, i + len, 1 + typos)) { return; } i = end; } } /// Whether `word` could be within `max` edits of `term` (or have a prefix that is): an /// edit removes at most one char the two have in common, so more than `max` chars of /// `term` missing from `word` rule it out. Far cheaper than [`prefix_distance`], which /// almost every word of a search fails. fn shares_enough(term: &[char], word: &[char], max: usize) -> bool { if word.len() > 64 { return true; } let mut used = 0u64; let mut missing = 0; for &c in term { match (0..word.len()).find(|&j| used & (1 << j) == 0 && word[j] == c) { Some(j) => used |= 1 << j, None => { missing += 1; if missing > max { return false; } } } } true } /// The fewest edits turning `term` into some prefix of `word`, and that prefix's length, /// if at most `max`. Optimal string alignment distance, so a swap counts as one edit. fn prefix_distance(term: &[char], word: &[char], max: usize) -> Option<(usize, usize)> { let (n, m) = (term.len(), word.len()); if m + max < n { return None; } // One flat table, row `i` at `i * w`. let w = m + 1; let mut d = vec![0usize; (n + 1) * w]; for i in 0..=n { d[i * w] = i; } for j in 0..=m { d[j] = j; } for i in 1..=n { for j in 1..=m { let cost = usize::from(term[i - 1] != word[j - 1]); let mut v = (d[(i - 1) * w + j] + 1).min(d[i * w + j - 1] + 1).min(d[(i - 1) * w + j - 1] + cost); if i > 1 && j > 1 && term[i - 1] == word[j - 2] && term[i - 2] == word[j - 1] { v = v.min(d[(i - 2) * w + j - 2] + 1); } d[i * w + j] = v; } } (n.saturating_sub(max).max(1)..=m) .map(|j| (d[n * w + j], j)) .min_by_key(|&(dist, j)| (dist, j.abs_diff(n))) .filter(|&(dist, _)| dist <= max) } #[cfg(test)] mod tests { use super::*; fn cost(text: &str, q: &str, opts: Options) -> Option { Matcher::new(q, opts).unwrap().unwrap().term_costs(text).into_iter().sum() } #[test] fn typo_tolerance() { let d = Options::default(); assert_eq!(cost("Groceries list", "groc", d), Some(0)); assert_eq!(cost("Groceries list", "grcoeries", d), Some(2)); // swapped letters assert_eq!(cost("Groceries list", "grocerues", d), Some(2)); // one substitution assert_eq!(cost("Project kickoff", "porject kikcoff", d), Some(4)); assert_eq!(cost("İzmir gezisi", "izmr", d), None); // 4 chars: only a swap assert_eq!(cost("Plan", "plna", d), Some(2)); assert_eq!(cost("Plan", "plen", d), None); assert_eq!(cost("Işık listesi", "isik listsi", d), Some(2)); } #[test] fn filters() { let case = Options { case: true, ..Default::default() }; let word = Options { word: true, ..Default::default() }; let exact = Options { exact: true, ..Default::default() }; let regex = Options { regex: true, ..Default::default() }; assert_eq!(cost("Groceries", "groceries", case), None); assert_eq!(cost("Groceries", "Groceries", case), Some(0)); assert_eq!(cost("Groceries", "Groc", word), None); assert_eq!(cost("milk, eggs", "milk", word), Some(0)); assert_eq!(cost("buy milk and eggs", "milk eggs", exact), None); assert_eq!(cost("buy milk and eggs", "milk and", exact), None); // text not collapsed assert_eq!(cost("buy milk and eggs", "MILK AND", exact), Some(0)); assert_eq!(cost("Groceries", "grcoeries", exact), None); // no typos assert_eq!(cost("order #42", r"#\d+", regex), Some(0)); assert!(Matcher::new("(", regex).is_err()); let within = |q: &str| Matcher::new(q, regex).unwrap().unwrap().word_regex().is_some(); assert!(within(r"\d{9}") && within(r"\bv9[0-9]+") && within("ab|cd")); assert!(!within(r"\w+") && !within("a b") && !within(r"a\B") && !within("é")); let m = Matcher::new("ş", Options::default()).unwrap().unwrap(); assert_eq!(m.ranges("Işık"), vec![(1, 2)]); } } #[cfg(test)] mod word_tests { use super::*; #[test] fn word_costs_equal_text_costs() { let texts = [ "Işık İzmir'de, milk and honey; asdadasxd foo_bar x2y alpha42 gamma-ray", "Paragraph 12 with some ordinary words in it. note_12() -> usize", "", ]; let queries = ["isik", "izmr", "mlik", "dadas", "alpha42", "gama", "bar", "ordinery wrds", "12", "ray gamma x2"]; for opts in [Options::default(), Options { word: true, ..Options::default() }] { for q in queries { let m = Matcher::new(q, opts).unwrap().unwrap(); for text in texts { let words: Vec> = words(text).map(fold_word).collect(); let by_word: Vec> = m .word_terms() .unwrap() .iter() .map(|t| words.iter().filter_map(|w| m.word_cost(t, w)).min()) .collect(); assert_eq!(by_word, m.term_costs(text), "{q:?} in {text:?} with {opts:?}"); } } } } }