From a24c3fff54f319eac42ae6947b910b54ee6fd899 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bla=C5=BE=20Hrastnik?= Date: Sat, 27 Mar 2021 12:06:40 +0900 Subject: [PATCH] Filter the completion menu based on text entered. --- helix-term/src/commands.rs | 130 +++++++--------------------- helix-term/src/compositor.rs | 5 +- helix-term/src/ui/completion.rs | 149 ++++++++++++++++++++++++++++++++ helix-term/src/ui/menu.rs | 70 +++++++++++++-- helix-term/src/ui/mod.rs | 2 + helix-term/src/ui/popup.rs | 14 +-- 6 files changed, 261 insertions(+), 109 deletions(-) create mode 100644 helix-term/src/ui/completion.rs diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index dbdebce0..bc1019d5 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -11,7 +11,7 @@ use once_cell::sync::Lazy; use crate::{ compositor::{Callback, Component, Compositor}, - ui::{self, Picker, Popup, Prompt, PromptEvent}, + ui::{self, Completion, Picker, Popup, Prompt, PromptEvent}, }; use std::path::PathBuf; @@ -55,12 +55,7 @@ impl<'a> Context<'a> { /// Push a new component onto the compositor. pub fn push_layer(&mut self, mut component: Box) { self.callback = Some(Box::new( - |compositor: &mut Compositor, editor: &mut Editor| { - let size = compositor.size(); - // trigger required_size on init - component.required_size((size.width, size.height)); - compositor.push(component); - }, + |compositor: &mut Compositor, editor: &mut Editor| compositor.push(component), )); } @@ -1604,10 +1599,28 @@ pub fn completion(cx: &mut Context) { // // downcast dyn Component to Completion component // // emit response to completion (completion.complete/handle(response)) // }) - // async { - // let (response, callback) = response.await?; - // callback(response) - // } + // + // typing after prompt opens: usually start offset is tracked and everything between + // start_offset..cursor is replaced. For our purposes we could keep the start state (doc, + // selection) and revert to them before applying. This needs to properly reset changes/history + // though... + // + // company-mode does this by matching the prefix of the completion and removing it. + + // ignore isIncomplete for now + // keep state while typing + // the behavior should be, filter the menu based on input + // if items returns empty at any point, remove the popup + // if backspace past initial offset point, remove the popup + // + // debounce requests! + // + // need an idle timeout thing. + // https://github.com/company-mode/company-mode/blob/master/company.el#L620-L622 + // + // "The idle delay in seconds until completion starts automatically. + // The prefix still has to satisfy `company-minimum-prefix-length' before that + // happens. The value of nil means no idle completion." let doc = cx.doc(); @@ -1623,11 +1636,13 @@ pub fn completion(cx: &mut Context) { let res = smol::block_on(language_server.completion(doc.identifier(), pos)).unwrap(); + let trigger_offset = doc.selection().cursor(); + cx.callback( res, - |editor: &mut Editor, - compositor: &mut Compositor, - response: Option| { + move |editor: &mut Editor, + compositor: &mut Compositor, + response: Option| { let items = match response { Some(lsp::CompletionResponse::Array(items)) => items, // TODO: do something with is_incomplete @@ -1640,92 +1655,11 @@ pub fn completion(cx: &mut Context) { // TODO: if no completion, show some message or something if !items.is_empty() { - // let snapshot = doc.state.clone(); - let mut menu = ui::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 - ); - } - } - - let transaction = - util::generate_transaction_from_edits(doc.text(), vec![edit]); - doc.apply(&transaction); - // TODO: doc.append_changes_to_history(); if not in insert mode? - } - _ => (), - }; - }, - ); - - let popup = Popup::new(Box::new(menu)); - let mut component: Box = Box::new(popup); + let completion = Completion::new(items, trigger_offset); // Server error: content modified - // TODO: this is shared with cx.push_layer - let size = compositor.size(); - // trigger required_size on init - component.required_size((size.width, size.height)); - compositor.push(component); + compositor.push(Box::new(completion)); } }, ); @@ -1774,7 +1708,7 @@ pub fn hover(cx: &mut Context) { // skip if contents empty let contents = ui::Markdown::new(contents); - let mut popup = Popup::new(Box::new(contents)); + let mut popup = Popup::new(contents); cx.push_layer(Box::new(popup)); } } diff --git a/helix-term/src/compositor.rs b/helix-term/src/compositor.rs index bd27f138..4869032b 100644 --- a/helix-term/src/compositor.rs +++ b/helix-term/src/compositor.rs @@ -92,7 +92,10 @@ impl Compositor { .expect("Unable to resize terminal") } - pub fn push(&mut self, layer: Box) { + pub fn push(&mut self, mut layer: Box) { + let size = self.size(); + // trigger required_size on init + layer.required_size((size.width, size.height)); self.layers.push(layer); } 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>, // TODO: Popup need to be able to access contents. + trigger_offset: usize, +} + +impl Completion { + pub fn new(items: Vec, trigger_offset: usize) -> Self { + // let items: Vec = 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 { cursor: Option, + matcher: Box, + /// (index, score) + matches: Vec<(usize, i64)>, + format_fn: Box Cow>, callback_fn: Box, MenuEvent)>, @@ -32,14 +39,53 @@ impl Menu { format_fn: impl Fn(&T) -> Cow + '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 Menu { } 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 Component for Menu { 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 Component for Menu { 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) -pub struct Popup { - contents: Box, +pub struct Popup { + contents: T, position: Option, size: (u16, u16), scroll: usize, } -impl Popup { +impl Popup { // TODO: it's like a slimmed down picker, share code? (picker = menu + prompt with different // rendering) - pub fn new(contents: Box) -> 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 Component for Popup { fn handle_event(&mut self, event: Event, cx: &mut Context) -> EventResult { let key = match event { Event::Key(event) => event,