summaryrefslogtreecommitdiff
path: root/mut/neovim/pack/plugins/start/blink.cmp/lua/blink/cmp/fuzzy/fuzzy.rs
blob: b09bb99ba26919892607ceb5eb38e3bddfac3d4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// TODO: refactor this heresy

use crate::frecency::FrecencyTracker;
use crate::keyword;
use crate::lsp_item::LspItem;
use mlua::prelude::*;
use mlua::FromLua;
use mlua::Lua;
use std::collections::HashMap;
use std::collections::HashSet;

#[derive(Clone, Hash)]
pub struct FuzzyOptions {
    match_suffix: bool,
    use_typo_resistance: bool,
    use_frecency: bool,
    use_proximity: bool,
    nearby_words: Option<Vec<String>>,
    min_score: u16,
}

impl FromLua for FuzzyOptions {
    fn from_lua(value: LuaValue, _lua: &'_ Lua) -> LuaResult<Self> {
        if let Some(tab) = value.as_table() {
            let match_suffix: bool = tab.get("match_suffix").unwrap_or_default();
            let use_typo_resistance: bool = tab.get("use_typo_resistance").unwrap_or_default();
            let use_frecency: bool = tab.get("use_frecency").unwrap_or_default();
            let use_proximity: bool = tab.get("use_proximity").unwrap_or_default();
            let nearby_words: Option<Vec<String>> = tab.get("nearby_words").ok();
            let min_score: u16 = tab.get("min_score").unwrap_or_default();

            Ok(FuzzyOptions {
                match_suffix,
                use_typo_resistance,
                use_frecency,
                use_proximity,
                nearby_words,
                min_score,
            })
        } else {
            Err(mlua::Error::FromLuaConversionError {
                from: "LuaValue",
                to: "FuzzyOptions".to_string(),
                message: None,
            })
        }
    }
}

fn group_by_needle(
    line: &str,
    cursor_col: usize,
    haystack: &[String],
    match_suffix: bool,
) -> HashMap<String, Vec<(usize, String)>> {
    let mut items_by_needle: HashMap<String, Vec<(usize, String)>> = HashMap::new();
    for (idx, item_text) in haystack.iter().enumerate() {
        let needle = keyword::guess_keyword_from_item(item_text, line, cursor_col, match_suffix);
        let entry = items_by_needle.entry(needle).or_default();
        entry.push((idx, item_text.to_string()));
    }
    items_by_needle
}

pub fn fuzzy(
    line: &str,
    cursor_col: usize,
    haystack: &[LspItem],
    frecency: &FrecencyTracker,
    opts: FuzzyOptions,
) -> (Vec<i32>, Vec<u32>) {
    let haystack_labels = haystack
        .iter()
        .map(|s| s.filter_text.clone().unwrap_or(s.label.clone()))
        .collect::<Vec<_>>();
    let options = frizbee::Options {
        prefilter: !opts.use_typo_resistance,
        min_score: opts.min_score,
        stable_sort: false,
        ..Default::default()
    };

    // Items may have different fuzzy matching ranges, so we split them up by needle
    let mut matches = group_by_needle(line, cursor_col, &haystack_labels, opts.match_suffix)
        .into_iter()
        // Match on each needle and combine
        .flat_map(|(needle, haystack)| {
            let mut matches = frizbee::match_list(
                &needle,
                &haystack
                    .iter()
                    .map(|(_, str)| str.as_str())
                    .collect::<Vec<_>>(),
                options,
            );
            for mtch in matches.iter_mut() {
                mtch.index_in_haystack = haystack[mtch.index_in_haystack].0;
            }
            matches
        })
        .collect::<Vec<_>>();

    matches.sort_by_key(|mtch| mtch.index_in_haystack);
    for (idx, mtch) in matches.iter_mut().enumerate() {
        mtch.index = idx;
    }

    // Get the score for each match, adding score_offset, frecency and proximity bonus
    let nearby_words: HashSet<String> = HashSet::from_iter(opts.nearby_words.unwrap_or_default());
    let match_scores = matches
        .iter()
        .map(|mtch| {
            let frecency_score = if opts.use_frecency {
                frecency.get_score(&haystack[mtch.index_in_haystack]) as i32
            } else {
                0
            };
            let nearby_words_score = if opts.use_proximity {
                nearby_words
                    .get(&haystack_labels[mtch.index_in_haystack])
                    .map(|_| 2)
                    .unwrap_or(0)
            } else {
                0
            };
            let score_offset = haystack[mtch.index_in_haystack].score_offset;

            (mtch.score as i32) + frecency_score + nearby_words_score + score_offset
        })
        .collect::<Vec<_>>();

    // Find the highest score and filter out matches that are unreasonably lower than it
    if opts.use_typo_resistance {
        let max_score = matches.iter().map(|mtch| mtch.score).max().unwrap_or(0);
        let secondary_min_score = max_score.max(16) - 16;
        matches = matches
            .into_iter()
            .filter(|mtch| mtch.score >= secondary_min_score)
            .collect::<Vec<_>>();
    }

    // Return scores and indices
    (
        matches
            .iter()
            .map(|mtch| match_scores[mtch.index])
            .collect::<Vec<_>>(),
        matches
            .iter()
            .map(|mtch| mtch.index_in_haystack as u32)
            .collect::<Vec<_>>(),
    )
}

pub fn fuzzy_matched_indices(
    line: &str,
    cursor_col: usize,
    haystack: &[String],
    match_suffix: bool,
) -> Vec<Vec<usize>> {
    let mut matches = group_by_needle(line, cursor_col, haystack, match_suffix)
        .into_iter()
        .flat_map(|(needle, haystack)| {
            frizbee::match_list_for_matched_indices(
                &needle,
                &haystack
                    .iter()
                    .map(|(_, str)| str.as_str())
                    .collect::<Vec<_>>(),
            )
            .into_iter()
            .enumerate()
            .map(|(idx, matched_indices)| (haystack[idx].0, matched_indices))
            .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();
    matches.sort_by_key(|mtch| mtch.0);

    matches
        .into_iter()
        .map(|(_, matched_indices)| matched_indices)
        .collect::<Vec<_>>()
}