on master help sign in
Merge pull request #7 from helix-editor/interactive-split-select

File picker/interactive split prompt

commit3f0dbfcac878131167953b6f57c923a5bc889e80 authorBlaž Hrastnik <blaz@mxxn.io> dateFri 18 Dec 2020, 19:24 (6 years ago) parentb12a6dc25aa45e
12 files changed+572−42
Cargo.lock+137−12 helix-lsp/Cargo.toml+5−4 helix-term/Cargo.toml+4 helix-term/src/commands.rs+77−4 helix-term/src/compositor.rs+1−1 helix-term/src/keymap.rs+3 helix-term/src/ui/editor.rs+1−1 helix-term/src/ui/helix.log helix-term/src/ui/mod.rs+35−1 helix-term/src/ui/picker.rs+258 helix-term/src/ui/prompt.rs+43−18 helix-view/src/document.rs+8−1
Cargo.lock+137−12
@@ -181,6 +181,15 @@ dependencies = [
181181 "once_cell",
182182]
183183
184+[[package]]
185+name = "bstr"
186+version = "0.2.14"
187+source = "registry+https://github.com/rust-lang/crates.io-index"
188+checksum = "473fc6b38233f9af7baa94fb5852dca389e3d95b8e21c8e3719301462c5d9faf"
189+dependencies = [
190+ "memchr",
191+]
192+
184193[[package]]
185194name = "cache-padded"
186195version = "1.1.1"
@@ -339,6 +348,12 @@ dependencies = [
339348 "log",
340349]
341350
351+[[package]]
352+name = "fnv"
353+version = "1.0.7"
354+source = "registry+https://github.com/rust-lang/crates.io-index"
355+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
356+
342357[[package]]
343358name = "form_urlencoded"
344359version = "1.0.0"
@@ -361,9 +376,28 @@ dependencies = [
361376
362377[[package]]
363378name = "futures"
364−version = "0.1.30"
379+version = "0.3.8"
365380source = "registry+https://github.com/rust-lang/crates.io-index"
366−checksum = "4c7e4c2612746b0df8fed4ce0c69156021b704c9aefa360311c04e6e9e002eed"
381+checksum = "9b3b0c040a1fe6529d30b3c5944b280c7f0dcb2930d2c3062bca967b602583d0"
382+dependencies = [
383+ "futures-channel",
384+ "futures-core",
385+ "futures-executor",
386+ "futures-io",
387+ "futures-sink",
388+ "futures-task",
389+ "futures-util",
390+]
391+
392+[[package]]
393+name = "futures-channel"
394+version = "0.3.8"
395+source = "registry+https://github.com/rust-lang/crates.io-index"
396+checksum = "4b7109687aa4e177ef6fe84553af6280ef2778bdb7783ba44c9dc3399110fe64"
397+dependencies = [
398+ "futures-core",
399+ "futures-sink",
400+]
367401
368402[[package]]
369403name = "futures-core"
@@ -371,6 +405,17 @@ version = "0.3.8"
371405source = "registry+https://github.com/rust-lang/crates.io-index"
372406checksum = "847ce131b72ffb13b6109a221da9ad97a64cbe48feb1028356b836b47b8f1748"
373407
408+[[package]]
409+name = "futures-executor"
410+version = "0.3.8"
411+source = "registry+https://github.com/rust-lang/crates.io-index"
412+checksum = "4caa2b2b68b880003057c1dd49f1ed937e38f22fcf6c212188a121f08cf40a65"
413+dependencies = [
414+ "futures-core",
415+ "futures-task",
416+ "futures-util",
417+]
418+
374419[[package]]
375420name = "futures-io"
376421version = "0.3.8"
@@ -404,6 +449,12 @@ dependencies = [
404449 "syn",
405450]
406451
452+[[package]]
453+name = "futures-sink"
454+version = "0.3.8"
455+source = "registry+https://github.com/rust-lang/crates.io-index"
456+checksum = "f878195a49cee50e006b02b93cf7e0a95a38ac7b776b4c4d9cc1207cd20fcb3d"
457+
407458[[package]]
408459name = "futures-task"
409460version = "0.3.8"
@@ -419,9 +470,13 @@ version = "0.3.8"
419470source = "registry+https://github.com/rust-lang/crates.io-index"
420471checksum = "d304cff4a7b99cfb7986f7d43fbe93d175e72e704a8860787cc95e9ffd85cbd2"
421472dependencies = [
473+ "futures-channel",
422474 "futures-core",
475+ "futures-io",
423476 "futures-macro",
477+ "futures-sink",
424478 "futures-task",
479+ "memchr",
425480 "pin-project",
426481 "pin-utils",
427482 "proc-macro-hack",
@@ -429,6 +484,15 @@ dependencies = [
429484 "slab",
430485]
431486
487+[[package]]
488+name = "fuzzy-matcher"
489+version = "0.3.7"
490+source = "registry+https://github.com/rust-lang/crates.io-index"
491+checksum = "54614a3312934d066701a80f20f15fa3b56d67ac7722b39eea5b4c9dd1d66c94"
492+dependencies = [
493+ "thread_local",
494+]
495+
432496[[package]]
433497name = "getrandom"
434498version = "0.1.15"
@@ -446,6 +510,19 @@ version = "0.3.0"
446510source = "registry+https://github.com/rust-lang/crates.io-index"
447511checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574"
448512
513+[[package]]
514+name = "globset"
515+version = "0.4.6"
516+source = "registry+https://github.com/rust-lang/crates.io-index"
517+checksum = "c152169ef1e421390738366d2f796655fec62621dabbd0fd476f905934061e4a"
518+dependencies = [
519+ "aho-corasick",
520+ "bstr",
521+ "fnv",
522+ "log",
523+ "regex",
524+]
525+
449526[[package]]
450527name = "hashbrown"
451528version = "0.9.1"
@@ -508,9 +585,11 @@ dependencies = [
508585 "crossterm",
509586 "fern",
510587 "futures-util",
588+ "fuzzy-matcher",
511589 "helix-core",
512590 "helix-lsp",
513591 "helix-view",
592+ "ignore",
514593 "log",
515594 "num_cpus",
516595 "once_cell",
@@ -551,11 +630,29 @@ dependencies = [
551630 "unicode-normalization",
552631]
553632
633+[[package]]
634+name = "ignore"
635+version = "0.4.17"
636+source = "registry+https://github.com/rust-lang/crates.io-index"
637+checksum = "b287fb45c60bb826a0dc68ff08742b9d88a2fea13d6e0c286b3172065aaf878c"
638+dependencies = [
639+ "crossbeam-utils",
640+ "globset",
641+ "lazy_static",
642+ "log",
643+ "memchr",
644+ "regex",
645+ "same-file",
646+ "thread_local",
647+ "walkdir",
648+ "winapi-util",
649+]
650+
554651[[package]]
555652name = "indexmap"
556−version = "1.6.0"
653+version = "1.6.1"
557654source = "registry+https://github.com/rust-lang/crates.io-index"
558−checksum = "55e2e4c765aa53a0424761bf9f41aa7a6ac1efa87238f59560640e27fca028f2"
655+checksum = "4fb1fa934250de4de8aef298d81c729a7d33d8c239daa3a7575e6b92bfc7313b"
559656dependencies = [
560657 "autocfg",
561658 "hashbrown",
@@ -587,9 +684,9 @@ dependencies = [
587684
588685[[package]]
589686name = "jsonrpc-core"
590−version = "15.1.0"
687+version = "16.0.0"
591688source = "registry+https://github.com/rust-lang/crates.io-index"
592−checksum = "0745a6379e3edc893c84ec203589790774e4247420033e71a76d3ab4687991fa"
689+checksum = "6a47c4c3ac843f9a4238943f97620619033dadef4b378cd1e8addd170de396b3"
593690dependencies = [
594691 "futures",
595692 "log",
@@ -630,9 +727,9 @@ dependencies = [
630727
631728[[package]]
632729name = "lsp-types"
633−version = "0.84.0"
730+version = "0.85.0"
634731source = "registry+https://github.com/rust-lang/crates.io-index"
635−checksum = "3b95be71fe205e44de754185bcf86447b65813ce1ceb298f8d3793ade5fff08d"
732+checksum = "857650f3e83fb62f89d15410414e0ed7d0735445020da398d37f65d20a5423b9"
636733dependencies = [
637734 "base64 0.12.3",
638735 "bitflags",
@@ -929,6 +1026,15 @@ version = "1.0.5"
9291026source = "registry+https://github.com/rust-lang/crates.io-index"
9301027checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
9311028
1029+[[package]]
1030+name = "same-file"
1031+version = "1.0.6"
1032+source = "registry+https://github.com/rust-lang/crates.io-index"
1033+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
1034+dependencies = [
1035+ "winapi-util",
1036+]
1037+
9321038[[package]]
9331039name = "scopeguard"
9341040version = "1.1.0"
@@ -1038,13 +1144,12 @@ dependencies = [
10381144
10391145[[package]]
10401146name = "socket2"
1041−version = "0.3.17"
1147+version = "0.3.18"
10421148source = "registry+https://github.com/rust-lang/crates.io-index"
1043−checksum = "2c29947abdee2a218277abeca306f25789c938e500ea5a9d4b12a5a504466902"
1149+checksum = "97e0e9fd577458a4f61fb91fcb559ea2afecc54c934119421f9f5d3d5b1a1057"
10441150dependencies = [
10451151 "cfg-if 1.0.0",
10461152 "libc",
1047− "redox_syscall",
10481153 "winapi",
10491154]
10501155
@@ -1146,7 +1251,7 @@ dependencies = [
11461251[[package]]
11471252name = "tui"
11481253version = "0.13.0"
1149−source = "git+https://github.com/fdehau/tui-rs#74243394d90ea1316b6bedac6c9e4f26971c76b6"
1254+source = "git+https://github.com/fdehau/tui-rs#eb1e3be7228509e42cbcbaef610e6bd5c5f64ba6"
11501255dependencies = [
11511256 "bitflags",
11521257 "cassowary",
@@ -1228,6 +1333,17 @@ version = "1.1.0"
12281333source = "registry+https://github.com/rust-lang/crates.io-index"
12291334checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca"
12301335
1336+[[package]]
1337+name = "walkdir"
1338+version = "2.3.1"
1339+source = "registry+https://github.com/rust-lang/crates.io-index"
1340+checksum = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d"
1341+dependencies = [
1342+ "same-file",
1343+ "winapi",
1344+ "winapi-util",
1345+]
1346+
12311347[[package]]
12321348name = "wasi"
12331349version = "0.9.0+wasi-snapshot-preview1"
@@ -1265,6 +1381,15 @@ version = "0.4.0"
12651381source = "registry+https://github.com/rust-lang/crates.io-index"
12661382checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
12671383
1384+[[package]]
1385+name = "winapi-util"
1386+version = "0.1.5"
1387+source = "registry+https://github.com/rust-lang/crates.io-index"
1388+checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
1389+dependencies = [
1390+ "winapi",
1391+]
1392+
12681393[[package]]
12691394name = "winapi-x86_64-pc-windows-gnu"
12701395version = "0.4.0"
helix-lsp/Cargo.toml+5−4
@@ -9,9 +9,10 @@ edition = "2018"
99[dependencies]
1010helix-core = { path = "../helix-core" }
1111helix-view = { path = "../helix-view" }
12+
1213once_cell = "1.4"
1314
14−lsp-types = { version = "0.84", features = ["proposed"] }
15+lsp-types = { version = "0.85", features = ["proposed"] }
1516smol = "1.2"
1617url = "2"
1718pathdiff = "0.2"
@@ -20,7 +21,7 @@ glob = "0.3"
2021anyhow = "1"
2122serde_json = "1.0"
2223serde = { version = "1.0", features = ["derive"] }
23−jsonrpc-core = "15.1"
24+jsonrpc-core = "16.0"
2425futures-util = "0.3"
25−thiserror = "1"
26−log = "0.4"
26+thiserror = "1.0"
27+log = "~0.4"
helix-term/Cargo.toml+4
@@ -32,3 +32,7 @@ futures-util = "0.3"
3232fern = "0.6"
3333chrono = "0.4"
3434log = "0.4"
35+
36+# File picker
37+fuzzy-matcher = "0.3"
38+ignore = "0.4"
helix-term/src/commands.rs+77−4
@@ -10,7 +10,7 @@ use helix_core::{
1010use once_cell::sync::Lazy;
1111
1212use crate::compositor::Compositor;
13−use crate::ui::Prompt;
13+use crate::ui::{self, Prompt, PromptEvent};
1414
1515use helix_view::{
1616 document::Mode,
@@ -248,6 +248,60 @@ pub fn extend_line_down(cx: &mut Context) {
248248 cx.view.doc.set_selection(selection);
249249}
250250
251+pub fn split_selection(cx: &mut Context) {
252+ // TODO: this needs to store initial selection state, revert on esc, confirm on enter
253+ // needs to also call the callback function per input change, not just final time.
254+ // could cheat and put it into completion_fn
255+ //
256+ // kakoune does it like this:
257+ // # save state to register
258+ // {
259+ // # restore state from register
260+ // # if event == abort, return early
261+ // # add to history if enabled
262+ // # update state
263+ // }
264+
265+ let snapshot = cx.view.doc.state.clone();
266+
267+ let prompt = Prompt::new(
268+ "split:".to_string(),
269+ |input: &str| Vec::new(), // this is fine because Vec::new() doesn't allocate
270+ move |editor: &mut Editor, input: &str, event: PromptEvent| {
271+ match event {
272+ PromptEvent::Abort => {
273+ // revert state
274+ let view = editor.view_mut().unwrap();
275+ view.doc.state = snapshot.clone();
276+ }
277+ PromptEvent::Validate => {
278+ //
279+ }
280+ PromptEvent::Update => {
281+ match Regex::new(input) {
282+ Ok(regex) => {
283+ let view = editor.view_mut().unwrap();
284+
285+ // revert state to what it was before the last update
286+ view.doc.state = snapshot.clone();
287+
288+ let text = &view.doc.text().slice(..);
289+ let selection =
290+ selection::split_on_matches(text, view.doc.selection(), &regex);
291+ view.doc.set_selection(selection);
292+ }
293+ Err(_) => (), // TODO: mark command line as error
294+ }
295+ }
296+ }
297+ },
298+ );
299+
300+ cx.callback = Some(Box::new(move |compositor: &mut Compositor| {
301+ compositor.push(Box::new(prompt));
302+ }));
303+}
304+
251305pub fn split_selection_on_newline(cx: &mut Context) {
252306 let text = &cx.view.doc.text().slice(..);
253307 // only compile the regex once
@@ -381,14 +435,33 @@ pub fn command_mode(cx: &mut Context) {
381435 .filter(|command| command.contains(_input))
382436 .collect()
383437 }, // completion
384− |editor: &mut Editor, input: &str| match input {
385− "q" => editor.should_close = true,
386− _ => (),
438+ |editor: &mut Editor, input: &str, event: PromptEvent| {
439+ if event != PromptEvent::Validate {
440+ return;
441+ }
442+
443+ let parts = input.split_ascii_whitespace().collect::<Vec<&str>>();
444+
445+ match parts.as_slice() {
446+ &["q"] => editor.should_close = true,
447+ &["o", path] => {
448+ // TODO: make view()/view_mut() always contain a view.
449+ let size = editor.view().unwrap().size;
450+ editor.open(path.into(), size);
451+ }
452+ _ => (),
453+ }
387454 },
388455 );
389456 compositor.push(Box::new(prompt));
390457 }));
391458}
459+pub fn file_picker(cx: &mut Context) {
460+ cx.callback = Some(Box::new(|compositor: &mut Compositor| {
461+ let picker = ui::file_picker("./");
462+ compositor.push(Box::new(picker));
463+ }));
464+}
392465
393466// calculate line numbers for each selection range
394467fn selection_lines(state: &State) -> Vec<usize> {
helix-term/src/compositor.rs+1−1
@@ -19,7 +19,7 @@ use smol::Executor;
1919use tui::buffer::Buffer as Surface;
2020use tui::layout::Rect;
2121
22−pub type Callback = Box<dyn Fn(&mut Compositor)>;
22+pub type Callback = Box<dyn FnOnce(&mut Compositor)>;
2323
2424// --> EventResult should have a callback that takes a context with methods like .popup(),
2525// .prompt() etc. That way we can abstract it from the renderer.
helix-term/src/keymap.rs+3
@@ -157,6 +157,7 @@ pub fn default() -> Keymaps {
157157 vec![key!('d')] => commands::delete_selection,
158158 vec![key!('c')] => commands::change_selection,
159159 vec![key!('s')] => commands::split_selection_on_newline,
160+ vec![shift!('S')] => commands::split_selection,
160161 vec![key!(';')] => commands::collapse_selection,
161162 // TODO should be alt(;)
162163 vec![key!('%')] => commands::flip_selections,
@@ -182,6 +183,8 @@ pub fn default() -> Keymaps {
182183 }] => commands::page_down,
183184 vec![ctrl!('u')] => commands::half_page_up,
184185 vec![ctrl!('d')] => commands::half_page_down,
186+
187+ vec![ctrl!('p')] => commands::file_picker,
185188 ),
186189 Mode::Insert => hashmap!(
187190 vec![Key {
helix-term/src/ui/editor.rs+1−1
@@ -226,7 +226,7 @@ impl EditorView {
226226 );
227227 surface.set_string(1, viewport.y, mode, text_color);
228228
229− if let Some(path) = view.doc.path() {
229+ if let Some(path) = view.doc.relative_path() {
230230 surface.set_string(6, viewport.y, path.to_string_lossy(), text_color);
231231 }
232232
helix-term/src/ui/helix.lognew file

No changes to the content.

helix-term/src/ui/mod.rs+35−1
@@ -1,8 +1,10 @@
11mod editor;
2+mod picker;
23mod prompt;
34
45pub use editor::EditorView;
5−pub use prompt::Prompt;
6+pub use picker::Picker;
7+pub use prompt::{Prompt, PromptEvent};
68
79pub use tui::layout::Rect;
810pub use tui::style::{Color, Modifier, Style};
@@ -12,3 +14,35 @@ pub use tui::style::{Color, Modifier, Style};
1214pub fn text_color() -> Style {
1315 Style::default().fg(Color::Rgb(219, 191, 239)) // lilac
1416}
17+
18+use std::path::PathBuf;
19+pub fn file_picker(root: &str) -> Picker<PathBuf> {
20+ use ignore::Walk;
21+ // TODO: determine root based on git root
22+ let files = Walk::new(root).filter_map(|entry| match entry {
23+ Ok(entry) => {
24+ // filter dirs, but we might need special handling for symlinks!
25+ if !entry.file_type().unwrap().is_dir() {
26+ Some(entry.into_path())
27+ } else {
28+ None
29+ }
30+ }
31+ Err(_err) => None,
32+ });
33+
34+ const MAX: usize = 1024;
35+
36+ use helix_view::Editor;
37+ Picker::new(
38+ files.take(MAX).collect(),
39+ |path: &PathBuf| {
40+ // format_fn
41+ path.strip_prefix("./").unwrap().to_str().unwrap() // TODO: render paths without ./
42+ },
43+ |editor: &mut Editor, path: &PathBuf| {
44+ let size = editor.view().unwrap().size;
45+ editor.open(path.into(), size);
46+ },
47+ )
48+}
helix-term/src/ui/picker.rsnew file+258
@@ -0,0 +1,258 @@
1+use crate::compositor::{Component, Compositor, Context, EventResult};
2+use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
3+use tui::buffer::Buffer as Surface;
4+use tui::{
5+ layout::Rect,
6+ style::{Color, Style},
7+ widgets::{Block, Borders},
8+};
9+
10+use fuzzy_matcher::skim::SkimMatcherV2 as Matcher;
11+use fuzzy_matcher::FuzzyMatcher;
12+
13+use crate::ui::{Prompt, PromptEvent};
14+use helix_core::Position;
15+use helix_view::Editor;
16+
17+pub struct Picker<T> {
18+ options: Vec<T>,
19+ // filter: String,
20+ matcher: Box<Matcher>,
21+ /// (index, score)
22+ matches: Vec<(usize, i64)>,
23+
24+ cursor: usize,
25+ // pattern: String,
26+ prompt: Prompt,
27+
28+ format_fn: Box<dyn Fn(&T) -> &str>,
29+ callback_fn: Box<dyn Fn(&mut Editor, &T)>,
30+}
31+
32+impl<T> Picker<T> {
33+ pub fn new(
34+ options: Vec<T>,
35+ format_fn: impl Fn(&T) -> &str + 'static,
36+ callback_fn: impl Fn(&mut Editor, &T) + 'static,
37+ ) -> Self {
38+ let prompt = Prompt::new(
39+ "".to_string(),
40+ |pattern: &str| Vec::new(),
41+ |editor: &mut Editor, pattern: &str, event: PromptEvent| {
42+ //
43+ },
44+ );
45+
46+ let mut picker = Self {
47+ options,
48+ matcher: Box::new(Matcher::default()),
49+ matches: Vec::new(),
50+ cursor: 0,
51+ prompt,
52+ format_fn: Box::new(format_fn),
53+ callback_fn: Box::new(callback_fn),
54+ };
55+
56+ // TODO: scoring on empty input should just use a fastpath
57+ picker.score();
58+
59+ picker
60+ }
61+
62+ pub fn score(&mut self) {
63+ // need to borrow via pattern match otherwise it complains about simultaneous borrow
64+ let Self {
65+ ref mut options,
66+ ref mut matcher,
67+ ref mut matches,
68+ ref format_fn,
69+ ..
70+ } = *self;
71+
72+ let pattern = &self.prompt.line;
73+
74+ // reuse the matches allocation
75+ matches.clear();
76+ matches.extend(
77+ self.options
78+ .iter()
79+ .enumerate()
80+ .filter_map(|(index, option)| {
81+ // TODO: maybe using format_fn isn't the best idea here
82+ let text = (format_fn)(option);
83+ // TODO: using fuzzy_indices could give us the char idx for match highlighting
84+ matcher
85+ .fuzzy_match(text, pattern)
86+ .map(|score| (index, score))
87+ }),
88+ );
89+ matches.sort_unstable_by_key(|(_, score)| -score);
90+
91+ // reset cursor position
92+ self.cursor = 0;
93+ }
94+
95+ pub fn move_up(&mut self) {
96+ self.cursor = self.cursor.saturating_sub(1);
97+ }
98+
99+ pub fn move_down(&mut self) {
100+ // TODO: len - 1
101+ if self.cursor < self.options.len() {
102+ self.cursor += 1;
103+ }
104+ }
105+
106+ pub fn selection(&self) -> Option<&T> {
107+ self.matches
108+ .get(self.cursor)
109+ .map(|(index, _score)| &self.options[*index])
110+ }
111+}
112+
113+// process:
114+// - read all the files into a list, maxed out at a large value
115+// - on input change:
116+// - score all the names in relation to input
117+
118+impl<T> Component for Picker<T> {
119+ fn handle_event(&mut self, event: Event, cx: &mut Context) -> EventResult {
120+ let key_event = match event {
121+ Event::Key(event) => event,
122+ Event::Resize(..) => return EventResult::Consumed(None),
123+ _ => return EventResult::Ignored,
124+ };
125+
126+ let close_fn = EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor| {
127+ // remove the layer
128+ compositor.pop();
129+ })));
130+
131+ match key_event {
132+ // KeyEvent {
133+ // code: KeyCode::Char(c),
134+ // modifiers: KeyModifiers::NONE,
135+ // } => {
136+ // self.insert_char(c);
137+ // (self.callback_fn)(cx.editor, &self.line, PromptEvent::Update);
138+ // }
139+ KeyEvent {
140+ code: KeyCode::Up, ..
141+ }
142+ | KeyEvent {
143+ code: KeyCode::Char('k'),
144+ modifiers: KeyModifiers::CONTROL,
145+ } => self.move_up(),
146+ KeyEvent {
147+ code: KeyCode::Down,
148+ ..
149+ }
150+ | KeyEvent {
151+ code: KeyCode::Char('j'),
152+ modifiers: KeyModifiers::CONTROL,
153+ } => self.move_down(),
154+ KeyEvent {
155+ code: KeyCode::Esc, ..
156+ } => {
157+ return close_fn;
158+ }
159+ KeyEvent {
160+ code: KeyCode::Enter,
161+ ..
162+ } => {
163+ if let Some(option) = self.selection() {
164+ (self.callback_fn)(&mut cx.editor, option);
165+ }
166+ return close_fn;
167+ }
168+ _ => {
169+ match self.prompt.handle_event(event, cx) {
170+ EventResult::Consumed(_) => {
171+ // TODO: recalculate only if pattern changed
172+ self.score();
173+ }
174+ _ => (),
175+ }
176+ }
177+ }
178+
179+ EventResult::Consumed(None)
180+ }
181+
182+ fn render(&self, area: Rect, surface: &mut Surface, cx: &mut Context) {
183+ let padding_vertical = area.height * 20 / 100;
184+ let padding_horizontal = area.width * 20 / 100;
185+
186+ let area = Rect::new(
187+ area.x + padding_horizontal,
188+ area.y + padding_vertical,
189+ area.width - padding_horizontal * 2,
190+ area.height - padding_vertical * 2,
191+ );
192+
193+ // -- Render the frame:
194+
195+ // clear area
196+ for y in area.top()..area.bottom() {
197+ for x in area.left()..area.right() {
198+ surface.get_mut(x, y).reset()
199+ }
200+ }
201+
202+ use tui::widgets::Widget;
203+ // don't like this but the lifetime sucks
204+ let block = Block::default().borders(Borders::ALL);
205+
206+ // calculate the inner area inside the box
207+ let inner = block.inner(area);
208+
209+ block.render(area, surface);
210+ // TODO: abstract into a clear(area) fn
211+ // surface.set_style(inner, Style::default().bg(Color::Rgb(150, 50, 0)));
212+
213+ // -- Render the input bar:
214+
215+ let area = Rect::new(inner.x + 1, inner.y, inner.width - 1, 1);
216+ self.prompt.render(area, surface, cx);
217+
218+ // -- Separator
219+ use tui::widgets::BorderType;
220+ let style = Style::default().fg(Color::Rgb(90, 89, 119));
221+ let symbols = BorderType::line_symbols(BorderType::Plain);
222+ for x in inner.left()..inner.right() {
223+ surface
224+ .get_mut(x, inner.y + 1)
225+ .set_symbol(symbols.horizontal)
226+ .set_style(style);
227+ }
228+
229+ // -- Render the contents:
230+
231+ let style = Style::default().fg(Color::Rgb(164, 160, 232)); // lavender
232+ let selected = Style::default().fg(Color::Rgb(255, 255, 255));
233+
234+ let rows = inner.height - 2; // -1 for search bar
235+
236+ let files = self.matches.iter().map(|(index, _score)| {
237+ (index, self.options.get(*index).unwrap()) // get_unchecked
238+ });
239+
240+ for (i, (_index, option)) in files.take(rows as usize).enumerate() {
241+ if i == self.cursor {
242+ surface.set_string(inner.x + 1, inner.y + 2 + i as u16, ">", selected);
243+ }
244+
245+ surface.set_stringn(
246+ inner.x + 3,
247+ inner.y + 2 + i as u16,
248+ (self.format_fn)(option),
249+ inner.width as usize - 1,
250+ if i == self.cursor { selected } else { style },
251+ );
252+ }
253+ }
254+
255+ fn cursor_position(&self, area: Rect, ctx: &mut Context) -> Option<Position> {
256+ self.prompt.cursor_position(area, ctx)
257+ }
258+}
helix-term/src/ui/prompt.rs+43−18
@@ -10,24 +10,32 @@ pub struct Prompt {
1010 pub line: String,
1111 pub cursor: usize,
1212 pub completion: Vec<String>,
13− pub should_close: bool,
1413 pub completion_selection_index: Option<usize>,
1514 completion_fn: Box<dyn FnMut(&str) -> Vec<String>>,
16− callback_fn: Box<dyn FnMut(&mut Editor, &str)>,
15+ callback_fn: Box<dyn FnMut(&mut Editor, &str, PromptEvent)>,
16+}
17+
18+#[derive(PartialEq)]
19+pub enum PromptEvent {
20+ /// The prompt input has been updated.
21+ Update,
22+ /// Validate and finalize the change.
23+ Validate,
24+ /// Abort the change, reverting to the initial state.
25+ Abort,
1726}
1827
1928impl Prompt {
2029 pub fn new(
2130 prompt: String,
2231 mut completion_fn: impl FnMut(&str) -> Vec<String> + 'static,
23− callback_fn: impl FnMut(&mut Editor, &str) + 'static,
32+ callback_fn: impl FnMut(&mut Editor, &str, PromptEvent) + 'static,
2433 ) -> Prompt {
2534 Prompt {
2635 prompt,
2736 line: String::new(),
2837 cursor: 0,
2938 completion: completion_fn(""),
30− should_close: false,
3139 completion_selection_index: None,
3240 completion_fn: Box::new(completion_fn),
3341 callback_fn: Box::new(callback_fn),
@@ -42,9 +50,7 @@ impl Prompt {
4250 }
4351
4452 pub fn move_char_left(&mut self) {
45− if self.cursor > 0 {
46− self.cursor -= 1;
47− }
53+ self.cursor = self.cursor.saturating_sub(1)
4854 }
4955
5056 pub fn move_char_right(&mut self) {
@@ -141,9 +147,15 @@ impl Prompt {
141147 }
142148 }
143149 }
150+ let line = area.height - 1;
144151 // render buffer text
145− surface.set_string(1, area.height - 1, &self.prompt, text_color);
146− surface.set_string(2, area.height - 1, &self.line, text_color);
152+ surface.set_string(area.x, area.y + line, &self.prompt, text_color);
153+ surface.set_string(
154+ area.x + self.prompt.len() as u16,
155+ area.y + line,
156+ &self.line,
157+ text_color,
158+ );
147159 }
148160}
149161
@@ -151,21 +163,28 @@ impl Component for Prompt {
151163 fn handle_event(&mut self, event: Event, cx: &mut Context) -> EventResult {
152164 let event = match event {
153165 Event::Key(event) => event,
166+ Event::Resize(..) => return EventResult::Consumed(None),
154167 _ => return EventResult::Ignored,
155168 };
156169
170+ let close_fn = EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor| {
171+ // remove the layer
172+ compositor.pop();
173+ })));
174+
157175 match event {
158176 KeyEvent {
159177 code: KeyCode::Char(c),
160178 modifiers: KeyModifiers::NONE,
161− } => self.insert_char(c),
179+ } => {
180+ self.insert_char(c);
181+ (self.callback_fn)(cx.editor, &self.line, PromptEvent::Update);
182+ }
162183 KeyEvent {
163184 code: KeyCode::Esc, ..
164185 } => {
165− return EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor| {
166− // remove the layer
167− compositor.pop();
168− })));
186+ (self.callback_fn)(cx.editor, &self.line, PromptEvent::Abort);
187+ return close_fn;
169188 }
170189 KeyEvent {
171190 code: KeyCode::Right,
@@ -186,11 +205,17 @@ impl Component for Prompt {
186205 KeyEvent {
187206 code: KeyCode::Backspace,
188207 modifiers: KeyModifiers::NONE,
189− } => self.delete_char_backwards(),
208+ } => {
209+ self.delete_char_backwards();
210+ (self.callback_fn)(cx.editor, &self.line, PromptEvent::Update);
211+ }
190212 KeyEvent {
191213 code: KeyCode::Enter,
192214 ..
193− } => (self.callback_fn)(cx.editor, &self.line),
215+ } => {
216+ (self.callback_fn)(cx.editor, &self.line, PromptEvent::Validate);
217+ return close_fn;
218+ }
194219 KeyEvent {
195220 code: KeyCode::Tab, ..
196221 } => self.change_completion_selection(),
@@ -210,8 +235,8 @@ impl Component for Prompt {
210235
211236 fn cursor_position(&self, area: Rect, ctx: &mut Context) -> Option<Position> {
212237 Some(Position::new(
213− area.height as usize - 1,
214− area.x as usize + 2 + self.cursor,
238+ area.height as usize,
239+ area.x as usize + self.prompt.len() + self.cursor,
215240 ))
216241 }
217242}
helix-view/src/document.rs+8−1
@@ -1,6 +1,6 @@
11use anyhow::Error;
22use std::future::Future;
3−use std::path::PathBuf;
3+use std::path::{Path, PathBuf};
44
55use helix_core::{
66 syntax::LOADER, ChangeSet, Diagnostic, History, Position, Range, Rope, RopeSlice, Selection,
@@ -201,6 +201,13 @@ impl Document {
201201 &self.state.selection
202202 }
203203
204+ pub fn relative_path(&self) -> Option<&Path> {
205+ self.path.as_ref().map(|path| {
206+ path.strip_prefix(std::env::current_dir().unwrap())
207+ .unwrap_or(path)
208+ })
209+ }
210+
204211 // pub fn slice<R>(&self, range: R) -> RopeSlice where R: RangeBounds {
205212 // self.state.doc.slice
206213 // }