matchmaker/nucleo/
query.rs

1// Original code from https://github.com/helix-editor/helix (MPL 2.0)
2// Modified by Squirreljetpack, 2025
3
4use std::{collections::HashMap, mem, ops::Range, sync::Arc};
5
6pub struct PickerQuery {
7    /// The column names of the picker.
8    column_names: Box<[Arc<str>]>,
9    /// The index of the primary column in `column_names`.
10    /// The primary column is selected by default unless another
11    /// field is specified explicitly with `%fieldname`.
12    primary_column: usize,
13    /// The mapping between column names and input in the query
14    /// for those columns.
15    inner: HashMap<Arc<str>, Arc<str>>,
16    /// The byte ranges of the input text which are used as input for each column.
17    /// This is calculated at parsing time for use in [Self::active_column].
18    /// This Vec is naturally sorted in ascending order and ranges do not overlap.
19    column_ranges: Vec<(Range<usize>, Option<Arc<str>>)>,
20}
21
22impl PartialEq<HashMap<Arc<str>, Arc<str>>> for PickerQuery {
23    fn eq(&self, other: &HashMap<Arc<str>, Arc<str>>) -> bool {
24        self.inner.eq(other)
25    }
26}
27
28impl PickerQuery {
29    pub fn new<I: Iterator<Item = Arc<str>>>(column_names: I, primary_column: usize) -> Self {
30        let column_names: Box<[_]> = column_names.collect();
31        let inner = HashMap::with_capacity(column_names.len());
32        let column_ranges = vec![(0..usize::MAX, Some(column_names[primary_column].clone()))];
33        Self {
34            column_names,
35            primary_column,
36            inner,
37            column_ranges,
38        }
39    }
40
41    pub fn get(&self, column: &str) -> Option<&Arc<str>> {
42        self.inner.get(column)
43    }
44
45    pub fn parse(&mut self, input: &str) -> HashMap<Arc<str>, Arc<str>> {
46        let mut fields: HashMap<Arc<str>, String> = HashMap::new();
47        let primary_field = &self.column_names[self.primary_column];
48        let mut escaped = false;
49        let mut in_field = false;
50        let mut field = None;
51        let mut text = String::new();
52        self.column_ranges.clear();
53        self.column_ranges
54            .push((0..usize::MAX, Some(primary_field.clone())));
55
56        macro_rules! finish_field {
57            () => {
58                let key = field.take().unwrap_or(primary_field);
59
60                // Trims one space from the end, enabling leading and trailing
61                // spaces in search patterns, while also retaining spaces as separators
62                // between column filters.
63                let pat = text.strip_suffix(' ').unwrap_or(&text);
64
65                if let Some(pattern) = fields.get_mut(key) {
66                    pattern.push(' ');
67                    pattern.push_str(pat);
68                } else {
69                    fields.insert(key.clone(), pat.to_string());
70                }
71                text.clear();
72            };
73        }
74
75        for (idx, ch) in input.char_indices() {
76            match ch {
77                // Backslash escaping
78                _ if escaped => {
79                    // '%' is the only character that is special cased.
80                    // You can escape it to prevent parsing the text that
81                    // follows it as a field name.
82                    if ch != '%' {
83                        text.push('\\');
84                    }
85                    text.push(ch);
86                    escaped = false;
87                }
88                '\\' => escaped = !escaped,
89                '%' => {
90                    if !text.is_empty() {
91                        finish_field!();
92                    }
93                    let (range, _field) = self
94                        .column_ranges
95                        .last_mut()
96                        .expect("column_ranges is non-empty");
97                    range.end = idx;
98                    in_field = true;
99                }
100                ' ' if in_field => {
101                    text.clear();
102                    in_field = false;
103                }
104                _ if in_field => {
105                    text.push(ch);
106                    // Go over all columns and their indices, find all that starts with field key,
107                    // select a column that fits key the most.
108                    field = self
109                        .column_names
110                        .iter()
111                        .filter(|col| col.starts_with(&text))
112                        // select "fittest" column
113                        .min_by_key(|col| col.len());
114
115                    // Update the column range for this column.
116                    if let Some((_range, current_field)) = self
117                        .column_ranges
118                        .last_mut()
119                        .filter(|(range, _)| range.end == usize::MAX)
120                    {
121                        *current_field = field.cloned();
122                    } else {
123                        self.column_ranges.push((idx..usize::MAX, field.cloned()));
124                    }
125                }
126                _ => text.push(ch),
127            }
128        }
129
130        if !in_field && !text.is_empty() {
131            finish_field!();
132        }
133
134        let new_inner: HashMap<_, _> = fields
135            .into_iter()
136            .map(|(field, query)| (field, query.as_str().into()))
137            .collect();
138
139        mem::replace(&mut self.inner, new_inner)
140    }
141
142    /// Finds the column which the cursor is 'within' in the last parse.
143    ///
144    /// The cursor is considered to be within a column when it is placed within any
145    /// of a column's text. See the `active_column_test` unit test below for examples.
146    ///
147    /// `cursor` is a byte index that represents the location of the prompt's cursor.
148    pub fn active_column(&self, cursor: usize) -> Option<&Arc<str>> {
149        let point = self
150            .column_ranges
151            .partition_point(|(range, _field)| cursor > range.end);
152
153        self.column_ranges
154            .get(point)
155            .filter(|(range, _field)| cursor >= range.start && cursor <= range.end)
156            .and_then(|(_range, field)| field.as_ref())
157    }
158}