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
use anyhow::Result;
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use item::Item;
use list::List;
use pastel_colours::{
BLUE_FG, DARK_BLUE_BG, DARK_GREY_BG, DARK_GREY_FG, GREEN_FG, RESET_BG, RESET_FG,
};
use std::io::{stdout, Stdout, Write};
use std::time::Instant;
use termion::clear::CurrentLine;
use termion::cursor::DetectCursorPos;
use termion::cursor::Show;
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::{IntoRawMode, RawTerminal};
pub mod item;
mod list;
pub struct FuzzyFinder<T>
where
T: Clone,
{
search_term: String,
all_items: Vec<Item<T>>,
matches: Vec<Item<T>>,
console_offset: u16,
stdout: RawTerminal<Stdout>,
first: bool,
list: List<T>,
positive_space_remaining: u16,
}
impl<T> FuzzyFinder<T>
where
T: Clone,
{
fn new(functions: Vec<Item<T>>, lines_to_show: i8) -> Self {
// We need to know where to start rendering from. We can't do this later because
// we overwrite the cursor. Maybe we shouldn't do this? (TODO)
let mut stdout = stdout().into_raw_mode().unwrap();
write!(stdout, "{}", termion::cursor::Save).unwrap();
let mut positive_space_remaining = 0;
let console_offset = if stdout.cursor_pos().is_ok() {
let cursor_pos_y = stdout.cursor_pos().unwrap().1;
let terminal_height = termion::terminal_size().unwrap().1;
let starting_y = cursor_pos_y;
let ending_y = starting_y + lines_to_show as u16;
let space_remaining: i16 = terminal_height as i16 - ending_y as i16;
positive_space_remaining = if space_remaining < 0 {
space_remaining.abs().try_into().unwrap()
} else {
0
};
cursor_pos_y
} else {
log::error!("Cannot get cursor!");
0
};
FuzzyFinder {
search_term: String::from(""),
all_items: functions,
matches: vec![],
console_offset,
stdout,
first: true,
list: List::new(lines_to_show),
positive_space_remaining,
}
}
pub fn up(&mut self) -> Result<()> {
self.list.up(&self.matches);
self.update_matches();
self.render()
}
pub fn down(&mut self) -> Result<()> {
self.list.down();
self.update_matches();
self.render()
}
pub fn append(&mut self, c: char) -> Result<()> {
self.list.reset_selection();
// This is a normal key that we want to add to the search.
self.search_term = format!("{}{}", self.search_term, c);
self.update_matches();
self.render()
}
pub fn backspace(&mut self) -> Result<()> {
self.list.reset_selection();
if self.search_term.chars().count() > 0 {
self.search_term =
String::from(&self.search_term[..self.search_term.chars().count() - 1]);
let matcher = SkimMatcherV2::default();
for f in &mut self.all_items {
f.score = matcher.fuzzy_indices(&f.name, &self.search_term);
}
}
self.update_matches();
self.render()
}
fn render_space(&mut self) -> Result<()> {
// Drop down so we don't over-write the terminal line that instigated
// this run of lk.
write!(self.stdout, "{}", termion::cursor::Save).unwrap();
if self.first {
for _ in 0..self.list.lines_to_show {
writeln!(self.stdout, " ")?;
}
self.first = false
}
write!(self.stdout, "{}", termion::cursor::Restore).unwrap();
Ok(())
}
fn goto_start(&mut self) -> Result<()> {
write!(
self.stdout,
"{}",
termion::cursor::Goto(1, self.console_offset - self.positive_space_remaining)
)?;
Ok(())
}
fn render_items(&mut self) -> Result<()> {
self.goto_start()?;
for (index, item) in self.list.items.iter().enumerate() {
if item.is_blank {
writeln!(self.stdout, "{}", termion::clear::CurrentLine)?;
} else {
let fuzzy_indecies = &item.score.as_ref().unwrap().1;
// Do some string manipulation to colourise the indexed parts
let coloured_line = get_coloured_line(
fuzzy_indecies,
&item.name,
index == self.list.selected_index as usize,
);
writeln!(
self.stdout,
"{}{}{}",
termion::clear::CurrentLine,
// Go maximum left, so we're at the start of the line
termion::cursor::Left(1000),
coloured_line
)?;
}
}
Ok(())
}
fn render_prompt(&mut self) -> Result<()> {
// Render the prompt
let prompt_y = self.list.lines_to_show as u16 + 1;
let current_x = self.search_term.chars().count() + 2;
// Go to the bottom line, where we'll render the prompt
write!(
self.stdout,
"{CurrentLine}{}{CurrentLine}",
termion::cursor::Goto(current_x as u16, prompt_y + self.console_offset),
)?;
write!(
self.stdout,
"{Show}{}{BLUE_FG}${RESET_FG} {}",
termion::cursor::Goto(1, prompt_y + self.console_offset),
self.search_term
)?;
self.stdout.flush()?;
Ok(())
}
/// Gets functions that match our current criteria, sorted by score.
pub fn update_matches(&mut self) {
let matcher = SkimMatcherV2::default();
for f in &mut self.all_items {
f.score = matcher.fuzzy_indices(&f.name, &self.search_term);
}
let mut matches = self
.all_items
.iter()
.filter(|f| f.score.is_some())
.cloned()
.collect::<Vec<Item<T>>>();
log::info!(
"There are a total of {} item(s) and {} match(es)",
self.all_items.len(),
matches.len()
);
// We want these in the order of their fuzzy matched score, i.e. closed matches
matches.sort_by(|a, b| b.score.cmp(&a.score));
self.matches = matches;
self.list.update(&self.matches);
}
/// Renders the current result set
pub fn render(&mut self) -> Result<()> {
self.render_space()?;
self.render_items()?;
self.render_prompt()?;
Ok(())
}
/// The main entry point for the fuzzy finder.
pub fn find(items: Vec<Item<T>>, lines_to_show: i8) -> Result<Option<T>> {
let mut state = FuzzyFinder::new(items, lines_to_show);
state.update_matches();
state.render()?;
let mut stdin = termion::async_stdin().keys();
// Run 'sed -n l' to explore escape codes
let mut escaped = String::from("");
let mut instant = Instant::now();
loop {
// What's going on here? The problem is how we detect escape.
// The key presses we're interested in, e.g. the arrows, are all preceded by escape, ^[.
// E.g. up is ^[[A and down is ^[[B. So the question is how do we identify an escape
// key by itself? If it's ^[[A then that's ^[ followed almost instantly by [A. If we have
// ^[ followed by a pause then we know it's not an escape for some other key, but an
// escape by itself. That's what the 100 136His below.
// NB: some terminals might send these bytes too slowly and escape might not be caught.
// NB: some terminals might use different escape keys entirely.
if escaped == "^[" && instant.elapsed().as_micros() > 100 {
write!(state.stdout, "{}", termion::cursor::Restore)?;
break;
}
if let Some(Ok(key)) = stdin.next() {
match key {
// ctrl-c and ctrl-d are two ways to exit.
Key::Ctrl('c') => break,
Key::Ctrl('d') => break,
// NB: It'd be neat if we could use Key::Up and Key::Down but they don't
// work in raw mode. So we've got to deal with the escape codes manually.
// This captures the enter key
Key::Char('\n') => {
return if !state.matches.is_empty() {
// Tidy up the console lines we've been writing
for _ in state.console_offset
..state.console_offset + state.list.lines_to_show as u16 + 4
{
write!(state.stdout, "{}", termion::clear::CurrentLine,)?;
}
Ok(Some(
state.list.get_selected().item.as_ref().unwrap().to_owned(),
))
} else {
Ok(None)
};
}
Key::Char(c) => {
if !escaped.is_empty() {
escaped = format!("{}{}", escaped, c);
match escaped.as_str() {
"^[" => continue,
"^[[" => continue,
"^[[A" => {
escaped = String::from("");
state.up()?;
}
"^[[B" => {
escaped = String::from("");
state.down()?;
}
_ => {
// This is nothing we recognise so let's abandon the escape sequence.
escaped = String::from("");
}
}
} else {
state.append(c)?;
}
}
Key::Esc => {
// All we're doing here is recording that we've entered an escape sequence.
// It's actually handled when we handle chars.
if escaped.is_empty() {
escaped = String::from("^[");
instant = Instant::now();
}
}
Key::Backspace => {
state.backspace()?;
}
_ => {}
}
state.stdout.flush().unwrap();
}
}
Ok(None)
}
}
/// Highlights the line. Will highlight matching search items, and also indicate
/// if it's a selected item.
fn get_coloured_line(fuzzy_indecies: &[usize], text: &str, is_selected: bool) -> String {
// Do some string manipulation to colourise the indexed parts
let mut coloured_line = String::from("");
let mut start = 0;
let text_vec = text.chars().collect::<Vec<_>>();
for i in fuzzy_indecies {
let part = &text_vec[start..*i].iter().cloned().collect::<String>();
let matching_char = &text_vec[*i..*i + 1].iter().cloned().collect::<String>();
if is_selected {
coloured_line = format!(
"{coloured_line}{DARK_GREY_BG}{part}{RESET_BG}{DARK_BLUE_BG}{matching_char}{RESET_BG}"
);
} else {
coloured_line = format!("{coloured_line}{part}{DARK_BLUE_BG}{matching_char}{RESET_BG}");
}
start = i + 1;
}
let remaining_chars = &text_vec[start..text.chars().count()]
.iter()
.cloned()
.collect::<String>();
if is_selected {
let prompt: String = format!("{DARK_GREY_BG}{GREEN_FG}>{RESET_FG}{RESET_BG}",);
let spacer: String = format!("{DARK_GREY_FG} {RESET_FG}");
let remaining: String = format!("{DARK_GREY_BG}{remaining_chars}{RESET_BG}");
coloured_line = format!("{prompt}{spacer}{coloured_line}{remaining}");
} else {
coloured_line = format!("{DARK_GREY_BG} {RESET_BG} {coloured_line}{remaining_chars}");
}
coloured_line
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let result = 2 + 2;
assert_eq!(result, 4);
}
}