diff options
author | Blaž Hrastnik | 2021-03-27 03:06:40 +0000 |
---|---|---|
committer | Blaž Hrastnik | 2021-03-27 03:08:44 +0000 |
commit | a24c3fff54f319eac42ae6947b910b54ee6fd899 (patch) | |
tree | 30f8b5394fc6205a6e7eae276a3a8caad47b59d3 /helix-term/src/ui | |
parent | 2a3910c1d9f2b05fe5bc0610e6a83e6dabe13b71 (diff) |
Filter the completion menu based on text entered.
Diffstat (limited to 'helix-term/src/ui')
-rw-r--r-- | helix-term/src/ui/completion.rs | 149 | ||||
-rw-r--r-- | helix-term/src/ui/menu.rs | 70 | ||||
-rw-r--r-- | helix-term/src/ui/mod.rs | 2 | ||||
-rw-r--r-- | helix-term/src/ui/popup.rs | 14 |
4 files changed, 225 insertions, 10 deletions
diff --git a/helix-term/src/ui/completion.rs b/helix-term/src/ui/completion.rs new file mode 100644 index 00000000..322e5b7b --- /dev/null +++ b/helix-term/src/ui/completion.rs @@ -0,0 +1,149 @@ +use crate::compositor::{Component, Compositor, Context, EventResult}; +use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers}; +use tui::{ + buffer::Buffer as Surface, + layout::Rect, + style::{Color, Style}, + widgets::{Block, Borders}, +}; + +use std::borrow::Cow; + +use helix_core::{Position, Transaction}; +use helix_view::Editor; + +use crate::ui::{Menu, Popup, PromptEvent}; + +use helix_lsp::lsp; +use lsp::CompletionItem; + +/// Wraps a Menu. +pub struct Completion { + popup: Popup<Menu<CompletionItem>>, // TODO: Popup<Menu> need to be able to access contents. + trigger_offset: usize, +} + +impl Completion { + pub fn new(items: Vec<CompletionItem>, trigger_offset: usize) -> Self { + // let items: Vec<CompletionItem> = Vec::new(); + let mut menu = Menu::new( + items, + |item| { + // format_fn + item.label.as_str().into() + + // TODO: use item.filter_text for filtering + }, + move |editor: &mut Editor, item, event| { + match event { + PromptEvent::Abort => { + // revert state + // let id = editor.view().doc; + // let doc = &mut editor.documents[id]; + // doc.state = snapshot.clone(); + } + PromptEvent::Validate => { + let id = editor.view().doc; + let doc = &mut editor.documents[id]; + + // revert state to what it was before the last update + // doc.state = snapshot.clone(); + + // extract as fn(doc, item): + + // TODO: need to apply without composing state... + // TODO: need to update lsp on accept/cancel by diffing the snapshot with + // the final state? + // -> on update simply update the snapshot, then on accept redo the call, + // finally updating doc.changes + notifying lsp. + // + // or we could simply use doc.undo + apply when changing between options + + // always present here + let item = item.unwrap(); + + use helix_lsp::{lsp, util}; + // determine what to insert: text_edit | insert_text | label + let edit = if let Some(edit) = &item.text_edit { + match edit { + lsp::CompletionTextEdit::Edit(edit) => edit.clone(), + lsp::CompletionTextEdit::InsertAndReplace(item) => { + unimplemented!("completion: insert_and_replace {:?}", item) + } + } + } else { + item.insert_text.as_ref().unwrap_or(&item.label); + unimplemented!(); + // lsp::TextEdit::new(); TODO: calculate a TextEdit from insert_text + // and we insert at position. + }; + + // TODO: merge edit with additional_text_edits + if let Some(additional_edits) = &item.additional_text_edits { + if !additional_edits.is_empty() { + unimplemented!( + "completion: additional_text_edits: {:?}", + additional_edits + ); + } + } + + // if more text was entered, remove it + let cursor = doc.selection().cursor(); + if trigger_offset < cursor { + let remove = Transaction::change( + doc.text(), + vec![(trigger_offset, cursor, None)].into_iter(), + ); + doc.apply(&remove); + } + + let transaction = + util::generate_transaction_from_edits(doc.text(), vec![edit]); + doc.apply(&transaction); + } + _ => (), + }; + }, + ); + let popup = Popup::new(menu); + Self { + popup, + trigger_offset, + } + } +} + +impl Component for Completion { + fn handle_event(&mut self, event: Event, cx: &mut Context) -> EventResult { + // input + if let Event::Key(KeyEvent { + code: KeyCode::Char(ch), + .. + }) = event + { + // recompute menu based on matches + let menu = self.popup.contents(); + let id = cx.editor.view().doc; + let doc = cx.editor.document(id).unwrap(); + + let cursor = doc.selection().cursor(); + if self.trigger_offset <= cursor { + let fragment = doc.text().slice(self.trigger_offset..cursor); + let text = Cow::from(fragment); + // TODO: logic is same as ui/picker + menu.score(&text); + } + } + + self.popup.handle_event(event, cx) + } + + fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> { + self.popup.required_size(viewport) + } + + fn render(&self, area: Rect, surface: &mut Surface, cx: &mut Context) { + self.popup.render(area, surface, cx) + } +} diff --git a/helix-term/src/ui/menu.rs b/helix-term/src/ui/menu.rs index 049d6170..5c3ff654 100644 --- a/helix-term/src/ui/menu.rs +++ b/helix-term/src/ui/menu.rs @@ -9,6 +9,9 @@ use tui::{ use std::borrow::Cow; +use fuzzy_matcher::skim::SkimMatcherV2 as Matcher; +use fuzzy_matcher::FuzzyMatcher; + use helix_core::Position; use helix_view::Editor; @@ -17,6 +20,10 @@ pub struct Menu<T> { cursor: Option<usize>, + matcher: Box<Matcher>, + /// (index, score) + matches: Vec<(usize, i64)>, + format_fn: Box<dyn Fn(&T) -> Cow<str>>, callback_fn: Box<dyn Fn(&mut Editor, Option<&T>, MenuEvent)>, @@ -32,14 +39,53 @@ impl<T> Menu<T> { format_fn: impl Fn(&T) -> Cow<str> + 'static, callback_fn: impl Fn(&mut Editor, Option<&T>, MenuEvent) + 'static, ) -> Self { - Self { + let mut menu = Self { options, + matcher: Box::new(Matcher::default()), + matches: Vec::new(), cursor: None, format_fn: Box::new(format_fn), callback_fn: Box::new(callback_fn), scroll: 0, size: (0, 0), - } + }; + + // TODO: scoring on empty input should just use a fastpath + menu.score(""); + + menu + } + + pub fn score(&mut self, pattern: &str) { + // need to borrow via pattern match otherwise it complains about simultaneous borrow + let Self { + ref mut options, + ref mut matcher, + ref mut matches, + ref format_fn, + .. + } = *self; + + // reuse the matches allocation + matches.clear(); + matches.extend( + self.options + .iter() + .enumerate() + .filter_map(|(index, option)| { + // TODO: maybe using format_fn isn't the best idea here + let text = (format_fn)(option); + // TODO: using fuzzy_indices could give us the char idx for match highlighting + matcher + .fuzzy_match(&text, pattern) + .map(|score| (index, score)) + }), + ); + matches.sort_unstable_by_key(|(_, score)| -score); + + // reset cursor position + self.cursor = None; + self.scroll = 0; } pub fn move_up(&mut self) { @@ -71,7 +117,11 @@ impl<T> Menu<T> { } pub fn selection(&self) -> Option<&T> { - self.cursor.and_then(|cursor| self.options.get(cursor)) + self.cursor.and_then(|cursor| { + self.matches + .get(cursor) + .map(|(index, _score)| &self.options[*index]) + }) } } @@ -186,7 +236,17 @@ impl<T> Component for Menu<T> { let selected = Style::default().fg(Color::Rgb(255, 255, 255)); let scroll = self.scroll; - let len = self.options.len(); + + let options: Vec<_> = self + .matches + .iter() + .map(|(index, _score)| { + // (index, self.options.get(*index).unwrap()) // get_unchecked + &self.options[*index] // get_unchecked + }) + .collect(); + + let len = options.len(); let win_height = area.height as usize; @@ -199,7 +259,7 @@ impl<T> Component for Menu<T> { let scroll_line = (win_height - scroll_height) * scroll / std::cmp::max(1, len.saturating_sub(win_height)); - for (i, option) in self.options[scroll..(scroll + win_height).min(len)] + for (i, option) in options[scroll..(scroll + win_height).min(len)] .iter() .enumerate() { diff --git a/helix-term/src/ui/mod.rs b/helix-term/src/ui/mod.rs index f7f77d0c..2d282867 100644 --- a/helix-term/src/ui/mod.rs +++ b/helix-term/src/ui/mod.rs @@ -1,3 +1,4 @@ +mod completion; mod editor; mod markdown; mod menu; @@ -6,6 +7,7 @@ mod popup; mod prompt; mod text; +pub use completion::Completion; pub use editor::EditorView; pub use markdown::Markdown; pub use menu::Menu; diff --git a/helix-term/src/ui/popup.rs b/helix-term/src/ui/popup.rs index 98ccae61..f1666451 100644 --- a/helix-term/src/ui/popup.rs +++ b/helix-term/src/ui/popup.rs @@ -15,17 +15,17 @@ use helix_view::Editor; // TODO: share logic with Menu, it's essentially Popup(render_fn), but render fn needs to return // a width/height hint. maybe Popup(Box<Component>) -pub struct Popup { - contents: Box<dyn Component>, +pub struct Popup<T: Component> { + contents: T, position: Option<Position>, size: (u16, u16), scroll: usize, } -impl Popup { +impl<T: Component> Popup<T> { // TODO: it's like a slimmed down picker, share code? (picker = menu + prompt with different // rendering) - pub fn new(contents: Box<dyn Component>) -> Self { + pub fn new(contents: T) -> Self { Self { contents, position: None, @@ -45,9 +45,13 @@ impl Popup { self.scroll = self.scroll.saturating_sub(offset); } } + + pub fn contents(&mut self) -> &mut T { + &mut self.contents + } } -impl Component for Popup { +impl<T: Component> Component for Popup<T> { fn handle_event(&mut self, event: Event, cx: &mut Context) -> EventResult { let key = match event { Event::Key(event) => event, |