1#[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
46pub 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 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 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
123pub 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
135pub 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
185pub enum Tier {
186 Label,
188 Keyword,
191 Description,
194}
195
196#[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#[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 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 pub fn extend(mut self, other: Fields) -> Self {
273 self.fields.extend(other.fields);
274 self
275 }
276
277 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 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 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 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 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 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 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 assert!(f.find("mgnf").is_some());
405 assert!(f.find("prcnt").is_none());
406 assert!(Fields::new().label("ab").label("cd").find("abcd").is_none());
408 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}