Debian Codegraph @

helix-term/src/ui/picker/query.rs

raw symbols SCIP
1 use std::{collections::HashMap, mem, ops::Range, sync::Arc};
2
3 #[derive(Debug)]
4 pub(super) struct PickerQuery {
5 /// The column names of the picker.
6 column_names: Box<[Arc<str>]>,
7 /// The index of the primary column in `column_names`.
8 /// The primary column is selected by default unless another
9 /// field is specified explicitly with `%fieldname`.
10 primary_column: usize,
11 /// The mapping between column names and input in the query
12 /// for those columns.
13 inner: HashMap<Arc<str>, Arc<str>>,
14 /// The byte ranges of the input text which are used as input for each column.
15 /// This is calculated at parsing time for use in [Self::active_column].
16 /// This Vec is naturally sorted in ascending order and ranges do not overlap.
17 column_ranges: Vec<(Range<usize>, Option<Arc<str>>)>,
18 }
19
20 impl PartialEq<HashMap<Arc<str>, Arc<str>>> for PickerQuery {
21 fn eq(&self, other: &HashMap<Arc<str>, Arc<str>>) -> bool {
22 self.inner.eq(other)
23 }
24 }
25
26 impl PickerQuery {
27 pub(super) fn new<I: Iterator<Item = Arc<str>>>(
28 column_names: I,
29 primary_column: usize,
30 ) -> Self {
31 let column_names: Box<[_]> = column_names.collect();
32 let inner = HashMap::with_capacity(column_names.len());
33 let column_ranges = vec![(0..usize::MAX, Some(column_names[primary_column].clone()))];
34 Self {
35 column_names,
36 primary_column,
37 inner,
38 column_ranges,
39 }
40 }
41
42 pub(super) fn get(&self, column: &str) -> Option<&Arc<str>> {
43 self.inner.get(column)
44 }
45
46 pub(super) fn parse(&mut self, input: &str) -> HashMap<Arc<str>, Arc<str>> {
47 let mut fields: HashMap<Arc<str>, String> = HashMap::new();
48 let primary_field = &self.column_names[self.primary_column];
49 let mut escaped = false;
50 let mut in_field = false;
51 let mut field = None;
52 let mut text = String::new();
53 self.column_ranges.clear();
54 self.column_ranges
55 .push((0..usize::MAX, Some(primary_field.clone())));
56
57 macro_rules! finish_field {
58 () => {
59 let key = field.take().unwrap_or(primary_field);
60
61 // Trims one space from the end, enabling leading and trailing
62 // spaces in search patterns, while also retaining spaces as separators
63 // between column filters.
64 let pat = text.strip_suffix(' ').unwrap_or(&text);
65
66 if let Some(pattern) = fields.get_mut(key) {
67 pattern.push(' ');
68 pattern.push_str(pat);
69 } else {
70 fields.insert(key.clone(), pat.to_string());
71 }
72 text.clear();
73 };
74 }
75
76 for (idx, ch) in input.char_indices() {
77 match ch {
78 // Backslash escaping
79 _ if escaped => {
80 // '%' is the only character that is special cased.
81 // You can escape it to prevent parsing the text that
82 // follows it as a field name.
83 if ch != '%' {
84 text.push('\\');
85 }
86 text.push(ch);
87 escaped = false;
88 }
89 '\\' => escaped = !escaped,
90 '%' => {
91 if !text.is_empty() {
92 finish_field!();
93 }
94 let (range, _field) = self
95 .column_ranges
96 .last_mut()
97 .expect("column_ranges is non-empty");
98 range.end = idx;
99 in_field = true;
100 }
101 ' ' if in_field => {
102 text.clear();
103 in_field = false;
104 }
105 _ if in_field => {
106 text.push(ch);
107 // Go over all columns and their indices, find all that starts with field key,
108 // select a column that fits key the most.
109 field = self
110 .column_names
111 .iter()
112 .filter(|col| col.starts_with(&text))
113 // select "fittest" column
114 .min_by_key(|col| col.len());
115
116 // Update the column range for this column.
117 if let Some((_range, current_field)) = self
118 .column_ranges
119 .last_mut()
120 .filter(|(range, _)| range.end == usize::MAX)
121 {
122 *current_field = field.cloned();
123 } else {
124 self.column_ranges.push((idx..usize::MAX, field.cloned()));
125 }
126 }
127 _ => text.push(ch),
128 }
129 }
130
131 if !in_field && !text.is_empty() {
132 finish_field!();
133 }
134
135 let new_inner: HashMap<_, _> = fields
136 .into_iter()
137 .map(|(field, query)| (field, query.as_str().into()))
138 .collect();
139
140 mem::replace(&mut self.inner, new_inner)
141 }
142
143 /// Finds the column which the cursor is 'within' in the last parse.
144 ///
145 /// The cursor is considered to be within a column when it is placed within any
146 /// of a column's text. See the `active_column_test` unit test below for examples.
147 ///
148 /// `cursor` is a byte index that represents the location of the prompt's cursor.
149 pub fn active_column(&self, cursor: usize) -> Option<&Arc<str>> {
150 let point = self
151 .column_ranges
152 .partition_point(|(range, _field)| cursor > range.end);
153
154 self.column_ranges
155 .get(point)
156 .filter(|(range, _field)| cursor >= range.start && cursor <= range.end)
157 .and_then(|(_range, field)| field.as_ref())
158 }
159 }
160
161 #[cfg(test)]
162 mod test {
163 use helix_core::hashmap;
164
165 use super::*;
166
167 #[test]
168 fn parse_query_test() {
169 let mut query = PickerQuery::new(
170 [
171 "primary".into(),
172 "field1".into(),
173 "field2".into(),
174 "another".into(),
175 "anode".into(),
176 ]
177 .into_iter(),
178 0,
179 );
180
181 // Basic field splitting
182 query.parse("hello world");
183 assert_eq!(
184 query,
185 hashmap!(
186 "primary".into() => "hello world".into(),
187 )
188 );
189 query.parse("hello %field1 world %field2 !");
190 assert_eq!(
191 query,
192 hashmap!(
193 "primary".into() => "hello".into(),
194 "field1".into() => "world".into(),
195 "field2".into() => "!".into(),
196 )
197 );
198 query.parse("%field1 abc %field2 def xyz");
199 assert_eq!(
200 query,
201 hashmap!(
202 "field1".into() => "abc".into(),
203 "field2".into() => "def xyz".into(),
204 )
205 );
206
207 // Trailing space is trimmed
208 query.parse("hello ");
209 assert_eq!(
210 query,
211 hashmap!(
212 "primary".into() => "hello".into(),
213 )
214 );
215
216 // Unknown fields are trimmed.
217 query.parse("hello %foo");
218 assert_eq!(
219 query,
220 hashmap!(
221 "primary".into() => "hello".into(),
222 )
223 );
224
225 // Multiple words in a field
226 query.parse("hello %field1 a b c");
227 assert_eq!(
228 query,
229 hashmap!(
230 "primary".into() => "hello".into(),
231 "field1".into() => "a b c".into(),
232 )
233 );
234
235 // Escaping
236 query.parse(r#"hello\ world"#);
237 assert_eq!(
238 query,
239 hashmap!(
240 "primary".into() => r#"hello\ world"#.into(),
241 )
242 );
243 query.parse(r#"hello \%field1 world"#);
244 assert_eq!(
245 query,
246 hashmap!(
247 "primary".into() => "hello %field1 world".into(),
248 )
249 );
250 query.parse(r#"%field1 hello\ world"#);
251 assert_eq!(
252 query,
253 hashmap!(
254 "field1".into() => r#"hello\ world"#.into(),
255 )
256 );
257 query.parse(r#"hello %field1 a\"b"#);
258 assert_eq!(
259 query,
260 hashmap!(
261 "primary".into() => "hello".into(),
262 "field1".into() => r#"a\"b"#.into(),
263 )
264 );
265 query.parse(r#"%field1 hello\ world"#);
266 assert_eq!(
267 query,
268 hashmap!(
269 "field1".into() => r#"hello\ world"#.into(),
270 )
271 );
272 query.parse(r#"\bfoo\b"#);
273 assert_eq!(
274 query,
275 hashmap!(
276 "primary".into() => r#"\bfoo\b"#.into(),
277 )
278 );
279 query.parse(r#"\\n"#);
280 assert_eq!(
281 query,
282 hashmap!(
283 "primary".into() => r#"\\n"#.into(),
284 )
285 );
286
287 // Only the prefix of a field is required.
288 query.parse("hello %anot abc");
289 assert_eq!(
290 query,
291 hashmap!(
292 "primary".into() => "hello".into(),
293 "another".into() => "abc".into(),
294 )
295 );
296 // The shortest matching the prefix is selected.
297 query.parse("hello %ano abc");
298 assert_eq!(
299 query,
300 hashmap!(
301 "primary".into() => "hello".into(),
302 "anode".into() => "abc".into()
303 )
304 );
305 // Multiple uses of a column are concatenated with space separators.
306 query.parse("hello %field1 xyz %fie abc");
307 assert_eq!(
308 query,
309 hashmap!(
310 "primary".into() => "hello".into(),
311 "field1".into() => "xyz abc".into()
312 )
313 );
314 query.parse("hello %fie abc");
315 assert_eq!(
316 query,
317 hashmap!(
318 "primary".into() => "hello".into(),
319 "field1".into() => "abc".into()
320 )
321 );
322 // The primary column can be explicitly qualified.
323 query.parse("hello %fie abc %prim world");
324 assert_eq!(
325 query,
326 hashmap!(
327 "primary".into() => "hello world".into(),
328 "field1".into() => "abc".into()
329 )
330 );
331 }
332
333 #[test]
334 fn active_column_test() {
335 fn active_column<'a>(query: &'a mut PickerQuery, input: &str) -> Option<&'a str> {
336 let cursor = input.find('|').expect("cursor must be indicated with '|'");
337 let input = input.replace('|', "");
338 query.parse(&input);
339 query.active_column(cursor).map(AsRef::as_ref)
340 }
341
342 let mut query = PickerQuery::new(
343 ["primary".into(), "foo".into(), "bar".into()].into_iter(),
344 0,
345 );
346
347 assert_eq!(active_column(&mut query, "|"), Some("primary"));
348 assert_eq!(active_column(&mut query, "hello| world"), Some("primary"));
349 assert_eq!(active_column(&mut query, "|%foo hello"), Some("primary"));
350 assert_eq!(active_column(&mut query, "%foo|"), Some("foo"));
351 assert_eq!(active_column(&mut query, "%|"), None);
352 assert_eq!(active_column(&mut query, "%baz|"), None);
353 assert_eq!(active_column(&mut query, "%quiz%|"), None);
354 assert_eq!(active_column(&mut query, "%foo hello| world"), Some("foo"));
355 assert_eq!(active_column(&mut query, "%foo hello world|"), Some("foo"));
356 assert_eq!(active_column(&mut query, "%foo| hello world"), Some("foo"));
357 assert_eq!(active_column(&mut query, "%|foo hello world"), Some("foo"));
358 assert_eq!(active_column(&mut query, "%f|oo hello world"), Some("foo"));
359 assert_eq!(active_column(&mut query, "hello %f|oo world"), Some("foo"));
360 assert_eq!(
361 active_column(&mut query, "hello %f|oo world %bar !"),
362 Some("foo")
363 );
364 assert_eq!(
365 active_column(&mut query, "hello %foo wo|rld %bar !"),
366 Some("foo")
367 );
368 assert_eq!(
369 active_column(&mut query, "hello %foo world %bar !|"),
370 Some("bar")
371 );
372 }
373 }