on 2158366 help sign in
helix/helix-term/src/ui/prompt.rs
564 lines 19 kB history raw
1use crate::compositor::{Component, Compositor, Context, EventResult};
2use crate::ui;
3use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
4use std::{borrow::Cow, ops::RangeFrom};
5use tui::buffer::Buffer as Surface;
7use helix_core::{
8 unicode::segmentation::GraphemeCursor, unicode::width::UnicodeWidthStr, Position,
9};
10use helix_view::{
11 graphics::{CursorKind, Margin, Rect},
12 Editor,
13};
15pub type Completion = (RangeFrom<usize>, Cow<'static, str>);
17pub struct Prompt {
18 prompt: String,
19 pub line: String,
20 cursor: usize,
21 completion: Vec<Completion>,
22 selection: Option<usize>,
23 history_register: Option<char>,
24 history_pos: Option<usize>,
25 completion_fn: Box<dyn FnMut(&str) -> Vec<Completion>>,
26 callback_fn: Box<dyn FnMut(&mut Context, &str, PromptEvent)>,
27 pub doc_fn: Box<dyn Fn(&str) -> Option<&'static str>>,
30#[derive(Clone, Copy, PartialEq)]
31pub enum PromptEvent {
32 /// The prompt input has been updated.
33 Update,
34 /// Validate and finalize the change.
35 Validate,
36 /// Abort the change, reverting to the initial state.
37 Abort,
40pub enum CompletionDirection {
41 Forward,
42 Backward,
45#[derive(Debug, Clone, Copy)]
46pub enum Movement {
47 BackwardChar(usize),
48 BackwardWord(usize),
49 ForwardChar(usize),
50 ForwardWord(usize),
51 StartOfLine,
52 EndOfLine,
53 None,
56impl Prompt {
57 pub fn new(
58 prompt: String,
59 history_register: Option<char>,
60 mut completion_fn: impl FnMut(&str) -> Vec<Completion> + 'static,
61 callback_fn: impl FnMut(&mut Context, &str, PromptEvent) + 'static,
62 ) -> Self {
63 Self {
64 prompt,
65 line: String::new(),
66 cursor: 0,
67 completion: completion_fn(""),
68 selection: None,
69 history_register,
70 history_pos: None,
71 completion_fn: Box::new(completion_fn),
72 callback_fn: Box::new(callback_fn),
73 doc_fn: Box::new(|_| None),
74 }
75 }
77 /// Compute the cursor position after applying movement
78 /// Taken from: https://github.com/wez/wezterm/blob/e0b62d07ca9bf8ce69a61e30a3c20e7abc48ce7e/termwiz/src/lineedit/mod.rs#L516-L611
79 fn eval_movement(&self, movement: Movement) -> usize {
80 match movement {
81 Movement::BackwardChar(rep) => {
82 let mut position = self.cursor;
83 for _ in 0..rep {
84 let mut cursor = GraphemeCursor::new(position, self.line.len(), false);
85 if let Ok(Some(pos)) = cursor.prev_boundary(&self.line, 0) {
86 position = pos;
87 } else {
88 break;
89 }
90 }
91 position
92 }
93 Movement::BackwardWord(rep) => {
94 let char_indices: Vec<(usize, char)> = self.line.char_indices().collect();
95 if char_indices.is_empty() {
96 return self.cursor;
97 }
98 let mut char_position = char_indices
99 .iter()
100 .position(|(idx, _)| *idx == self.cursor)
101 .unwrap_or(char_indices.len() - 1);
103 for _ in 0..rep {
104 if char_position == 0 {
105 break;
106 }
108 let mut found = None;
109 for prev in (0..char_position - 1).rev() {
110 if char_indices[prev].1.is_whitespace() {
111 found = Some(prev + 1);
112 break;
113 }
114 }
116 char_position = found.unwrap_or(0);
117 }
118 char_indices[char_position].0
119 }
120 Movement::ForwardWord(rep) => {
121 let char_indices: Vec<(usize, char)> = self.line.char_indices().collect();
122 if char_indices.is_empty() {
123 return self.cursor;
124 }
125 let mut char_position = char_indices
126 .iter()
127 .position(|(idx, _)| *idx == self.cursor)
128 .unwrap_or_else(|| char_indices.len());
130 for _ in 0..rep {
131 // Skip any non-whitespace characters
132 while char_position < char_indices.len()
133 && !char_indices[char_position].1.is_whitespace()
134 {
135 char_position += 1;
136 }
138 // Skip any whitespace characters
139 while char_position < char_indices.len()
140 && char_indices[char_position].1.is_whitespace()
141 {
142 char_position += 1;
143 }
145 // We are now on the start of the next word
146 }
147 char_indices
148 .get(char_position)
149 .map(|(i, _)| *i)
150 .unwrap_or_else(|| self.line.len())
151 }
152 Movement::ForwardChar(rep) => {
153 let mut position = self.cursor;
154 for _ in 0..rep {
155 let mut cursor = GraphemeCursor::new(position, self.line.len(), false);
156 if let Ok(Some(pos)) = cursor.next_boundary(&self.line, 0) {
157 position = pos;
158 } else {
159 break;
160 }
161 }
162 position
163 }
164 Movement::StartOfLine => 0,
165 Movement::EndOfLine => {
166 let mut cursor =
167 GraphemeCursor::new(self.line.len().saturating_sub(1), self.line.len(), false);
168 if let Ok(Some(pos)) = cursor.next_boundary(&self.line, 0) {
169 pos
170 } else {
171 self.cursor
172 }
173 }
174 Movement::None => self.cursor,
175 }
176 }
178 pub fn insert_char(&mut self, c: char) {
179 self.line.insert(self.cursor, c);
180 let mut cursor = GraphemeCursor::new(self.cursor, self.line.len(), false);
181 if let Ok(Some(pos)) = cursor.next_boundary(&self.line, 0) {
182 self.cursor = pos;
183 }
184 self.completion = (self.completion_fn)(&self.line);
185 self.exit_selection();
186 }
188 pub fn move_cursor(&mut self, movement: Movement) {
189 let pos = self.eval_movement(movement);
190 self.cursor = pos
191 }
193 pub fn move_start(&mut self) {
194 self.cursor = 0;
195 }
197 pub fn move_end(&mut self) {
198 self.cursor = self.line.len();
199 }
201 pub fn delete_char_backwards(&mut self) {
202 let pos = self.eval_movement(Movement::BackwardChar(1));
203 self.line.replace_range(pos..self.cursor, "");
204 self.cursor = pos;
206 self.exit_selection();
207 self.completion = (self.completion_fn)(&self.line);
208 }
210 pub fn delete_word_backwards(&mut self) {
211 let pos = self.eval_movement(Movement::BackwardWord(1));
212 self.line.replace_range(pos..self.cursor, "");
213 self.cursor = pos;
215 self.exit_selection();
216 self.completion = (self.completion_fn)(&self.line);
217 }
219 pub fn kill_to_end_of_line(&mut self) {
220 let pos = self.eval_movement(Movement::EndOfLine);
221 self.line.replace_range(self.cursor..pos, "");
223 self.exit_selection();
224 self.completion = (self.completion_fn)(&self.line);
225 }
227 pub fn clear(&mut self) {
228 self.line.clear();
229 self.cursor = 0;
230 self.completion = (self.completion_fn)(&self.line);
231 self.exit_selection();
232 }
234 pub fn change_history(&mut self, register: &[String], direction: CompletionDirection) {
235 if register.is_empty() {
236 return;
237 }
239 let end = register.len().saturating_sub(1);
241 let index = match direction {
242 CompletionDirection::Forward => self.history_pos.map_or(0, |i| i + 1),
243 CompletionDirection::Backward => {
244 self.history_pos.unwrap_or(register.len()).saturating_sub(1)
245 }
246 }
247 .min(end);
249 self.line = register[index].clone();
251 self.history_pos = Some(index);
253 self.move_end();
254 }
256 pub fn change_completion_selection(&mut self, direction: CompletionDirection) {
257 if self.completion.is_empty() {
258 return;
259 }
261 let index = match direction {
262 CompletionDirection::Forward => self.selection.map_or(0, |i| i + 1),
263 CompletionDirection::Backward => {
264 self.selection.unwrap_or(0) + self.completion.len() - 1
265 }
266 } % self.completion.len();
268 self.selection = Some(index);
270 let (range, item) = &self.completion[index];
272 self.line.replace_range(range.clone(), item);
274 self.move_end();
275 }
277 pub fn exit_selection(&mut self) {
278 self.selection = None;
279 }
282const BASE_WIDTH: u16 = 30;
284impl Prompt {
285 pub fn render_prompt(&self, area: Rect, surface: &mut Surface, cx: &mut Context) {
286 let theme = &cx.editor.theme;
287 let prompt_color = theme.get("ui.text");
288 let completion_color = theme.get("ui.statusline");
289 let selected_color = theme.get("ui.menu.selected");
290 // completion
292 let max_len = self
293 .completion
294 .iter()
295 .map(|(_, completion)| completion.len() as u16)
296 .max()
297 .unwrap_or(BASE_WIDTH)
298 .max(BASE_WIDTH);
300 let cols = std::cmp::max(1, area.width / max_len);
301 let col_width = (area.width - (cols)) / cols;
303 let height = ((self.completion.len() as u16 + cols - 1) / cols)
304 .min(10) // at most 10 rows (or less)
305 .min(area.height.saturating_sub(1));
307 let completion_area = Rect::new(
308 area.x,
309 (area.height - height).saturating_sub(1),
310 area.width,
311 height,
312 );
314 if !self.completion.is_empty() {
315 let area = completion_area;
316 let background = theme.get("ui.statusline");
318 let items = height as usize * cols as usize;
320 let offset = self
321 .selection
322 .map(|selection| selection / items * items)
323 .unwrap_or_default();
325 surface.clear_with(area, background);
327 let mut row = 0;
328 let mut col = 0;
330 for (i, (_range, completion)) in
331 self.completion.iter().enumerate().skip(offset).take(items)
332 {
333 let color = if Some(i) == self.selection {
334 selected_color // TODO: just invert bg
335 } else {
336 completion_color
337 };
338 surface.set_stringn(
339 area.x + col * (1 + col_width),
340 area.y + row,
341 &completion,
342 col_width.saturating_sub(1) as usize,
343 color,
344 );
345 row += 1;
346 if row > area.height - 1 {
347 row = 0;
348 col += 1;
349 }
350 }
351 }
353 if let Some(doc) = (self.doc_fn)(&self.line) {
354 let mut text = ui::Text::new(doc.to_string());
356 let viewport = area;
357 let area = viewport.intersection(Rect::new(
358 completion_area.x,
359 completion_area.y.saturating_sub(3),
360 BASE_WIDTH * 3,
361 3,
362 ));
364 let background = theme.get("ui.help");
365 surface.clear_with(area, background);
367 text.render(
368 area.inner(&Margin {
369 vertical: 1,
370 horizontal: 1,
371 }),
372 surface,
373 cx,
374 );
375 }
377 let line = area.height - 1;
378 // render buffer text
379 surface.set_string(area.x, area.y + line, &self.prompt, prompt_color);
380 surface.set_string(
381 area.x + self.prompt.len() as u16,
382 area.y + line,
383 &self.line,
384 prompt_color,
385 );
386 }
389impl Component for Prompt {
390 fn handle_event(&mut self, event: Event, cx: &mut Context) -> EventResult {
391 let event = match event {
392 Event::Key(event) => event,
393 Event::Resize(..) => return EventResult::Consumed(None),
394 _ => return EventResult::Ignored,
395 };
397 let close_fn = EventResult::Consumed(Some(Box::new(|compositor: &mut Compositor| {
398 // remove the layer
399 compositor.pop();
400 })));
402 match event {
403 // char or shift char
404 KeyEvent {
405 code: KeyCode::Char(c),
406 modifiers: KeyModifiers::NONE,
407 }
408 | KeyEvent {
409 code: KeyCode::Char(c),
410 modifiers: KeyModifiers::SHIFT,
411 } => {
412 self.insert_char(c);
413 (self.callback_fn)(cx, &self.line, PromptEvent::Update);
414 }
415 KeyEvent {
416 code: KeyCode::Char('c'),
417 modifiers: KeyModifiers::CONTROL,
418 }
419 | KeyEvent {
420 code: KeyCode::Esc, ..
421 } => {
422 (self.callback_fn)(cx, &self.line, PromptEvent::Abort);
423 return close_fn;
424 }
425 KeyEvent {
426 code: KeyCode::Left,
427 modifiers: KeyModifiers::ALT,
428 }
429 | KeyEvent {
430 code: KeyCode::Char('b'),
431 modifiers: KeyModifiers::ALT,
432 } => self.move_cursor(Movement::BackwardWord(1)),
433 KeyEvent {
434 code: KeyCode::Right,
435 modifiers: KeyModifiers::ALT,
436 }
437 | KeyEvent {
438 code: KeyCode::Char('f'),
439 modifiers: KeyModifiers::ALT,
440 } => self.move_cursor(Movement::ForwardWord(1)),
441 KeyEvent {
442 code: KeyCode::Char('f'),
443 modifiers: KeyModifiers::CONTROL,
444 }
445 | KeyEvent {
446 code: KeyCode::Right,
447 ..
448 } => self.move_cursor(Movement::ForwardChar(1)),
449 KeyEvent {
450 code: KeyCode::Char('b'),
451 modifiers: KeyModifiers::CONTROL,
452 }
453 | KeyEvent {
454 code: KeyCode::Left,
455 ..
456 } => self.move_cursor(Movement::BackwardChar(1)),
457 KeyEvent {
458 code: KeyCode::End,
459 modifiers: KeyModifiers::NONE,
460 }
461 | KeyEvent {
462 code: KeyCode::Char('e'),
463 modifiers: KeyModifiers::CONTROL,
464 } => self.move_end(),
465 KeyEvent {
466 code: KeyCode::Home,
467 modifiers: KeyModifiers::NONE,
468 }
469 | KeyEvent {
470 code: KeyCode::Char('a'),
471 modifiers: KeyModifiers::CONTROL,
472 } => self.move_start(),
473 KeyEvent {
474 code: KeyCode::Char('w'),
475 modifiers: KeyModifiers::CONTROL,
476 } => self.delete_word_backwards(),
477 KeyEvent {
478 code: KeyCode::Char('k'),
479 modifiers: KeyModifiers::CONTROL,
480 } => self.kill_to_end_of_line(),
481 KeyEvent {
482 code: KeyCode::Backspace,
483 modifiers: KeyModifiers::NONE,
484 } => {
485 self.delete_char_backwards();
486 (self.callback_fn)(cx, &self.line, PromptEvent::Update);
487 }
488 KeyEvent {
489 code: KeyCode::Enter,
490 ..
491 } => {
492 if self.selection.is_some() && self.line.ends_with('/') {
493 self.completion = (self.completion_fn)(&self.line);
494 self.exit_selection();
495 } else {
496 (self.callback_fn)(cx, &self.line, PromptEvent::Validate);
498 if let Some(register) = self.history_register {
499 // store in history
500 let register = cx.editor.registers.get_mut(register);
501 register.push(self.line.clone());
502 }
503 return close_fn;
504 }
505 }
506 KeyEvent {
507 code: KeyCode::Char('p'),
508 modifiers: KeyModifiers::CONTROL,
509 }
510 | KeyEvent {
511 code: KeyCode::Up, ..
512 } => {
513 if let Some(register) = self.history_register {
514 let register = cx.editor.registers.get_mut(register);
515 self.change_history(register.read(), CompletionDirection::Backward);
516 }
517 }
518 KeyEvent {
519 code: KeyCode::Char('n'),
520 modifiers: KeyModifiers::CONTROL,
521 }
522 | KeyEvent {
523 code: KeyCode::Down,
524 ..
525 } => {
526 if let Some(register) = self.history_register {
527 let register = cx.editor.registers.get_mut(register);
528 self.change_history(register.read(), CompletionDirection::Forward);
529 }
530 }
531 KeyEvent {
532 code: KeyCode::Tab, ..
533 } => self.change_completion_selection(CompletionDirection::Forward),
534 KeyEvent {
535 code: KeyCode::BackTab,
536 ..
537 } => self.change_completion_selection(CompletionDirection::Backward),
538 KeyEvent {
539 code: KeyCode::Char('q'),
540 modifiers: KeyModifiers::CONTROL,
541 } => self.exit_selection(),
542 _ => (),
543 };
545 EventResult::Consumed(None)
546 }
548 fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
549 self.render_prompt(area, surface, cx)
550 }
552 fn cursor(&self, area: Rect, _editor: &Editor) -> (Option<Position>, CursorKind) {
553 let line = area.height as usize - 1;
554 (
555 Some(Position::new(
556 area.y as usize + line,
557 area.x as usize
558 + self.prompt.len()
559 + UnicodeWidthStr::width(&self.line[..self.cursor]),
560 )),
561 CursorKind::Block,
562 )
563 }