on master help sign in
Merge pull request #821 from helix-editor/idle-timer

Idle timer / Autocompletion

commitf8f63c55081ee966c7cb2b84139c25c6301b5fff authorBlaž Hrastnik <blaz@mxxn.io> dateSun 10 Oct 2021, 22:11 (5 years ago) parenta7f49fa76b1bbc
7 files changed+140−16
book/src/configuration.md+1 helix-term/src/application.rs+37 helix-term/src/commands.rs+21−7 helix-term/src/ui/completion.rs+20−6 helix-term/src/ui/editor.rs+14−2 helix-view/src/editor.rs+31−1 helix-view/src/macros.rs+16
book/src/configuration.md+1
@@ -19,6 +19,7 @@ To override global configuration parameters, create a `config.toml` file located
1919| `line-number` | Line number display (`absolute`, `relative`) | `absolute` |
2020| `smart-case` | Enable smart case regex searching (case insensitive unless pattern contains upper case characters) | `true` |
2121| `auto-pairs` | Enable automatic insertion of pairs to parenthese, brackets, etc. | `true` |
22+| `idle-timeout` | Time in milliseconds since last keypress before idle timers trigger. Used for autocompletion, set to 0 for instant. | `400` |
2223
2324## LSP
2425
helix-term/src/application.rs+37
@@ -199,6 +199,11 @@ impl Application {
199199 self.jobs.handle_callback(&mut self.editor, &mut self.compositor, callback);
200200 self.render();
201201 }
202+ _ = &mut self.editor.idle_timer => {
203+ // idle timeout
204+ self.editor.clear_idle_timer();
205+ self.handle_idle_timeout();
206+ }
202207 }
203208 }
204209 }
@@ -228,6 +233,38 @@ impl Application {
228233 }
229234 }
230235
236+ pub fn handle_idle_timeout(&mut self) {
237+ use crate::commands::{completion, Context};
238+ use helix_view::document::Mode;
239+
240+ if doc_mut!(self.editor).mode != Mode::Insert {
241+ return;
242+ }
243+ let editor_view = self
244+ .compositor
245+ .find(std::any::type_name::<ui::EditorView>())
246+ .expect("expected at least one EditorView");
247+ let editor_view = editor_view
248+ .as_any_mut()
249+ .downcast_mut::<ui::EditorView>()
250+ .unwrap();
251+
252+ if editor_view.completion.is_some() {
253+ return;
254+ }
255+
256+ let mut cx = Context {
257+ register: None,
258+ editor: &mut self.editor,
259+ jobs: &mut self.jobs,
260+ count: None,
261+ callback: None,
262+ on_next_key_callback: None,
263+ };
264+ completion(&mut cx);
265+ self.render();
266+ }
267+
231268 pub fn handle_terminal_events(&mut self, event: Option<Result<Event, crossterm::ErrorKind>>) {
232269 let mut cx = crate::compositor::Context {
233270 editor: &mut self.editor,
helix-term/src/commands.rs+21−7
@@ -4051,7 +4051,7 @@ fn remove_primary_selection(cx: &mut Context) {
40514051 doc.set_selection(view.id, selection);
40524052}
40534053
4054−fn completion(cx: &mut Context) {
4054+pub fn completion(cx: &mut Context) {
40554055 // trigger on trigger char, or if user calls it
40564056 // (or on word char typing??)
40574057 // after it's triggered, if response marked is_incomplete, update on every subsequent keypress
@@ -4096,10 +4096,8 @@ fn completion(cx: &mut Context) {
40964096 };
40974097
40984098 let offset_encoding = language_server.offset_encoding();
4099− let cursor = doc
4100− .selection(view.id)
4101− .primary()
4102− .cursor(doc.text().slice(..));
4099+ let text = doc.text().slice(..);
4100+ let cursor = doc.selection(view.id).primary().cursor(text);
41034101
41044102 let pos = pos_to_lsp_pos(doc.text(), cursor, offset_encoding);
41054103
@@ -4107,6 +4105,15 @@ fn completion(cx: &mut Context) {
41074105
41084106 let trigger_offset = cursor;
41094107
4108+ // TODO: trigger_offset should be the cursor offset but we also need a starting offset from where we want to apply
4109+ // completion filtering. For example logger.te| should filter the initial suggestion list with "te".
4110+
4111+ use helix_core::chars;
4112+ let mut iter = text.chars_at(cursor);
4113+ iter.reverse();
4114+ let offset = iter.take_while(|ch| chars::char_is_word(*ch)).count();
4115+ let start_offset = cursor.saturating_sub(offset);
4116+
41104117 cx.callback(
41114118 future,
41124119 move |editor: &mut Editor,
@@ -4129,7 +4136,7 @@ fn completion(cx: &mut Context) {
41294136 };
41304137
41314138 if items.is_empty() {
4132− editor.set_error("No completion available".to_string());
4139+ // editor.set_error("No completion available".to_string());
41334140 return;
41344141 }
41354142 let size = compositor.size();
@@ -4137,7 +4144,14 @@ fn completion(cx: &mut Context) {
41374144 .find(std::any::type_name::<ui::EditorView>())
41384145 .unwrap();
41394146 if let Some(ui) = ui.as_any_mut().downcast_mut::<ui::EditorView>() {
4140− ui.set_completion(items, offset_encoding, trigger_offset, size);
4147+ ui.set_completion(
4148+ editor,
4149+ items,
4150+ offset_encoding,
4151+ start_offset,
4152+ trigger_offset,
4153+ size,
4154+ );
41414155 };
41424156 },
41434157 );
helix-term/src/ui/completion.rs+20−6
@@ -69,14 +69,18 @@ impl menu::Item for CompletionItem {
6969/// Wraps a Menu.
7070pub struct Completion {
7171 popup: Popup<Menu<CompletionItem>>,
72+ start_offset: usize,
73+ #[allow(dead_code)]
7274 trigger_offset: usize,
7375 // TODO: maintain a completioncontext with trigger kind & trigger char
7476}
7577
7678impl Completion {
7779 pub fn new(
80+ editor: &Editor,
7881 items: Vec<CompletionItem>,
7982 offset_encoding: helix_lsp::OffsetEncoding,
83+ start_offset: usize,
8084 trigger_offset: usize,
8185 ) -> Self {
8286 // let items: Vec<CompletionItem> = Vec::new();
@@ -175,16 +179,22 @@ impl Completion {
175179 };
176180 });
177181 let popup = Popup::new(menu);
178− Self {
182+ let mut completion = Self {
179183 popup,
184+ start_offset,
180185 trigger_offset,
181− }
186+ };
187+
188+ // need to recompute immediately in case start_offset != trigger_offset
189+ completion.recompute_filter(editor);
190+
191+ completion
182192 }
183193
184− pub fn update(&mut self, cx: &mut commands::Context) {
194+ pub fn recompute_filter(&mut self, editor: &Editor) {
185195 // recompute menu based on matches
186196 let menu = self.popup.contents_mut();
187− let (view, doc) = current!(cx.editor);
197+ let (view, doc) = current_ref!(editor);
188198
189199 // cx.hooks()
190200 // cx.add_hook(enum type, ||)
@@ -200,14 +210,18 @@ impl Completion {
200210 .selection(view.id)
201211 .primary()
202212 .cursor(doc.text().slice(..));
203− if self.trigger_offset <= cursor {
204− let fragment = doc.text().slice(self.trigger_offset..cursor);
213+ if self.start_offset <= cursor {
214+ let fragment = doc.text().slice(self.start_offset..cursor);
205215 let text = Cow::from(fragment);
206216 // TODO: logic is same as ui/picker
207217 menu.score(&text);
208218 }
209219 }
210220
221+ pub fn update(&mut self, cx: &mut commands::Context) {
222+ self.recompute_filter(cx.editor)
223+ }
224+
211225 pub fn is_empty(&self) -> bool {
212226 self.popup.contents().is_empty()
213227 }
helix-term/src/ui/editor.rs+14−2
@@ -33,7 +33,7 @@ pub struct EditorView {
3333 keymaps: Keymaps,
3434 on_next_key: Option<Box<dyn FnOnce(&mut commands::Context, KeyEvent)>>,
3535 last_insert: (commands::Command, Vec<KeyEvent>),
36− completion: Option<Completion>,
36+ pub(crate) completion: Option<Completion>,
3737 spinners: ProgressSpinners,
3838 autoinfo: Option<Info>,
3939}
@@ -721,12 +721,21 @@ impl EditorView {
721721
722722 pub fn set_completion(
723723 &mut self,
724+ editor: &Editor,
724725 items: Vec<helix_lsp::lsp::CompletionItem>,
725726 offset_encoding: helix_lsp::OffsetEncoding,
727+ start_offset: usize,
726728 trigger_offset: usize,
727729 size: Rect,
728730 ) {
729− let mut completion = Completion::new(items, offset_encoding, trigger_offset);
731+ let mut completion =
732+ Completion::new(editor, items, offset_encoding, start_offset, trigger_offset);
733+
734+ if completion.is_empty() {
735+ // skip if we got no completion results
736+ return;
737+ }
738+
730739 // TODO : propagate required size on resize to completion too
731740 completion.required_size((size.width, size.height));
732741 self.completion = Some(completion);
@@ -901,6 +910,7 @@ impl Component for EditorView {
901910 EventResult::Consumed(None)
902911 }
903912 Event::Key(key) => {
913+ cxt.editor.reset_idle_timer();
904914 let mut key = KeyEvent::from(key);
905915 canonicalize_key(&mut key);
906916 // clear status
@@ -935,6 +945,7 @@ impl Component for EditorView {
935945 if callback.is_some() {
936946 // assume close_fn
937947 self.completion = None;
948+ cxt.editor.clear_idle_timer(); // don't retrigger
938949 }
939950 }
940951 }
@@ -948,6 +959,7 @@ impl Component for EditorView {
948959 completion.update(&mut cxt);
949960 if completion.is_empty() {
950961 self.completion = None;
962+ cxt.editor.clear_idle_timer(); // don't retrigger
951963 }
952964 }
953965 }
helix-view/src/editor.rs+31−1
@@ -9,10 +9,12 @@ use crate::{
99use futures_util::future;
1010use std::{
1111 path::{Path, PathBuf},
12+ pin::Pin,
1213 sync::Arc,
13− time::Duration,
1414};
1515
16+use tokio::time::{sleep, Duration, Instant, Sleep};
17+
1618use slotmap::SlotMap;
1719
1820use anyhow::Error;
@@ -24,6 +26,14 @@ use helix_core::Position;
2426
2527use serde::Deserialize;
2628
29+fn deserialize_duration_millis<'de, D>(deserializer: D) -> Result<Duration, D::Error>
30+where
31+ D: serde::Deserializer<'de>,
32+{
33+ let millis = u64::deserialize(deserializer)?;
34+ Ok(Duration::from_millis(millis))
35+}
36+
2737#[derive(Debug, Clone, PartialEq, Deserialize)]
2838#[serde(rename_all = "kebab-case", default)]
2939pub struct Config {
@@ -43,6 +53,9 @@ pub struct Config {
4353 pub smart_case: bool,
4454 /// Automatic insertion of pairs to parentheses, brackets, etc. Defaults to true.
4555 pub auto_pairs: bool,
56+ /// Time in milliseconds since last keypress before idle timers trigger. Used for autocompletion, set to 0 for instant. Defaults to 400ms.
57+ #[serde(skip_serializing, deserialize_with = "deserialize_duration_millis")]
58+ pub idle_timeout: Duration,
4659}
4760
4861#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
@@ -70,6 +83,7 @@ impl Default for Config {
7083 middle_click_paste: true,
7184 smart_case: true,
7285 auto_pairs: true,
86+ idle_timeout: Duration::from_millis(400),
7387 }
7488 }
7589}
@@ -91,6 +105,8 @@ pub struct Editor {
91105 pub status_msg: Option<(String, Severity)>,
92106
93107 pub config: Config,
108+
109+ pub idle_timer: Pin<Box<Sleep>>,
94110}
95111
96112#[derive(Debug, Copy, Clone)]
@@ -125,10 +141,24 @@ impl Editor {
125141 registers: Registers::default(),
126142 clipboard_provider: get_clipboard_provider(),
127143 status_msg: None,
144+ idle_timer: Box::pin(sleep(Duration::from_millis(500))),
128145 config,
129146 }
130147 }
131148
149+ pub fn clear_idle_timer(&mut self) {
150+ // equivalent to internal Instant::far_future() (30 years)
151+ self.idle_timer
152+ .as_mut()
153+ .reset(Instant::now() + Duration::from_secs(86400 * 365 * 30));
154+ }
155+
156+ pub fn reset_idle_timer(&mut self) {
157+ self.idle_timer
158+ .as_mut()
159+ .reset(Instant::now() + Duration::from_millis(500));
160+ }
161+
132162 pub fn clear_status(&mut self) {
133163 self.status_msg = None;
134164 }
helix-view/src/macros.rs+16
@@ -44,3 +44,19 @@ macro_rules! view {
4444 $( $editor ).+ .tree.get($( $editor ).+ .tree.focus)
4545 }};
4646}
47+
48+#[macro_export]
49+macro_rules! doc {
50+ ( $( $editor:ident ).+ ) => {{
51+ $crate::current_ref!( $( $editor ).+ ).1
52+ }};
53+}
54+
55+#[macro_export]
56+macro_rules! current_ref {
57+ ( $( $editor:ident ).+ ) => {{
58+ let view = $( $editor ).+ .tree.get($( $editor ).+ .tree.focus);
59+ let doc = &$( $editor ).+ .documents[view.doc];
60+ (view, doc)
61+ }};
62+}