Skip to main content

rustaco_core/
fuzzy.rs

1//! Fuzzy matching for completion lists, and collecting the words of a text.
2
3use std::collections::HashSet;
4
5use crate::Rope;
6
7/// A fuzzy match: higher scores rank first; `matches` are the char indices of `word` that
8/// matched, for highlighting.
9#[derive(Clone, Debug, PartialEq)]
10pub struct FuzzyMatch {
11    pub score: f64,
12    pub matches: Vec<usize>,
13}
14
15fn is_boundary(word: &[char], i: usize) -> bool {
16    i == 0
17        || matches!(word[i - 1], '_' | '-' | '.' | ' ' | '/' | ':')
18        || (word[i].is_uppercase() && !word[i - 1].is_uppercase())
19}
20
21/// Scores `word` against what was typed, the way VS Code's completion filter does: every
22/// char of `pattern` in order, case-insensitively, with the first one at the start of the
23/// word or at a word boundary (after `_`, `-`, `.`, space, `/`, `:`, or a lower-to-upper
24/// case change). Matches at the start, consecutive chars, boundaries and the same case
25/// score higher. An empty pattern matches everything with score 0. `None` when it does not
26/// match.
27pub fn fuzzy_score(pattern: &str, word: &str) -> Option<FuzzyMatch> {
28    if pattern.is_empty() {
29        return Some(FuzzyMatch { score: 0.0, matches: Vec::new() });
30    }
31    let lower = |c: char| c.to_lowercase().next().unwrap_or(c);
32    // Most words in a list do not contain the pattern at all: reject those without
33    // allocating.
34    let mut rest = word.chars().map(lower);
35    if !pattern.chars().map(lower).all(|p| rest.any(|w| w == p)) {
36        return None;
37    }
38    let pat: Vec<char> = pattern.chars().collect();
39    let wrd: Vec<char> = word.chars().collect();
40    let p: Vec<char> = pat.iter().map(|&c| lower(c)).collect();
41    let w: Vec<char> = wrd.iter().map(|&c| lower(c)).collect();
42    let mut best: Option<FuzzyMatch> = None;
43    for first in 0..w.len() {
44        if w[first] != p[0] || !is_boundary(&wrd, first) {
45            continue;
46        }
47        let mut matches = vec![first];
48        let mut score = (if first == 0 { 8.0 } else { 5.0 }) + if wrd[first] == pat[0] { 1.0 } else { 0.0 };
49        let mut wi = first + 1;
50        let mut ok = true;
51        for pi in 1..p.len() {
52            while wi < w.len() && w[wi] != p[pi] {
53                wi += 1;
54            }
55            if wi >= w.len() {
56                ok = false;
57                break;
58            }
59            let consecutive = matches.last() == Some(&(wi - 1));
60            score += 1.0
61                + if consecutive { 3.0 } else { 0.0 }
62                + if is_boundary(&wrd, wi) { 4.0 } else { 0.0 }
63                + if wrd[wi] == pat[pi] { 1.0 } else { 0.0 };
64            matches.push(wi);
65            wi += 1;
66        }
67        if ok && best.as_ref().is_none_or(|b| score - first as f64 * 0.1 > b.score) {
68            best = Some(FuzzyMatch { score: score - first as f64 * 0.1, matches });
69        }
70        if first == 0 && best.is_some() {
71            break;
72        }
73    }
74    best
75}
76
77/// Filters and ranks completion candidates. `texts` are the strings matched against
78/// (filter text or label), `sort_texts` break ties. Returns indices into `texts` with their
79/// matches, best first; with `keep_order` (snippet choices) in the given order.
80pub fn rank_completions(
81    pattern: &str,
82    texts: &[String],
83    sort_texts: &[String],
84    keep_order: bool,
85) -> Vec<(usize, FuzzyMatch)> {
86    let mut scored: Vec<(usize, FuzzyMatch)> =
87        texts.iter().enumerate().filter_map(|(i, t)| fuzzy_score(pattern, t).map(|m| (i, m))).collect();
88    if !keep_order {
89        scored.sort_by(|a, b| {
90            b.1.score
91                .partial_cmp(&a.1.score)
92                .unwrap_or(std::cmp::Ordering::Equal)
93                .then_with(|| sort_texts[a.0].cmp(&sort_texts[b.0]))
94        });
95    }
96    scored
97}
98
99fn is_word_char(c: char) -> bool {
100    c.is_alphanumeric() || c == '_'
101}
102
103/// The distinct words (a letter or `_`, then letters, digits or `_`) of `lines`, in order of
104/// first appearance, at most `max`.
105pub fn collect_words(rope: &Rope, lines: std::ops::Range<usize>, max: usize) -> Vec<String> {
106    let end = lines.end.min(rope.len_lines());
107    let mut seen: HashSet<String> = HashSet::new();
108    let mut out = Vec::new();
109    let mut word = String::new();
110    let mut flush = |word: &mut String, out: &mut Vec<String>| {
111        if !word.is_empty() {
112            if !seen.contains(word.as_str()) {
113                seen.insert(word.clone());
114                out.push(std::mem::take(word));
115            } else {
116                word.clear();
117            }
118        }
119    };
120    for line in lines.start.min(end)..end {
121        for c in rope.line(line).chars() {
122            if is_word_char(c) && (!word.is_empty() || !c.is_numeric()) {
123                word.push(c);
124            } else {
125                flush(&mut word, &mut out);
126            }
127            if out.len() >= max {
128                return out;
129            }
130        }
131        flush(&mut word, &mut out);
132    }
133    out.truncate(max);
134    out
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn fuzzy_matches_prefixes_and_boundaries() {
143        let m = fuzzy_score("gv", "getValue").unwrap();
144        assert_eq!(m.matches, vec![0, 3]);
145        assert!(fuzzy_score("val", "getValue").is_some());
146        // The first char must sit at a boundary.
147        assert!(fuzzy_score("al", "getValue").is_none());
148        assert!(fuzzy_score("x", "getValue").is_none());
149        // A prefix beats a match further in; the same case scores a little higher.
150        let prefix = fuzzy_score("get", "getValue").unwrap().score;
151        let inner = fuzzy_score("get", "my_get").unwrap().score;
152        assert!(prefix > inner);
153        assert!(fuzzy_score("Get", "Get").unwrap().score > fuzzy_score("get", "Get").unwrap().score);
154        assert_eq!(fuzzy_score("", "anything").unwrap().score, 0.0);
155    }
156
157    #[test]
158    fn ranking_sorts_by_score_then_sort_text() {
159        let texts: Vec<String> = ["my_get", "getValue", "getter"].map(String::from).to_vec();
160        let ranked = rank_completions("get", &texts, &texts, false);
161        let order: Vec<usize> = ranked.iter().map(|r| r.0).collect();
162        assert_eq!(order[2], 0);
163        let kept = rank_completions("", &texts, &texts, true);
164        assert_eq!(kept.iter().map(|r| r.0).collect::<Vec<_>>(), vec![0, 1, 2]);
165    }
166
167    #[test]
168    fn words_are_distinct_and_skip_numbers() {
169        let rope = Rope::from_str("let a1 = b_2 + a1;\nfn 42x zé\n");
170        assert_eq!(collect_words(&rope, 0..3, 100), vec!["let", "a1", "b_2", "fn", "x", "zé"]);
171        assert_eq!(collect_words(&rope, 0..3, 2), vec!["let", "a1"]);
172    }
173}