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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use crate::{selectable::SelectableItem, ui::ui};
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use nucleo::{
pattern::{CaseMatching, Normalization},
Config, Injector, Nucleo, Snapshot,
};
use ratatui::{prelude::CrosstermBackend, Terminal};
use std::{error, fmt::Display, io, sync::Arc};
pub type AppResult<T> = std::result::Result<T, Box<dyn error::Error>>;
// TODO convert static to a proper lifetime
pub struct Picker<T>
where
T: Sync + Send + 'static,
{
pub matcher: Nucleo<SelectableItem<T>>,
pub current_index: u32,
pub height: u16,
pub query: String,
pub query_index: usize,
}
impl<T: Sync + Send + Display> Default for Picker<T> {
fn default() -> Self {
Self::new()
}
}
// TODO maybe expose the Nucleo update callback
impl<T> Picker<T>
where
T: Sync + Send + Display,
{
pub fn new() -> Self {
let matcher = Nucleo::new(Config::DEFAULT, Arc::new(|| {}), None, 1);
Picker {
matcher,
current_index: 0,
height: 0,
query: String::new(),
query_index: 0,
}
}
pub fn inject_items<F>(&self, f: F)
where
F: FnOnce(&Injector<SelectableItem<T>>),
{
let injector = self.matcher.injector();
f(&injector);
}
pub fn tick(&mut self, timeout: u64) {
self.matcher.tick(timeout);
}
pub fn snapshot(&self) -> &Snapshot<SelectableItem<T>> {
self.matcher.snapshot()
}
pub fn items(&self) -> Vec<&SelectableItem<T>> {
self.snapshot().matched_items(..).map(|i| i.data).collect()
}
pub(crate) fn update_height(&mut self, height: u16) {
self.height = height;
}
pub(crate) fn selected_items(&self) -> Vec<&T> {
// NOTE: matched_items is not factored out due to ownership issues
let selected_items: Vec<&T> = self
.snapshot()
.matched_items(..)
.filter(|i| i.data.is_selected())
.map(|i| i.data.value())
.collect();
if !selected_items.is_empty() {
selected_items
} else {
self.snapshot()
.matched_items(..)
.nth(self.current_index as usize)
.map(|i| vec![i.data.value()])
.unwrap_or_default()
}
}
pub fn next(&mut self) {
let indices = self.snapshot().matched_item_count();
if indices == 0 {
return;
}
self.current_index = (self.current_index + 1) % indices;
}
fn next_page(&mut self) {
let indices = self.snapshot().matched_item_count();
if indices == 0 {
return;
}
let next_page_index = self.current_index + self.height as u32;
self.current_index = if next_page_index > indices {
indices
} else {
next_page_index
}
}
fn end(&mut self) {
let indices = self.snapshot().matched_item_count();
if indices == 0 {
return;
}
self.current_index = indices;
}
pub fn previous(&mut self) {
let indices = self.snapshot().matched_item_count();
if indices == 0 {
return;
}
self.current_index = if self.current_index == 0 {
indices - 1
} else {
self.current_index.saturating_sub(1)
};
}
pub fn previous_page(&mut self) {
let indices = self.snapshot().matched_item_count();
if indices == 0 {
return;
}
self.current_index = self.current_index.saturating_sub(self.height as u32);
}
fn home(&mut self) {
let indices = self.snapshot().matched_item_count();
if indices == 0 {
return;
}
self.current_index = 0;
}
pub fn toggle_selected(&mut self) {
let snapshot = self.snapshot();
if snapshot.matched_item_count() == 0 {
return;
}
// get the currently selected item and toggle it's selected state
if let Some(i) = snapshot.get_matched_item(self.current_index) {
i.data.toggle_selected();
};
}
pub(crate) fn append_to_query(&mut self, key: char) {
// TODO constrain selected item to match range
if self.query_index >= self.query.len() {
self.query.push(key);
} else {
self.query.insert(self.query_index, key);
}
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
true,
);
}
pub(crate) fn jump_word_forward(&mut self) {
let query_len = self.query.len();
if self.query_index >= query_len {
return;
}
// Start from current position
let remaining = &self.query[self.query_index..];
// Find the next word boundary
let mut chars = remaining.char_indices();
// Skip the current word if we're in the middle of one
while let Some((i, c)) = chars.next() {
if c.is_whitespace() {
break;
}
if i == remaining.len() - 1 {
// If we reach the end of the string, set index to the end
self.query_index = query_len;
return;
}
}
// Skip any whitespace
let mut word_start = 0;
while let Some((i, c)) = chars.next() {
if !c.is_whitespace() {
word_start = i;
break;
}
if i == remaining.len() - 1 {
// If we reach the end of the string, set index to the end
self.query_index = query_len;
return;
}
}
// Move to the start of the next word
self.query_index += word_start;
}
pub(crate) fn jump_word_backward(&mut self) {
if self.query_index == 0 {
return;
}
// Get the part of the query before the current position
let before_cursor = &self.query[..self.query_index];
// Find the previous word boundary
let chars: Vec<char> = before_cursor.chars().collect();
let mut pos = chars.len() - 1;
// Skip any whitespace before the cursor
while pos > 0 && chars[pos].is_whitespace() {
pos -= 1;
}
// Skip the current word
while pos > 0 && !chars[pos].is_whitespace() {
pos -= 1;
}
// If we stopped at whitespace and we're not at the beginning, move to the next char
if pos > 0 && chars[pos].is_whitespace() {
pos += 1;
}
self.query_index = pos;
}
pub(crate) fn delete_word_backward(&mut self) {
if self.query_index == 0 {
return;
}
// Get the part of the query before the current position
let before_cursor = &self.query[..self.query_index];
// Find the previous word boundary
let chars: Vec<char> = before_cursor.chars().collect();
let mut pos = chars.len() - 1;
// Skip any whitespace before the cursor
while pos > 0 && chars[pos].is_whitespace() {
pos -= 1;
}
// Skip the current word
while pos > 0 && !chars[pos].is_whitespace() {
pos -= 1;
}
// If we stopped at whitespace and we're not at the beginning, move to the next char
if pos > 0 && chars[pos].is_whitespace() {
pos += 1;
}
// Remove the characters between the new position and the old cursor position
self.query = format!("{}{}", &self.query[..pos], &self.query[self.query_index..]);
self.query_index = pos;
// Update the matcher
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
false,
);
}
pub(crate) fn delete_word_forward(&mut self) {
let query_len = self.query.len();
if self.query_index >= query_len {
return;
}
// Start from current position
let remaining = &self.query[self.query_index..];
// Find the next word boundary
let mut chars = remaining.char_indices();
let mut end_pos = query_len;
// If we're at the beginning of a word, delete that word
if let Some((_, first_char)) = chars.next() {
if !first_char.is_whitespace() {
// Skip until we hit whitespace or end
while let Some((i, c)) = chars.next() {
if c.is_whitespace() {
end_pos = self.query_index + i;
break;
}
}
} else {
// Skip whitespace
while let Some((i, c)) = chars.next() {
if !c.is_whitespace() {
// Then skip until next whitespace or end
while let Some((j, c2)) = chars.next() {
if c2.is_whitespace() {
end_pos = self.query_index + j;
break;
}
}
break;
}
}
}
}
// Remove the characters between the cursor position and the end position
self.query = format!(
"{}{}",
&self.query[..self.query_index],
&self.query[end_pos..]
);
// Update the matcher
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
false,
);
}
pub(crate) fn delete_to_end(&mut self) {
if self.query_index >= self.query.len() {
return;
}
// Truncate the query at the cursor position
self.query.truncate(self.query_index);
// Update the matcher
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
false,
);
}
pub(crate) fn delete_from_query(&mut self) {
if self.query_index > 0 && !self.query.is_empty() {
// Remove the character before the cursor
self.query.remove(self.query_index - 1);
}
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
false,
);
}
pub(crate) fn clear_query(&mut self) {
self.query.clear();
// TODO seems like there should be a better way to clear the query
self.matcher.pattern.reparse(
0,
&self.query,
CaseMatching::Smart,
Normalization::Smart,
false,
);
}
pub fn run(&mut self) -> AppResult<Vec<&T>> {
// Setup terminal
enable_raw_mode()?;
// TODO should we allow the caller to pass any arbitrary stream?
let mut stream = io::stderr();
execute!(stream, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stream);
let mut terminal = Terminal::new(backend)?;
let result = self.run_loop(&mut terminal);
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
result
}
pub(crate) fn run_loop<B: ratatui::backend::Backend>(
&mut self,
terminal: &mut Terminal<B>,
) -> AppResult<Vec<&T>> {
loop {
self.tick(10);
terminal.draw(|f| ui(f, self))?;
if let Ok(Event::Key(key)) = event::read() {
match (key.code, key.modifiers) {
(KeyCode::Char(key), KeyModifiers::NONE)
| (KeyCode::Char(key), KeyModifiers::SHIFT) => {
self.append_to_query(key);
// NOTE: this probably doesn't need to saturate, that would require an absurdly long query
self.query_index = self.query_index.saturating_add(1);
}
(KeyCode::Backspace, KeyModifiers::NONE) => {
self.delete_from_query();
// NOTE: this needs to saturate to handle deleting when the query is empty
self.query_index = self.query_index.saturating_sub(1);
}
// TODO find out if it's a local keybinding that's preventing `Ctrl + Backspace` from working or if it's actually a bug
(KeyCode::Backspace, KeyModifiers::CONTROL)
| (KeyCode::Backspace, KeyModifiers::ALT) => {
self.delete_word_backward();
}
(KeyCode::Right, KeyModifiers::NONE) => {
// NOTE: this probably doesn't need to saturate, that would require an absurdly long query
self.query_index = self.query_index.saturating_add(1);
}
(KeyCode::Right, KeyModifiers::CONTROL)
| (KeyCode::Right, KeyModifiers::ALT) => {
self.jump_word_forward();
}
(KeyCode::Left, KeyModifiers::NONE) => {
// NOTE: this needs to saturate to handle deleting when the query is empty
self.query_index = self.query_index.saturating_sub(1);
}
(KeyCode::Left, KeyModifiers::CONTROL) | (KeyCode::Left, KeyModifiers::ALT) => {
self.jump_word_backward();
}
(KeyCode::Delete, KeyModifiers::CONTROL)
| (KeyCode::Delete, KeyModifiers::ALT) => {
self.delete_word_forward();
}
(KeyCode::Esc, KeyModifiers::NONE) => {
return Ok(vec![]);
}
(KeyCode::Char('u'), KeyModifiers::CONTROL) => {
self.clear_query();
self.query_index = 0;
}
(KeyCode::Char('c'), KeyModifiers::CONTROL) => {
return Ok(vec![]);
}
(KeyCode::Char('a'), KeyModifiers::CONTROL) => {
self.query_index = 0;
}
(KeyCode::Char('e'), KeyModifiers::CONTROL) => {
self.query_index = self.query.len();
}
(KeyCode::Char('k'), KeyModifiers::CONTROL) => {
self.delete_to_end();
}
(KeyCode::Enter, KeyModifiers::NONE) => {
// Print selected items and exit
return Ok(self.selected_items());
}
(KeyCode::Down, KeyModifiers::NONE) => {
self.next();
}
(KeyCode::PageDown, KeyModifiers::NONE) => {
self.next_page();
}
(KeyCode::End, KeyModifiers::NONE) => {
self.end();
}
(KeyCode::Up, KeyModifiers::NONE) => {
self.previous();
}
(KeyCode::PageUp, KeyModifiers::NONE) => {
self.previous_page();
}
(KeyCode::Home, KeyModifiers::NONE) => {
self.home();
}
(KeyCode::Tab, KeyModifiers::NONE) => {
self.toggle_selected();
self.next();
}
// ignore other key codes
_ => {}
}
};
}
}
}