1use std::collections::HashSet;
4
5use crate::Rope;
6
7#[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
21pub 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 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
77pub 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
103pub 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 assert!(fuzzy_score("al", "getValue").is_none());
148 assert!(fuzzy_score("x", "getValue").is_none());
149 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}