Filter the completion menu based on text entered.

pull/11/head
Blaž Hrastnik 4 years ago
parent 2a3910c1d9
commit a24c3fff54

@ -11,7 +11,7 @@ use once_cell::sync::Lazy;
use crate::{ use crate::{
compositor::{Callback, Component, Compositor}, compositor::{Callback, Component, Compositor},
ui::{self, Picker, Popup, Prompt, PromptEvent}, ui::{self, Completion, Picker, Popup, Prompt, PromptEvent},
}; };
use std::path::PathBuf; use std::path::PathBuf;
@ -55,12 +55,7 @@ impl<'a> Context<'a> {
/// Push a new component onto the compositor. /// Push a new component onto the compositor.
pub fn push_layer(&mut self, mut component: Box<dyn Component>) { pub fn push_layer(&mut self, mut component: Box<dyn Component>) {
self.callback = Some(Box::new( self.callback = Some(Box::new(
|compositor: &mut Compositor, editor: &mut Editor| { |compositor: &mut Compositor, editor: &mut Editor| compositor.push(component),
let size = compositor.size();
// trigger required_size on init
component.required_size((size.width, size.height));
compositor.push(component);
},
)); ));
} }
@ -1604,10 +1599,28 @@ pub fn completion(cx: &mut Context) {
// // downcast dyn Component to Completion component // // downcast dyn Component to Completion component
// // emit response to completion (completion.complete/handle(response)) // // emit response to completion (completion.complete/handle(response))
// }) // })
// async { //
// let (response, callback) = response.await?; // typing after prompt opens: usually start offset is tracked and everything between
// callback(response) // 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(); 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 res = smol::block_on(language_server.completion(doc.identifier(), pos)).unwrap();
let trigger_offset = doc.selection().cursor();
cx.callback( cx.callback(
res, res,
|editor: &mut Editor, move |editor: &mut Editor,
compositor: &mut Compositor, compositor: &mut Compositor,
response: Option<lsp::CompletionResponse>| { response: Option<lsp::CompletionResponse>| {
let items = match response { let items = match response {
Some(lsp::CompletionResponse::Array(items)) => items, Some(lsp::CompletionResponse::Array(items)) => items,
// TODO: do something with is_incomplete // 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 // TODO: if no completion, show some message or something
if !items.is_empty() { if !items.is_empty() {
// let snapshot = doc.state.clone(); let completion = Completion::new(items, trigger_offset);
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<dyn Component> = Box::new(popup);
// Server error: content modified // Server error: content modified
// TODO: this is shared with cx.push_layer compositor.push(Box::new(completion));
let size = compositor.size();
// trigger required_size on init
component.required_size((size.width, size.height));
compositor.push(component);
} }
}, },
); );
@ -1774,7 +1708,7 @@ pub fn hover(cx: &mut Context) {
// skip if contents empty // skip if contents empty
let contents = ui::Markdown::new(contents); 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)); cx.push_layer(Box::new(popup));
} }
} }

@ -92,7 +92,10 @@ impl Compositor {
.expect("Unable to resize terminal") .expect("Unable to resize terminal")
} }
pub fn push(&mut self, layer: Box<dyn Component>) { pub fn push(&mut self, mut layer: Box<dyn Component>) {
let size = self.size();
// trigger required_size on init
layer.required_size((size.width, size.height));
self.layers.push(layer); self.layers.push(layer);
} }

@ -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)
}
}

@ -9,6 +9,9 @@ use tui::{
use std::borrow::Cow; use std::borrow::Cow;
use fuzzy_matcher::skim::SkimMatcherV2 as Matcher;
use fuzzy_matcher::FuzzyMatcher;
use helix_core::Position; use helix_core::Position;
use helix_view::Editor; use helix_view::Editor;
@ -17,6 +20,10 @@ pub struct Menu<T> {
cursor: Option<usize>, cursor: Option<usize>,
matcher: Box<Matcher>,
/// (index, score)
matches: Vec<(usize, i64)>,
format_fn: Box<dyn Fn(&T) -> Cow<str>>, format_fn: Box<dyn Fn(&T) -> Cow<str>>,
callback_fn: Box<dyn Fn(&mut Editor, Option<&T>, MenuEvent)>, 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, format_fn: impl Fn(&T) -> Cow<str> + 'static,
callback_fn: impl Fn(&mut Editor, Option<&T>, MenuEvent) + 'static, callback_fn: impl Fn(&mut Editor, Option<&T>, MenuEvent) + 'static,
) -> Self { ) -> Self {
Self { let mut menu = Self {
options, options,
matcher: Box::new(Matcher::default()),
matches: Vec::new(),
cursor: None, cursor: None,
format_fn: Box::new(format_fn), format_fn: Box::new(format_fn),
callback_fn: Box::new(callback_fn), callback_fn: Box::new(callback_fn),
scroll: 0, scroll: 0,
size: (0, 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) { pub fn move_up(&mut self) {
@ -71,7 +117,11 @@ impl<T> Menu<T> {
} }
pub fn selection(&self) -> Option<&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 selected = Style::default().fg(Color::Rgb(255, 255, 255));
let scroll = self.scroll; 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; 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 let scroll_line = (win_height - scroll_height) * scroll
/ std::cmp::max(1, len.saturating_sub(win_height)); / 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() .iter()
.enumerate() .enumerate()
{ {

@ -1,3 +1,4 @@
mod completion;
mod editor; mod editor;
mod markdown; mod markdown;
mod menu; mod menu;
@ -6,6 +7,7 @@ mod popup;
mod prompt; mod prompt;
mod text; mod text;
pub use completion::Completion;
pub use editor::EditorView; pub use editor::EditorView;
pub use markdown::Markdown; pub use markdown::Markdown;
pub use menu::Menu; pub use menu::Menu;

@ -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 // 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>) // a width/height hint. maybe Popup(Box<Component>)
pub struct Popup { pub struct Popup<T: Component> {
contents: Box<dyn Component>, contents: T,
position: Option<Position>, position: Option<Position>,
size: (u16, u16), size: (u16, u16),
scroll: usize, scroll: usize,
} }
impl Popup { impl<T: Component> Popup<T> {
// TODO: it's like a slimmed down picker, share code? (picker = menu + prompt with different // TODO: it's like a slimmed down picker, share code? (picker = menu + prompt with different
// rendering) // rendering)
pub fn new(contents: Box<dyn Component>) -> Self { pub fn new(contents: T) -> Self {
Self { Self {
contents, contents,
position: None, position: None,
@ -45,9 +45,13 @@ impl Popup {
self.scroll = self.scroll.saturating_sub(offset); 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 { fn handle_event(&mut self, event: Event, cx: &mut Context) -> EventResult {
let key = match event { let key = match event {
Event::Key(event) => event, Event::Key(event) => event,

Loading…
Cancel
Save