Skip to main content

egui_pop_model/
fuzzy.rs

1//! Fuzzy matching for search fields (the command palette, the settings
2//! filter): the query's characters in order in the text, not
3//! necessarily next to each other, scored so that matches at word
4//! starts, in runs and early in the text come first.
5//!
6//! Owned rather than adopted: `nucleo-matcher` is MPL-2.0 (refused by the
7//! licence policy), `fuzzy-matcher` and `sublime_fuzzy` are unmaintained
8//! and give no say over the word starts this needs (`Category: Title`).
9//!
10//! ```
11//! use egui_pop_model::fuzzy;
12//!
13//! let m = fuzzy::score("opf", "File: Open file").unwrap();
14//! assert_eq!(m.positions, [6, 7, 11]); // `Op`en `f`ile
15//! assert!(fuzzy::score("zz", "File: Open file").is_none());
16//! ```
17
18/// A match: its score (higher is better) and the matched characters'
19/// indices (in `char`s) in the text.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct Match {
22    pub score: i32,
23    pub positions: Vec<usize>,
24}
25
26const MATCH: i32 = 16;
27const WORD_START: i32 = 24;
28const TEXT_START: i32 = 8;
29const RUN: i32 = 20;
30const SAME_CASE: i32 = 1;
31const GAP: i32 = 1;
32const GAP_MAX: i32 = 12;
33
34fn word_start(text: &[char], j: usize) -> bool {
35    if j == 0 {
36        return true;
37    }
38    let (prev, c) = (text[j - 1], text[j]);
39    !prev.is_alphanumeric() || (prev.is_lowercase() && c.is_uppercase())
40}
41
42fn same(a: char, b: char) -> bool {
43    a == b || a.to_lowercase().eq(b.to_lowercase())
44}
45
46/// Matches `query` (spaces ignored, case-insensitive) in `text`; none
47/// when its characters are not all there in order. An empty query
48/// matches everything with a score of 0.
49pub fn score(query: &str, text: &str) -> Option<Match> {
50    let q: Vec<char> = query.chars().filter(|c| !c.is_whitespace()).collect();
51    let t: Vec<char> = text.chars().collect();
52    if q.is_empty() {
53        return Some(Match {
54            score: 0,
55            positions: Vec::new(),
56        });
57    }
58    let (n, m) = (q.len(), t.len());
59    if n > m {
60        return None;
61    }
62    // best[i][j]: the best score with q[i] matched at t[j], and from
63    // where q[i - 1] was matched.
64    const NONE: i32 = i32::MIN / 2;
65    let mut best = vec![vec![NONE; m]; n];
66    let mut from = vec![vec![usize::MAX; m]; n];
67    for i in 0..n {
68        for j in i..m {
69            if !same(q[i], t[j]) {
70                continue;
71            }
72            let mut here = MATCH;
73            if word_start(&t, j) {
74                here += WORD_START;
75            }
76            if j == 0 {
77                here += TEXT_START;
78            }
79            if q[i] == t[j] {
80                here += SAME_CASE;
81            }
82            if i == 0 {
83                // Earlier is better, a little.
84                best[i][j] = here - (j as i32).min(GAP_MAX);
85                continue;
86            }
87            for k in (i - 1)..j {
88                let before = best[i - 1][k];
89                if before == NONE {
90                    continue;
91                }
92                let s = if k + 1 == j {
93                    before + here + RUN
94                } else {
95                    before + here - ((j - k - 1) as i32 * GAP).min(GAP_MAX)
96                };
97                if s > best[i][j] {
98                    best[i][j] = s;
99                    from[i][j] = k;
100                }
101            }
102        }
103    }
104    let (end, &top) = best[n - 1]
105        .iter()
106        .enumerate()
107        .max_by_key(|(j, s)| (**s, std::cmp::Reverse(*j)))?;
108    if top == NONE {
109        return None;
110    }
111    let mut positions = vec![end; n];
112    let mut j = end;
113    for i in (1..n).rev() {
114        j = from[i][j];
115        positions[i - 1] = j;
116    }
117    Some(Match {
118        score: top,
119        positions,
120    })
121}
122
123/// The items matching `query`, best first (ties keep their order), each
124/// with its match.
125pub fn rank<T>(items: &[T], query: &str, text: impl Fn(&T) -> String) -> Vec<(usize, Match)> {
126    let mut hits: Vec<(usize, Match)> = items
127        .iter()
128        .enumerate()
129        .filter_map(|(i, it)| score(query, &text(it)).map(|m| (i, m)))
130        .collect();
131    hits.sort_by_key(|(i, m)| (std::cmp::Reverse(m.score), *i));
132    hits
133}
134
135/// Matches `word` (one word of a query, case-insensitive) at the start
136/// of a word of `text`: the whole word or its beginning, never letters
137/// scattered over several words. For long text, such as a description,
138/// where [`score`] would find almost any short word somewhere.
139///
140/// ```
141/// use egui_pop_model::fuzzy;
142///
143/// let m = fuzzy::word_prefix("par", "Reads a paragraph").unwrap();
144/// assert_eq!(m.positions, [8, 9, 10]);
145/// assert!(fuzzy::word_prefix("agr", "Reads a paragraph").is_none());
146/// ```
147pub fn word_prefix(word: &str, text: &str) -> Option<Match> {
148    let q: Vec<char> = word.chars().filter(|c| !c.is_whitespace()).collect();
149    let t: Vec<char> = text.chars().collect();
150    if q.is_empty() {
151        return Some(Match {
152            score: 0,
153            positions: Vec::new(),
154        });
155    }
156    let n = q.len();
157    let mut best: Option<Match> = None;
158    for j in 0..t.len().saturating_sub(n - 1) {
159        if !word_start(&t, j) || !q.iter().zip(&t[j..j + n]).all(|(a, b)| same(*a, *b)) {
160            continue;
161        }
162        let mut s = MATCH * n as i32 + WORD_START + RUN * (n as i32 - 1);
163        // The whole word, not only its start.
164        if t.get(j + n).is_none_or(|c| !c.is_alphanumeric()) {
165            s += WORD_START;
166        }
167        if j == 0 {
168            s += TEXT_START;
169        }
170        s += q.iter().zip(&t[j..j + n]).filter(|(a, b)| a == b).count() as i32 * SAME_CASE;
171        s -= (j as i32).min(GAP_MAX);
172        if best.as_ref().is_none_or(|b| s > b.score) {
173            best = Some(Match {
174                score: s,
175                positions: (j..j + n).collect(),
176            });
177        }
178    }
179    best
180}
181
182/// Which kind of field a search word was found in, best first: a label
183/// before a keyword, a keyword before a description.
184#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
185pub enum Tier {
186    /// A name the user reads first (a title, a label): matched fuzzily.
187    Label,
188    /// A word given to be found by (a keyword, an id, a section's
189    /// title): matched fuzzily.
190    Keyword,
191    /// Running text (a description): matched by whole words or word
192    /// prefixes only ([`word_prefix`]).
193    Description,
194}
195
196/// What a search found in [`Fields`]: the worst tier any of the query's
197/// words needed, and the words' summed score. Sorting ascending puts
198/// the best first (tier, then the higher score).
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200pub struct Found {
201    pub tier: Tier,
202    pub score: i32,
203}
204
205impl Ord for Found {
206    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
207        self.tier
208            .cmp(&other.tier)
209            .then(other.score.cmp(&self.score))
210    }
211}
212
213impl PartialOrd for Found {
214    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
215        Some(self.cmp(other))
216    }
217}
218
219/// The fields of one thing a search field looks through (a setting, a
220/// page), each of a [`Tier`]: labels and keywords are matched fuzzily
221/// ([`score`]), descriptions by words and word prefixes
222/// ([`word_prefix`]), so a long description does not match a word
223/// whose letters it merely holds in order. Each field is matched on its
224/// own: a word never spans two fields.
225///
226/// ```
227/// use egui_pop_model::fuzzy::{Fields, Tier};
228///
229/// let wrap = Fields::new()
230///     .label("Soft wrap")
231///     .description("Lines break at the pane's edge, so a paragraph reads without scrolling; the file itself remains unchanged.");
232/// assert_eq!(wrap.find("swrp").unwrap().tier, Tier::Label);
233/// assert_eq!(wrap.find("parag").unwrap().tier, Tier::Description);
234/// assert!(wrap.find("specimen").is_none());
235/// ```
236#[derive(Clone, Debug, Default)]
237pub struct Fields {
238    fields: Vec<(Tier, String)>,
239}
240
241impl Fields {
242    pub fn new() -> Self {
243        Self::default()
244    }
245
246    /// A field of `tier`; empty text is left out.
247    pub fn field(mut self, tier: Tier, text: impl Into<String>) -> Self {
248        let text = text.into();
249        if !text.trim().is_empty() {
250            self.fields.push((tier, text));
251        }
252        self
253    }
254
255    pub fn label(self, text: impl Into<String>) -> Self {
256        self.field(Tier::Label, text)
257    }
258
259    pub fn keyword(self, text: impl Into<String>) -> Self {
260        self.field(Tier::Keyword, text)
261    }
262
263    pub fn keywords<S: Into<String>>(self, words: impl IntoIterator<Item = S>) -> Self {
264        words.into_iter().fold(self, |f, w| f.keyword(w))
265    }
266
267    pub fn description(self, text: impl Into<String>) -> Self {
268        self.field(Tier::Description, text)
269    }
270
271    /// Adds another's fields, keeping their tiers.
272    pub fn extend(mut self, other: Fields) -> Self {
273        self.fields.extend(other.fields);
274        self
275    }
276
277    /// One word's best field: the best tier, then the best score there.
278    fn word(&self, word: &str) -> Option<Found> {
279        self.fields
280            .iter()
281            .filter_map(|(tier, text)| {
282                let m = match tier {
283                    Tier::Label | Tier::Keyword => score(word, text),
284                    Tier::Description => word_prefix(word, text),
285                };
286                m.map(|m| Found {
287                    tier: *tier,
288                    score: m.score,
289                })
290            })
291            .min()
292    }
293
294    /// Whether every word of `query` (split on whitespace) is found, and
295    /// how well; an empty query matches with a score of 0.
296    pub fn find(&self, query: &str) -> Option<Found> {
297        let mut found = Found {
298            tier: Tier::Label,
299            score: 0,
300        };
301        for w in query.split_whitespace() {
302            let f = self.word(w)?;
303            found.tier = found.tier.max(f.tier);
304            found.score += f.score;
305        }
306        Some(found)
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    fn order(query: &str, items: &[&str]) -> Vec<String> {
315        rank(items, query, |s| s.to_string())
316            .into_iter()
317            .map(|(i, _)| items[i].to_string())
318            .collect()
319    }
320
321    #[test]
322    fn word_starts_and_runs_win() {
323        assert_eq!(
324            order(
325                "of",
326                &["Edit: Copy format", "File: Open file", "View: Zoom off"]
327            ),
328            ["File: Open file", "View: Zoom off", "Edit: Copy format"]
329        );
330        assert_eq!(
331            order("undo", &["Edit: Redo", "Edit: Undo", "View: Unfold doc"]),
332            ["Edit: Undo", "View: Unfold doc"]
333        );
334        // Camel case counts as a word start.
335        let m = score("ts", "toggleSidebar").unwrap();
336        assert_eq!(m.positions, [0, 6]);
337    }
338
339    #[test]
340    fn every_character_must_be_there_in_order() {
341        assert!(score("abc", "cab").is_none());
342        assert!(score("abcd", "abc").is_none());
343        assert_eq!(score("", "x").unwrap().score, 0);
344        let m = score("o p", "File: Open").unwrap();
345        assert_eq!(m.positions, [6, 7]);
346        // Non-ASCII text: positions are in characters.
347        assert_eq!(score("é", "Café").unwrap().positions, [3]);
348    }
349
350    #[test]
351    fn positions_are_increasing_and_point_at_matching_characters() {
352        let texts = [
353            "Command palette",
354            "View: Toggle side bar",
355            "settings/appearance.focus",
356            "aaaa bbbb aaaa",
357        ];
358        for t in texts {
359            let chars: Vec<char> = t.chars().collect();
360            for q in ["a", "ab", "cp", "vtsb", "sf", "aba", "e"] {
361                if let Some(m) = score(q, t) {
362                    assert!(m.positions.windows(2).all(|w| w[0] < w[1]), "{q} in {t}");
363                    let qc: Vec<char> = q.chars().collect();
364                    for (i, &p) in m.positions.iter().enumerate() {
365                        assert!(same(qc[i], chars[p]), "{q} in {t}");
366                    }
367                }
368            }
369        }
370    }
371
372    const WRAP: &str = "Soft wrap: lines break at the pane's edge, so a paragraph reads without scrolling; the file itself remains unchanged on disk.";
373
374    #[test]
375    fn a_long_description_does_not_match_scattered_letters() {
376        // The letters are all there, in order, over several words.
377        assert!(score("specimen", WRAP).is_some());
378        assert!(word_prefix("specimen", WRAP).is_none());
379        assert!(Fields::new().description(WRAP).find("specimen").is_none());
380        // Words and word prefixes still match, in any case.
381        assert!(word_prefix("Paragraph", WRAP).is_some());
382        assert!(word_prefix("scroll", WRAP).is_some());
383        assert!(word_prefix("ragraph", WRAP).is_none());
384        assert_eq!(
385            word_prefix("pane", WRAP).unwrap().positions,
386            [30, 31, 32, 33]
387        );
388    }
389
390    #[test]
391    fn fields_rank_label_then_keyword_then_description() {
392        let f = Fields::new()
393            .label("Text zoom")
394            .keyword("magnify")
395            .description("The size of the text, in percent.");
396        assert_eq!(f.find("tz").unwrap().tier, Tier::Label);
397        assert_eq!(f.find("mag").unwrap().tier, Tier::Keyword);
398        assert_eq!(f.find("percent").unwrap().tier, Tier::Description);
399        // A query's tier is its worst word's.
400        assert_eq!(f.find("zoom percent").unwrap().tier, Tier::Description);
401        assert!(f.find("zoom nothing").is_none());
402        assert_eq!(f.find("  ").unwrap().score, 0);
403        // Keywords match fuzzily, a description does not.
404        assert!(f.find("mgnf").is_some());
405        assert!(f.find("prcnt").is_none());
406        // A word does not span two fields.
407        assert!(Fields::new().label("ab").label("cd").find("abcd").is_none());
408        // Best first.
409        let label = Fields::new().label("Zoom").find("zoom").unwrap();
410        let desc = Fields::new().description("zoom").find("zoom").unwrap();
411        let mut v = [desc, label];
412        v.sort();
413        assert_eq!(v, [label, desc]);
414    }
415}