From f0ab3d0c316a9dba55b8c7d5248e2c9830ae6b64 Mon Sep 17 00:00:00 2001 From: Victor-Loos Date: Mon, 26 Oct 2026 18:31:19 +0100 Subject: [PATCH 1/2] feat: add in-place tab completion cycling Add an opt-in tabCompletionCycleInsert action that writes the selected candidate into the command buffer and replaces it on subsequent Tab presses. Expose tabCompletionInserted so Enter can submit a candidate already present in the buffer. Scope insertion requests to the active completion and invalidate them on edits, cursor movement or selection changes. Preserve the selected candidate as more results arrive or the grid changes shape, and use the complete inserted span when accepting one or all candidates. Document the bindings and add unit and Bash PTY regression coverage for cycling, navigation, cancellation, editing, Unicode, undo and resizing. Validation: - cargo test --workspace --lib --locked - cargo fmt --all -- --check - cargo clippy --workspace --all-features --locked -- -D warnings - cargo doc --workspace --no-deps --document-private-items --locked - cargo build --release --locked - python3 tests/tab_cycle_pty.py --flyline target/release/libflyline.so --- README.md | 12 + src/active_suggestions.rs | 366 +++++++++++++++++++++++++++--- src/app/actions/keyboard.rs | 19 +- src/app/mod.rs | 33 ++- src/cli.rs | 2 +- src/completions/tab_completion.rs | 40 +++- tests/tab_cycle_pty.py | 232 +++++++++++++++++++ 7 files changed, 669 insertions(+), 35 deletions(-) create mode 100755 tests/tab_cycle_pty.py diff --git a/README.md b/README.md index de152eff..8a5e4174 100644 --- a/README.md +++ b/README.md @@ -803,6 +803,18 @@ If `tabCompletionAvailable` is false, then it will try the next keybinding for ` The `always` context variable is always true. For tab completion, `tabCompletionOneResult` is true when there is exactly one tab completion result. +The `tabCompletionCycleInsert` action writes the highlighted suggestion into the buffer instead of only highlighting it, and repeating it replaces that text with the next suggestion (`menu-complete` in other shells). +It is opt-in: without these bindings Tab keeps its default behavior. +Typing or moving the cursor ends the cycle; `tabCompletionInserted` lets Enter submit text already inserted. + +```bash +flyline key bind Tab 'editingBufferMode=tabCompletionCycleInsert' +flyline key bind Tab 'tabCompletionBackgroundActive=tabCompletionCycleInsert' +flyline key bind Tab 'tabCompletionWaiting=tabCompletionCycleInsert' +flyline key bind Tab 'tabCompletionAvailable=tabCompletionCycleInsert' +flyline key bind Enter 'tabCompletionInserted=submitOrNewline' +``` + Flyline provides useful tab completions to help you write keybindings. #### List keybindings diff --git a/src/active_suggestions.rs b/src/active_suggestions.rs index 13132d82..5dc66d77 100644 --- a/src/active_suggestions.rs +++ b/src/active_suggestions.rs @@ -1221,6 +1221,7 @@ mod description_tests { selected_coord: None, original_word_under_cursor: wuc.clone(), word_under_cursor: wuc, + inserted: None, last_num_rows_per_col: 0, last_num_visible_cols: 0, last_num_data_cols: 0, @@ -1857,6 +1858,35 @@ pub struct ColumnInfo { pub is_selected_col: bool, } +#[derive(Debug)] +pub(crate) struct CompletionBufferState { + contents: String, + cursor: usize, + selection: Option, +} + +impl CompletionBufferState { + pub fn new(buffer: &TextBuffer) -> Self { + Self { + contents: buffer.buffer().to_string(), + cursor: buffer.cursor_byte_pos(), + selection: buffer.selection_byte(), + } + } + + pub fn matches(&self, buffer: &TextBuffer) -> bool { + self.contents == buffer.buffer() + && self.cursor == buffer.cursor_byte_pos() + && self.selection == buffer.selection_byte() + } +} + +#[derive(Debug)] +struct InsertedSuggestion { + span: SubString, + state: CompletionBufferState, +} + #[derive(Debug)] pub struct ActiveSuggestions { /// Raw completions waiting to be post-processed. Drained from the front @@ -1872,6 +1902,8 @@ pub struct ActiveSuggestions { pub selected_coord: Option<(usize, usize)>, pub original_word_under_cursor: SubString, pub word_under_cursor: SubString, + /// The last cycle insertion, valid until the buffer or cursor changes. + inserted: Option, /// Number of suggestion rows per column as used in the last rendered /// grid. Kept in sync by [`update_grid_size`]. last_num_rows_per_col: usize, @@ -1935,6 +1967,7 @@ impl ActiveSuggestions { selected_coord: if auto_started { None } else { Some((0, 0)) }, original_word_under_cursor: word_under_cursor.clone(), word_under_cursor: word_under_cursor.clone(), + inserted: None, last_num_rows_per_col: 0, last_num_visible_cols: 0, last_num_data_cols: 0, @@ -2013,6 +2046,15 @@ impl ActiveSuggestions { self.clamp_selection(); } + /// Preserve the flat selection index when the rendered grid changes shape. + fn update_grid_size(&mut self, num_rows_per_col: usize) { + let selected_idx = self.current_1d_index(); + self.last_num_rows_per_col = num_rows_per_col; + if let Some(idx) = selected_idx { + self.set_selected_by_idx(idx); + } + } + /// Ensure the selected position refers to a valid suggestion. fn clamp_selection(&mut self) { let n = self.filtered_suggestions.len(); @@ -2201,13 +2243,14 @@ impl ActiveSuggestions { self.update_fuzzy_filtered(); } - let selected_1d = self.current_1d_index(); - let selected_col = self.selected_coord.map(|(c, _)| c).unwrap_or(0); let n = self.filtered_suggestions.len(); if n == 0 || max_rows == 0 { self.last_num_data_cols = 0; return vec![]; } + self.update_grid_size(max_rows); + let selected_1d = self.current_1d_index(); + let selected_col = self.selected_coord.map(|(c, _)| c).unwrap_or(0); // Compute the animation frame index at ANIMATION_FRAME_FPS fps from the current wall-clock time. let frame_index: usize = std::time::SystemTime::now() @@ -2335,7 +2378,6 @@ impl ActiveSuggestions { self.last_num_visible_cols = final_grid.len(); - self.last_num_rows_per_col = max_rows; final_grid } @@ -2346,7 +2388,6 @@ impl ActiveSuggestions { self.update_fuzzy_filtered(); } - let selected_row = self.selected_coord.map(|(_, r)| r).unwrap_or(0); let n = self.filtered_suggestions.len(); if n == 0 || max_rows == 0 { return vec![]; @@ -2354,7 +2395,8 @@ impl ActiveSuggestions { self.last_num_data_cols = 1; self.last_num_visible_cols = 1; - self.last_num_rows_per_col = n.max(1); + self.update_grid_size(n); + let selected_row = self.current_1d_index().unwrap_or(0); let frame_index: usize = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -2475,13 +2517,81 @@ impl ActiveSuggestions { } pub fn update_word_under_cursor(&mut self, new_word_under_cursor: &SubString) { + self.inserted = None; self.word_under_cursor = new_word_under_cursor.clone(); self.update_fuzzy_filtered(); } + /// Whether completion should retain its original filter and replacement span. + /// An external edit or cursor movement ends the cycle, even if the inserted + /// substring itself happens to be unchanged. + pub fn insertion_is_current(&self, buffer: &TextBuffer) -> bool { + self.inserted + .as_ref() + .is_some_and(|inserted| inserted.state.matches(buffer)) + } + + pub fn has_insertion(&self) -> bool { + self.inserted.is_some() + } + + /// Enter may submit directly only while the highlighted candidate is the + /// one already in the buffer. Navigation can select a different candidate. + pub fn selected_is_inserted(&self, buffer: &TextBuffer) -> bool { + self.insertion_is_current(buffer) + && self.selected_suggestion().is_some_and(|suggestion| { + self.inserted + .as_ref() + .is_some_and(|inserted| suggestion.formatted() == inserted.span.s) + }) + } + + fn selected_suggestion(&self) -> Option<&ProcessedSuggestion> { + let index = self + .current_1d_index() + .or_else(|| (self.filtered_suggestions.len() == 1).then_some(0))?; + let item = self.filtered_suggestions.get(index)?; + self.processed_suggestions.get(item.suggestion_idx) + } + + fn replacement_span(&self, buffer: &TextBuffer) -> Option<&SubString> { + match &self.inserted { + Some(inserted) => inserted.state.matches(buffer).then_some(&inserted.span), + None => Some(&self.word_under_cursor), + } + } + + /// Promote background suggestions and cycle independently of grid layout, + /// which may not have been rendered yet when the first results arrive. + pub fn cycle_insert(&mut self, buffer: &mut TextBuffer) -> Option { + self.auto_started = false; + while self.filtered_suggestions.is_empty() && !self.unprocessed_suggestions.is_empty() { + self.process_chunk(); + self.update_fuzzy_filtered(); + } + let n = self.filtered_suggestions.len(); + if n == 0 { + return None; + } + if self.selected_coord.is_none() { + self.set_selected_by_idx(0); + } else if self.selected_is_inserted(buffer) { + self.set_selected_by_idx((self.current_1d_index()? + 1) % n); + } + self.insert_selected(buffer) + } + /// Apply fuzzy search filtering to the suggestions based on the given pattern. fn update_fuzzy_filtered(&mut self) { let had_selection = self.selected_coord.is_some(); + // New processing chunks can change the sort order while cycling. + // Preserve the candidate's identity, not its previous filtered index. + // External edits clear `inserted` before updating the filter. + let selected_suggestion_idx = self.inserted.as_ref().and_then(|_| { + self.current_1d_index() + .and_then(|idx| self.filtered_suggestions.get(idx)) + .map(|item| item.suggestion_idx) + }); let raw_pattern = self.word_under_cursor.s.as_str(); log::debug!( "Applying fuzzy filter with raw_pattern {:?} on {} processed suggestions ({} still unprocessed)", @@ -2528,6 +2638,13 @@ impl ActiveSuggestions { Some((0, 0)) }; } + if let Some(idx) = selected_suggestion_idx.and_then(|suggestion_idx| { + self.filtered_suggestions + .iter() + .position(|item| item.suggestion_idx == suggestion_idx) + }) { + self.set_selected_by_idx(idx); + } self.formatted_cache = vec![None; self.filtered_suggestions.len()]; } @@ -2545,36 +2662,39 @@ impl ActiveSuggestions { } pub fn accept_selected_filtered_item(&mut self, buffer: &mut TextBuffer) { - let selected_idx = if let Some(selected_idx) = self.current_1d_index() { - selected_idx - } else if self.filtered_suggestions.len() == 1 { - 0 - } else { + let Some(suggestion) = self.selected_suggestion() else { log::warn!("No selected suggestion to accept"); return; }; - let Some(filtered_item) = self.filtered_suggestions.get(selected_idx) else { - log::warn!("No suggestion at selected index {}", selected_idx); - return; - }; - - let Some(suggestion) = self.processed_suggestions.get(filtered_item.suggestion_idx) else { - log::warn!( - "Suggestion index {} out of bounds (processed len={})", - filtered_item.suggestion_idx, - self.processed_suggestions.len() - ); + let Some(target) = self.replacement_span(buffer) else { return; }; - - if let Err(e) = - buffer.replace_word_under_cursor(&suggestion.formatted(), &self.word_under_cursor) - { + if let Err(e) = buffer.replace_word_under_cursor(&suggestion.formatted(), target) { log::error!("Failed to apply suggestion: {}", e); } } + /// Replace the original word or the previous insertion with the selected + /// candidate and record the resulting buffer state for the next cycle. + fn insert_selected(&mut self, buffer: &mut TextBuffer) -> Option { + let text = self.selected_suggestion()?.formatted(); + let target = self.replacement_span(buffer)?; + match buffer.replace_word_under_cursor(&text, target) { + Ok(new_span) => { + self.inserted = Some(InsertedSuggestion { + span: new_span.clone(), + state: CompletionBufferState::new(buffer), + }); + Some(new_span) + } + Err(e) => { + log::warn!("Could not insert suggestion: {}", e); + None + } + } + } + pub fn accept_all_filtered_items(&mut self, buffer: &mut TextBuffer) { if self.filtered_suggestions.is_empty() { return; @@ -2606,12 +2726,206 @@ impl ActiveSuggestions { joined.push_str(s); } - if let Err(e) = buffer.replace_word_under_cursor(&joined, &self.word_under_cursor) { + let Some(target) = self.replacement_span(buffer) else { + return; + }; + if let Err(e) = buffer.replace_word_under_cursor(&joined, target) { log::error!("Failed to apply all suggestions: {}", e); } } } +#[cfg(test)] +mod cycle_tests { + use super::*; + + fn suggestions(buffer: &TextBuffer, start: usize, values: &[&str]) -> ActiveSuggestions { + ActiveSuggestions::new( + ActiveSuggestionsBuilder::from_processed( + values.iter().map(|s| ProcessedSuggestion::new(*s, "", "")), + ), + SubString { + start, + s: buffer.buffer()[start..].to_string(), + }, + std::time::Duration::ZERO, + false, + crate::settings::SuggestionSortOrder::Alphabetical, + crate::settings::FuzzyMode::None, + ) + } + + #[test] + fn cycles_and_wraps_before_first_render() { + let mut buffer = TextBuffer::new("cmd f"); + let mut active = suggestions(&buffer, 4, &["far ", "foo "]); + for expected in ["cmd far ", "cmd foo ", "cmd far "] { + active.cycle_insert(&mut buffer).unwrap(); + assert_eq!(buffer.buffer(), expected); + assert!(active.selected_is_inserted(&buffer)); + assert_eq!(active.filtered_suggestions_len(), 2); + } + } + + #[test] + fn cycles_across_rendered_columns() { + let mut buffer = TextBuffer::new("cmd f"); + let mut active = suggestions(&buffer, 4, &["faa", "fbb", "fcc", "fdd", "fee"]); + for value in ["faa", "fbb", "fcc", "fdd", "fee", "faa"] { + active.into_grid(2, 80, &Palette::default(), None); + active.cycle_insert(&mut buffer).unwrap(); + assert_eq!(buffer.buffer(), format!("cmd {value}")); + } + } + + #[test] + fn resizing_preserves_the_inserted_candidate_and_cycle_order() { + let mut buffer = TextBuffer::new("cmd f"); + let mut active = suggestions(&buffer, 4, &["faa", "fbb", "fcc", "fdd", "fee"]); + active.into_grid(2, 80, &Palette::default(), None); + for _ in 0..4 { + active.cycle_insert(&mut buffer).unwrap(); + } + assert_eq!(buffer.buffer(), "cmd fdd"); + for rows in [1, 3, 2] { + active.into_list(2, &Palette::default()); + assert!(active.selected_is_inserted(&buffer)); + active.into_grid(rows, 40, &Palette::default(), None); + assert!(active.selected_is_inserted(&buffer)); + assert_eq!(active.current_1d_index(), Some(3)); + } + active.cycle_insert(&mut buffer).unwrap(); + assert_eq!(buffer.buffer(), "cmd fee"); + } + + #[test] + fn new_results_preserve_the_highlighted_candidate_during_a_cycle() { + let mut buffer = TextBuffer::new("cmd f"); + let mut active = suggestions(&buffer, 4, &["foo", "fzz"]); + active.cycle_insert(&mut buffer).unwrap(); + // A later chunk inserts an entry before the selected candidate. + active + .unprocessed_suggestions + .push_back(UnprocessedSuggestion { + raw_text: "far".into(), + full_path: None, + flags: shell::CompletionFlags { + no_suffix_desired: true, + ..Default::default() + }, + word_under_cursor: "f".into(), + is_git_command: false, + custom_prefix: None, + }); + active.into_grid(2, 80, &Palette::default(), None); + assert!(active.selected_is_inserted(&buffer)); + assert_eq!(active.current_1d_index(), Some(1)); + // Also preserve a candidate highlighted by navigation, before insertion. + active.set_selected_by_idx(2); + active.update_fuzzy_filtered(); + assert_eq!(active.selected_suggestion().unwrap().s, "fzz"); + active.cycle_insert(&mut buffer).unwrap(); + assert_eq!(buffer.buffer(), "cmd fzz"); + } + + #[test] + fn promotes_background_suggestions_without_a_grid() { + let mut buffer = TextBuffer::new("cmd f"); + let mut active = suggestions(&buffer, 4, &["far", "foo"]); + active.auto_started = true; + active.selected_coord = None; + active.cycle_insert(&mut buffer).unwrap(); + assert_eq!(buffer.buffer(), "cmd far"); + assert!(!active.auto_started); + } + + #[test] + fn navigation_accepts_highlighted_candidate_without_skipping_it() { + let mut buffer = TextBuffer::new("cmd f"); + let mut active = suggestions(&buffer, 4, &["far", "foo", "fzz"]); + active.cycle_insert(&mut buffer).unwrap(); + active.set_selected_by_idx(1); + assert!(!active.selected_is_inserted(&buffer)); + active.cycle_insert(&mut buffer).unwrap(); + assert_eq!(buffer.buffer(), "cmd foo"); + active.set_selected_by_idx(2); + assert!(!active.selected_is_inserted(&buffer)); + active.accept_selected_filtered_item(&mut buffer); + assert_eq!(buffer.buffer(), "cmd fzz"); + } + + #[test] + fn accept_all_replaces_entire_inserted_text() { + let mut buffer = TextBuffer::new("cmd f"); + let mut active = suggestions(&buffer, 4, &["far", "foo"]); + active.cycle_insert(&mut buffer).unwrap(); + active.accept_all_filtered_items(&mut buffer); + assert_eq!(buffer.buffer(), "cmd far foo"); + } + + #[test] + fn typing_invalidates_insertion_and_refinement_uses_the_new_word() { + let mut buffer = TextBuffer::new("cmd foo"); + let mut active = suggestions(&buffer, 4, &["foo", "foobar"]); + active.cycle_insert(&mut buffer).unwrap(); + buffer.insert_str("b"); + assert!(!active.insertion_is_current(&buffer)); + assert!(!active.selected_is_inserted(&buffer)); + assert!(active.cycle_insert(&mut buffer).is_none()); + assert_eq!(buffer.buffer(), "cmd foob"); + active.update_word_under_cursor(&SubString { + start: 4, + s: "foob".into(), + }); + active.cycle_insert(&mut buffer).unwrap(); + assert_eq!(buffer.buffer(), "cmd foobar"); + } + + #[test] + fn cursor_movement_and_edits_outside_the_span_end_insertion() { + let mut buffer = TextBuffer::new("cmd f"); + let mut active = suggestions(&buffer, 4, &["far", "foo"]); + active.cycle_insert(&mut buffer).unwrap(); + buffer.move_left(); + assert!(!active.insertion_is_current(&buffer)); + active.accept_all_filtered_items(&mut buffer); + assert_eq!(buffer.buffer(), "cmd far"); + buffer.replace_buffer("new far"); + assert!(!active.insertion_is_current(&buffer)); + active.accept_selected_filtered_item(&mut buffer); + assert_eq!(buffer.buffer(), "new far"); + } + + #[test] + fn quoted_unicode_candidates_replace_the_complete_byte_span() { + let mut buffer = TextBuffer::new("cmd \"é"); + let mut active = suggestions(&buffer, 4, &["\"été un\" ", "\"été deux\" "]); + active.cycle_insert(&mut buffer).unwrap(); + active.cycle_insert(&mut buffer).unwrap(); + assert_eq!(buffer.buffer(), "cmd \"été un\" "); + } + + #[test] + fn undo_restores_the_previous_candidate_and_invalidates_insertion() { + let mut buffer = TextBuffer::new("cmd f"); + let mut active = suggestions(&buffer, 4, &["far", "foo"]); + active.cycle_insert(&mut buffer).unwrap(); + active.cycle_insert(&mut buffer).unwrap(); + buffer.undo(); + assert_eq!(buffer.buffer(), "cmd far"); + assert!(!active.insertion_is_current(&buffer)); + } + + #[test] + fn empty_results_leave_the_buffer_unchanged() { + let mut buffer = TextBuffer::new("cmd f"); + let mut active = suggestions(&buffer, 4, &[]); + assert!(active.cycle_insert(&mut buffer).is_none()); + assert!(!active.has_insertion()); + assert_eq!(buffer.buffer(), "cmd f"); + } +} + #[cfg(test)] mod subshell_payload_serde_tests { use super::*; diff --git a/src/app/actions/keyboard.rs b/src/app/actions/keyboard.rs index 32ce9652..ff85d80e 100644 --- a/src/app/actions/keyboard.rs +++ b/src/app/actions/keyboard.rs @@ -78,6 +78,10 @@ pub enum KeyEventAction { TabCompletionPrevSuggestion, #[strum(message = "Move to the next tab completion suggestion")] TabCompletionNextSuggestion, + #[strum( + message = "Write the selected suggestion into the buffer, replacing the one written by the previous press" + )] + TabCompletionCycleInsert, #[strum(message = "Promote background tab completion to user-visible completion")] TabCompletionPromote, #[strum(message = "Scroll up through fuzzy history search results")] @@ -492,12 +496,13 @@ impl KeyEventAction { ContentMode::TabCompletion(suggestions) => Some(suggestions), _ => None, }; - app.start_tab_complete(false, previous_suggestions); + app.start_tab_complete(false, previous_suggestions, false); } else if let ContentMode::TabCompletion(active_suggestions) = &mut app.content_mode { active_suggestions.on_tab(false); } } + KeyEventAction::TabCompletionCycleInsert => app.cycle_insert_tab_completion(), KeyEventAction::FuzzyHistorySelectPrev => { let source = match &app.content_mode { ContentMode::FuzzyHistorySearch(s) => *s, @@ -647,7 +652,7 @@ impl KeyEventAction { } _ => {} }, - KeyEventAction::RunTabCompletion => app.start_tab_complete(false, None), + KeyEventAction::RunTabCompletion => app.start_tab_complete(false, None, false), KeyEventAction::RunFlycomp => app.force_start_flycomp(), KeyEventAction::ToggleMouse => { if matches!( @@ -1097,9 +1102,9 @@ impl KeyEventAction { // Capture the word-under-cursor when dismissing tab completion, so we don't // auto-suggest on the same word the user just dismissed. match &app.content_mode { - ContentMode::TabCompletion(active_suggestions) => { + ContentMode::TabCompletion(_) => { app.dismissed_tab_completion_wuc = - Some(active_suggestions.word_under_cursor.s.to_string()); + Some(app.get_completion_context().word_under_cursor.s.clone()); } ContentMode::TabCompletionWaiting { wuc_substring, .. } => { app.dismissed_tab_completion_wuc = Some(wuc_substring.s.to_string()); @@ -4653,6 +4658,8 @@ pub(crate) enum ContextVar { TabCompletionEntrySelected, #[strum(message = "Tab completion overlay is active and has exactly one filtered candidate")] TabCompletionOneResult, + #[strum(message = "The selected tab completion suggestion is already written into the buffer")] + TabCompletionInserted, #[strum(message = "Tab completion overlay is showing more than one column of candidates")] TabCompletionMultiColAvailable, #[strum(message = "Tab completion overlay is active but fuzzy filtering has no matches")] @@ -4766,6 +4773,10 @@ impl ContextVar { &app.content_mode, ContentMode::TabCompletion(active) if active.filtered_suggestions_len() == 1 ), + ContextVar::TabCompletionInserted => matches!( + &app.content_mode, + ContentMode::TabCompletion(active) if active.selected_is_inserted(&app.buffer) + ), ContextVar::TabCompletionMultiColAvailable => matches!( &app.content_mode, ContentMode::TabCompletion(active) diff --git a/src/app/mod.rs b/src/app/mod.rs index 64c10436..1e7a06cb 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -306,6 +306,8 @@ pub(crate) enum ContentMode { wuc_substring: SubString, start_time: std::time::Instant, auto_started: bool, + cycle_insert: bool, + buffer_state: crate::active_suggestions::CompletionBufferState, last_active_suggestions: Option>, }, /// AI command is running as a child process. The child is polled each @@ -1766,6 +1768,8 @@ impl<'a> App<'a> { ref handle, ref wuc_substring, auto_started, + cycle_insert, + ref buffer_state, .. } = self.content_mode { @@ -1777,10 +1781,11 @@ impl<'a> App<'a> { handle.pid ); let wuc = wuc_substring.clone(); + let cycle_insert = cycle_insert && buffer_state.matches(&self.buffer); self.content_mode = ContentMode::Normal; if let Some((builder, elapsed)) = completion_res { - self.finish_tab_complete(builder, wuc, elapsed, auto_started); + self.finish_tab_complete(builder, wuc, elapsed, auto_started, cycle_insert); self.on_possible_buffer_change(); } return true; @@ -1835,7 +1840,7 @@ impl<'a> App<'a> { .resolve_and_write_completion_script(&cmd_word, &script, output_dir); let _ = shell::backend().evaluate_shell_string(&script); self.content_mode = ContentMode::Normal; - self.start_tab_complete(false, None); + self.start_tab_complete(false, None, false); return true; } IpcStatus::Disconnected => { @@ -2164,6 +2169,23 @@ impl<'a> App<'a> { } fn on_possible_buffer_change(&mut self) { + // Keep the original candidate set while cycling. Any external edit or + // cursor movement ends the cycle, including a pending first insertion. + let (keep_cycle, end_cycle) = match &self.content_mode { + ContentMode::TabCompletion(active) => { + let current = active.insertion_is_current(&self.buffer); + (current, active.has_insertion() && !current) + } + ContentMode::TabCompletionWaiting { + cycle_insert: true, + buffer_state, + .. + } => (false, !buffer_state.matches(&self.buffer)), + _ => (false, false), + }; + if end_cycle { + self.take_active_suggestions(); + } if let ContentMode::AgentOutputSelection(ref mut selection) = self.content_mode { let current_buf = self.buffer.buffer(); if current_buf != selection.last_buffer_content { @@ -2245,6 +2267,7 @@ impl<'a> App<'a> { || crate::settings().auto_suggest_inline || is_tab_completion_active) && self.last_key.is_some() + && (!keep_cycle || navigated_history) { #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum CompletionAction { @@ -2458,7 +2481,11 @@ impl<'a> App<'a> { CompletionAction::Restart { carry_over } => { self.dismissed_tab_completion_wuc = None; let prev = self.take_active_suggestions().filter(|_| carry_over); - self.start_tab_complete(prev.as_ref().is_none_or(|p| p.auto_started), prev); + self.start_tab_complete( + prev.as_ref().is_none_or(|p| p.auto_started), + prev, + false, + ); } } } diff --git a/src/cli.rs b/src/cli.rs index 9dc20967..4ebe9613 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -763,7 +763,7 @@ enum KeySubcommands { /// /// Available context variables: always, bufferIsEmpty, bufferIsTrimmedEmpty, /// fuzzyHistorySearch, tabCompletionWaiting, tabCompletion, - /// tabCompletionAvailable, tabCompletionOneResult, + /// tabCompletionAvailable, tabCompletionOneResult, tabCompletionInserted, /// tabCompletionMultiColAvailable, tabCompletionNoFilteredResults, /// tabCompletionNoResults, agentModeWaiting, agentOutputSelection, /// agentModeError, inlineSuggestionAvailable, cursorAtEnd, diff --git a/src/completions/tab_completion.rs b/src/completions/tab_completion.rs index eaa7344b..4955e669 100644 --- a/src/completions/tab_completion.rs +++ b/src/completions/tab_completion.rs @@ -1116,6 +1116,7 @@ impl App<'_> { wuc_substring: SubString, load_time: std::time::Duration, auto_started: bool, + cycle_insert: bool, ) { let completion_context = self.get_completion_context(); let command_word = completion_context @@ -1158,7 +1159,7 @@ impl App<'_> { self.content_mode = ContentMode::Normal; } TabCompleteBufferOutcome::Pending { final_wuc } => { - let suggestions = ActiveSuggestions::new( + let mut suggestions = ActiveSuggestions::new( builder, final_wuc, load_time, @@ -1166,11 +1167,45 @@ impl App<'_> { crate::settings().suggestion_sort_order, crate::settings().fuzzy_mode, ); + if cycle_insert { + suggestions.cycle_insert(&mut self.buffer); + } self.content_mode = ContentMode::TabCompletion(Box::new(suggestions)); } } } } + + /// Backing action for `tabCompletionCycleInsert`: the first press starts tab + /// completion and writes the first suggestion into the buffer, further + /// presses replace that text with the next suggestion. + pub fn cycle_insert_tab_completion(&mut self) { + match &mut self.content_mode { + ContentMode::TabCompletion(active) => { + if active.cycle_insert(&mut self.buffer).is_none() + && active.filtered_suggestions_len() == 0 + { + let previous = self.take_active_suggestions(); + self.start_tab_complete(false, previous, true); + } + } + ContentMode::TabCompletionWaiting { + auto_started, + cycle_insert, + buffer_state, + .. + } if buffer_state.matches(&self.buffer) => { + // Promote the request already in flight instead of killing and + // restarting a slow completion on every Tab press. + *auto_started = false; + *cycle_insert = true; + } + ContentMode::Normal | ContentMode::TabCompletionWaiting { .. } => { + self.start_tab_complete(false, None, true); + } + _ => {} + } + } pub(crate) fn start_flycomp_prompt( &mut self, command_word: String, @@ -1216,6 +1251,7 @@ impl App<'_> { &mut self, auto_started: bool, previous_suggestions: Option>, + cycle_insert: bool, ) { // Stop the current tab completion process if one is running by dropping its handle if let ContentMode::TabCompletionWaiting { handle, .. } = @@ -1282,6 +1318,8 @@ impl App<'_> { wuc_substring, start_time, auto_started, + cycle_insert, + buffer_state: crate::active_suggestions::CompletionBufferState::new(&self.buffer), last_active_suggestions, }; diff --git a/tests/tab_cycle_pty.py b/tests/tab_cycle_pty.py new file mode 100755 index 00000000..6d29a44f --- /dev/null +++ b/tests/tab_cycle_pty.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +"""Exercise completion cycling in a real Bash PTY, without Docker. + +Usage: python3 tests/tab_cycle_pty.py --flyline target/release/libflyline.so +""" + +import argparse +import errno +import fcntl +from functools import partial +import os +from pathlib import Path +import pty +import re +import select +import shlex +import signal +import struct +import tempfile +import termios +import time + + +# Flyline enables CSI-u key disambiguation. Avoid the legacy Escape/Alt timeout. +ESCAPE = b"\x1b[27u" + + +class Shell: + def __init__( + self, library, directory, bash_path, *, automatic=False, inline=False, delay=0 + ): + self.output = bytearray() + self.queries = {b"\x1b[>c": 0, b"\x1b[6n": 0} + self.requests = directory / "requests" + rcfile = directory / "bashrc" + rcfile.write_text( + "PS1='$ '\n" + "HISTFILE=/dev/null\n" + "__cycle() { printf '\\nCYCLE_RESULT:<%s>\\n' \"$*\"; }\n" + "__complete_cycle() {\n" + f" printf x >> {shlex.quote(str(self.requests))}\n" + f" sleep {delay}\n" + " COMPREPLY=()\n" + " local value\n" + " for value in foo foobar; do\n" + ' [[ $value == "${COMP_WORDS[COMP_CWORD]}"* ]] && COMPREPLY+=("$value")\n' + " done\n" + " return 0\n" + "}\n" + "complete -o nospace -F __complete_cycle __cycle\n" + f"enable -f {shlex.quote(str(library))} flyline || exit 1\n" + "flyline --set-delayed-startup-ms 0\n" + "flyline mouse --mode disabled\n" + "flyline suggestions --sort-order alphabetical " + f"--auto-suggest {str(automatic).lower()} " + f"--auto-suggest-inline {str(inline).lower()}\n" + "flyline key bind Tab 'editingBufferMode=tabCompletionCycleInsert'\n" + "flyline key bind Tab 'tabCompletionBackgroundActive=tabCompletionCycleInsert'\n" + "flyline key bind Tab 'tabCompletionWaiting=tabCompletionCycleInsert'\n" + "flyline key bind Tab 'tabCompletionAvailable=tabCompletionCycleInsert'\n" + "flyline key bind Enter 'tabCompletionInserted=submitOrNewline'\n" + "flyline key bind Ctrl+g 'always=submitOrNewline'\n" + "flyline key bind Ctrl+y 'tabCompletionAvailable=tabCompletionAcceptAll'\n", + encoding="utf-8", + ) + self.pid, self.fd = pty.fork() + if self.pid == 0: + environment = os.environ | { + "TERM": "xterm-256color", + "COLUMNS": "100", + "LINES": "30", + "XDG_DATA_HOME": str(directory / "data"), + "XDG_CACHE_HOME": str(directory / "cache"), + "XDG_CONFIG_HOME": str(directory / "config"), + "XDG_STATE_HOME": str(directory / "state"), + } + os.chdir(directory) + os.execve( + bash_path, + [str(bash_path), "--noprofile", "--rcfile", str(rcfile), "-i"], + environment, + ) + fcntl.ioctl(self.fd, termios.TIOCSWINSZ, struct.pack("HHHH", 30, 100, 0, 0)) + + def pump(self, duration): + deadline = time.monotonic() + duration + while time.monotonic() < deadline: + timeout = min(0.02, max(0, deadline - time.monotonic())) + ready, _, _ = select.select([self.fd], [], [], timeout) + if ready: + try: + data = os.read(self.fd, 65536) + except OSError as error: + if error.errno == errno.EIO: + raise AssertionError(f"Bash exited: {bytes(self.output[-1000:])!r}") from error + raise + if not data: + raise AssertionError("Bash closed its terminal") + self.output.extend(data) + for query, response in [ + (b"\x1b[>c", b"\x1b[>0;1;0c"), + (b"\x1b[6n", b"\x1b[1;1R"), + ]: + count = self.output.count(query) + for _ in range(count - self.queries[query]): + os.write(self.fd, response) + self.queries[query] = count + + def send(self, keys, wait=0.15): + os.write(self.fd, keys) + self.pump(wait) + + def expect_result(self, value): + expected = f"CYCLE_RESULT:<{value}>".encode() + deadline = time.monotonic() + 3 + while expected not in self.output and time.monotonic() < deadline: + self.pump(0.05) + visible = re.sub(rb"\x1b\[[0-?]*[ -/]*[@-~]", b"", self.output) + visible = b" ".join(visible.split())[-1000:] + results = re.findall(rb"\r?\nCYCLE_RESULT:<([^\r\n]*)>\r?\n", self.output) + assert results == [value.encode()], ( + f"Expected only {expected!r}; terminal tail: {visible!r}" + ) + + def close(self): + try: + os.kill(self.pid, signal.SIGKILL) + except ProcessLookupError: + pass + os.close(self.fd) + os.waitpid(self.pid, 0) + + +def run_case( + library, name, steps, expected, *, bash_path, request_count=None, **options +): + with tempfile.TemporaryDirectory(prefix="flyline-cycle-test-") as directory: + shell = Shell(library, Path(directory), bash_path, **options) + try: + deadline = time.monotonic() + 3 + while b"\x1b[?2004h" not in shell.output and time.monotonic() < deadline: + shell.pump(0.02) + assert b"\x1b[?2004h" in shell.output, "Flyline did not initialize the terminal" + shell.pump(0.15) + for index, (keys, wait) in enumerate(steps): + shell.send(keys, wait) + if index == 0 and options.get("delay"): + deadline = time.monotonic() + 3 + while not shell.requests.exists() and time.monotonic() < deadline: + shell.pump(0.01) + assert shell.requests.exists(), "Completion process did not start" + shell.expect_result(expected) + if request_count is not None: + assert shell.requests.read_text() == "x" * request_count, ( + "Unexpected completion process count" + ) + print(f"PASS: {name}", flush=True) + finally: + shell.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--bash", type=Path, default=Path("/bin/bash")) + parser.add_argument("--flyline", type=Path, required=True) + arguments = parser.parse_args() + run = partial( + run_case, + arguments.flyline.resolve(strict=True), + bash_path=arguments.bash.resolve(strict=True), + ) + run( + "cycle then Enter", + [(b"__cycle f", 0.15), (b"\t", 0.2), (b"\t", 0.1), (b"\r", 0.1)], + "foobar", + ) + run( + "type after insertion", + [(b"__cycle f\t", 0.2), (b"b", 0.1), (b"\t", 0.2), (b"\x07", 0.1)], + "foobar", + ) + run( + "accept all after insertion", + [(b"__cycle f\t", 0.2), (b"\x19", 0.1), (b"\x07", 0.1)], + "foo foobar", + ) + run( + "navigate then accept", + [(b"__cycle f\t", 0.2), (b"\x1b[B", 0.1), (b"\r", 0.1), (b"\x07", 0.1)], + "foobar", + ) + run( + "hidden background completion", + [(b"__cycle f", 0.3), (b"\t", 0.15), (b"\t", 0.1), (b"\r", 0.1)], + "foobar", + inline=True, + ) + run( + "repeated Tab while loading", + [(b"__cycle f\t", 0.05), (b"\t", 0.5), (b"\r", 0.1)], + "foo", + delay=0.35, + request_count=1, + ) + run( + "Escape cancels pending insertion", + [(b"__cycle f\t", 0.05), (ESCAPE, 0.5), (b"\x07", 0.1)], + "f", + delay=0.35, + ) + run( + "typing cancels pending insertion", + [(b"__cycle f\t", 0.05), (b"b", 0.5), (b"\x07", 0.1)], + "fb", + delay=0.35, + ) + run( + "cursor movement cancels pending insertion", + [(b"__cycle f\t", 0.05), (b"\x1b[D", 0.5), (b"\x07", 0.1)], + "f", + delay=0.35, + ) + run( + "Escape retains inserted text", + [(b"__cycle f", 0.3), (b"\t", 0.2), (ESCAPE, 0.2), (b"\x07", 0.1)], + "foo", + automatic=True, + ) + + +if __name__ == "__main__": + main() From 3bf08798dc8ed07e8ca76321a6f511dfc9c54c95 Mon Sep 17 00:00:00 2001 From: Victor-Loos Date: Tue, 17 Nov 2026 11:00:10 +0100 Subject: [PATCH 2/2] feat: add inline previews for selected completions Replace opt-in cycle insertion with a default display-only completion preview, configurable with --preview. Emphasize matched input and share one mapping for cursor placement and mouse positions without editing the buffer during preview. Accept and submit the selected completion with one Enter press when previews are enabled. Disabling previews restores two-step Enter: accept, then submit. Keep Right/End acceptance aligned with the visible candidate and prevent hidden history suggestions from taking precedence. Preserve shared-prefix expansion and unique-match acceptance. Map Unicode case expansions back to original input and candidate coordinates. Traverse the ordered display mappings once during rendering. Cover Unicode, quotes, escaped filename spaces, mouse clicks, cancellation, selection stability and resizing. Document basic usage in the completion section. Validation: 1089 library tests passed (1 ignored), 28 Bash PTY scenarios passed, formatting and Clippy passed, release build and documentation completed. Documentation retains existing rustdoc warnings. --- README.md | 24 +- src/active_suggestions.rs | 386 ++++---------- src/app/actions/keyboard.rs | 41 +- src/app/completion_preview.rs | 853 ++++++++++++++++++++++++++++++ src/app/mod.rs | 34 +- src/app/ui.rs | 72 ++- src/cli.rs | 35 +- src/completions/tab_completion.rs | 40 +- src/settings.rs | 3 + tests/tab_cycle_pty.py | 201 +++++-- 10 files changed, 1216 insertions(+), 473 deletions(-) create mode 100644 src/app/completion_preview.rs diff --git a/README.md b/README.md index 8a5e4174..c94d8315 100644 --- a/README.md +++ b/README.md @@ -454,6 +454,18 @@ Flyline extends Bash's tab completion feature in many ways. Note that you will need to have [set up completions in normal Bash first](https://github.com/scop/bash-completion). +### Completion previews + +Selected completions appear in italics in the command line, with characters matching your input in bold. +Use Tab to browse, Enter to accept and run the command in one press, or Escape to dismiss the preview. + +Previews are enabled by default. Disable them to restore two-step Enter (accept, then run): + +```bash +flyline --preview false # disable +flyline --preview # enable +``` + ### Intellisense style auto suggestions Flyline can automatically start tab completion suggestions as you type. This demo shows auto-started suggestions, confirming a suggestion, dismissing with Escape, and submitting the command. @@ -803,18 +815,6 @@ If `tabCompletionAvailable` is false, then it will try the next keybinding for ` The `always` context variable is always true. For tab completion, `tabCompletionOneResult` is true when there is exactly one tab completion result. -The `tabCompletionCycleInsert` action writes the highlighted suggestion into the buffer instead of only highlighting it, and repeating it replaces that text with the next suggestion (`menu-complete` in other shells). -It is opt-in: without these bindings Tab keeps its default behavior. -Typing or moving the cursor ends the cycle; `tabCompletionInserted` lets Enter submit text already inserted. - -```bash -flyline key bind Tab 'editingBufferMode=tabCompletionCycleInsert' -flyline key bind Tab 'tabCompletionBackgroundActive=tabCompletionCycleInsert' -flyline key bind Tab 'tabCompletionWaiting=tabCompletionCycleInsert' -flyline key bind Tab 'tabCompletionAvailable=tabCompletionCycleInsert' -flyline key bind Enter 'tabCompletionInserted=submitOrNewline' -``` - Flyline provides useful tab completions to help you write keybindings. #### List keybindings diff --git a/src/active_suggestions.rs b/src/active_suggestions.rs index 5dc66d77..8ab0943c 100644 --- a/src/active_suggestions.rs +++ b/src/active_suggestions.rs @@ -1221,7 +1221,6 @@ mod description_tests { selected_coord: None, original_word_under_cursor: wuc.clone(), word_under_cursor: wuc, - inserted: None, last_num_rows_per_col: 0, last_num_visible_cols: 0, last_num_data_cols: 0, @@ -1858,35 +1857,6 @@ pub struct ColumnInfo { pub is_selected_col: bool, } -#[derive(Debug)] -pub(crate) struct CompletionBufferState { - contents: String, - cursor: usize, - selection: Option, -} - -impl CompletionBufferState { - pub fn new(buffer: &TextBuffer) -> Self { - Self { - contents: buffer.buffer().to_string(), - cursor: buffer.cursor_byte_pos(), - selection: buffer.selection_byte(), - } - } - - pub fn matches(&self, buffer: &TextBuffer) -> bool { - self.contents == buffer.buffer() - && self.cursor == buffer.cursor_byte_pos() - && self.selection == buffer.selection_byte() - } -} - -#[derive(Debug)] -struct InsertedSuggestion { - span: SubString, - state: CompletionBufferState, -} - #[derive(Debug)] pub struct ActiveSuggestions { /// Raw completions waiting to be post-processed. Drained from the front @@ -1902,8 +1872,6 @@ pub struct ActiveSuggestions { pub selected_coord: Option<(usize, usize)>, pub original_word_under_cursor: SubString, pub word_under_cursor: SubString, - /// The last cycle insertion, valid until the buffer or cursor changes. - inserted: Option, /// Number of suggestion rows per column as used in the last rendered /// grid. Kept in sync by [`update_grid_size`]. last_num_rows_per_col: usize, @@ -1967,7 +1935,6 @@ impl ActiveSuggestions { selected_coord: if auto_started { None } else { Some((0, 0)) }, original_word_under_cursor: word_under_cursor.clone(), word_under_cursor: word_under_cursor.clone(), - inserted: None, last_num_rows_per_col: 0, last_num_visible_cols: 0, last_num_data_cols: 0, @@ -2017,6 +1984,11 @@ impl ActiveSuggestions { } pub fn on_tab(&mut self, shift_tab: bool) { + // Hidden background completions have not rendered a grid yet. Give + // navigation a layout so the first Tab can select and preview an entry. + if self.last_num_rows_per_col == 0 { + self.update_grid_size(self.filtered_suggestions.len().max(1)); + } if shift_tab { self.on_up_arrow(); } else { @@ -2488,11 +2460,21 @@ impl ActiveSuggestions { }); } if sug.s.to_lowercase().starts_with(&pattern.to_lowercase()) { - let match_count = pattern.chars().count(); + // Lowercasing can expand a character (İ -> i + combining dot). + // Keep match indices in the original candidate's coordinates. + let match_count = pattern.to_lowercase().chars().count(); + let matching_indices = sug + .s + .chars() + .enumerate() + .flat_map(|(index, ch)| ch.to_lowercase().map(move |_| index)) + .take(match_count) + .dedup() + .collect(); return Some(FilteredItem { score: 1000, suggestion_idx: idx, - matching_indices: (0..match_count).collect(), + matching_indices, }); } return None; @@ -2517,81 +2499,29 @@ impl ActiveSuggestions { } pub fn update_word_under_cursor(&mut self, new_word_under_cursor: &SubString) { - self.inserted = None; self.word_under_cursor = new_word_under_cursor.clone(); self.update_fuzzy_filtered(); } - /// Whether completion should retain its original filter and replacement span. - /// An external edit or cursor movement ends the cycle, even if the inserted - /// substring itself happens to be unchanged. - pub fn insertion_is_current(&self, buffer: &TextBuffer) -> bool { - self.inserted - .as_ref() - .is_some_and(|inserted| inserted.state.matches(buffer)) - } - - pub fn has_insertion(&self) -> bool { - self.inserted.is_some() - } - - /// Enter may submit directly only while the highlighted candidate is the - /// one already in the buffer. Navigation can select a different candidate. - pub fn selected_is_inserted(&self, buffer: &TextBuffer) -> bool { - self.insertion_is_current(buffer) - && self.selected_suggestion().is_some_and(|suggestion| { - self.inserted - .as_ref() - .is_some_and(|inserted| suggestion.formatted() == inserted.span.s) - }) - } - - fn selected_suggestion(&self) -> Option<&ProcessedSuggestion> { - let index = self - .current_1d_index() - .or_else(|| (self.filtered_suggestions.len() == 1).then_some(0))?; - let item = self.filtered_suggestions.get(index)?; - self.processed_suggestions.get(item.suggestion_idx) - } - - fn replacement_span(&self, buffer: &TextBuffer) -> Option<&SubString> { - match &self.inserted { - Some(inserted) => inserted.state.matches(buffer).then_some(&inserted.span), - None => Some(&self.word_under_cursor), - } - } - - /// Promote background suggestions and cycle independently of grid layout, - /// which may not have been rendered yet when the first results arrive. - pub fn cycle_insert(&mut self, buffer: &mut TextBuffer) -> Option { - self.auto_started = false; - while self.filtered_suggestions.is_empty() && !self.unprocessed_suggestions.is_empty() { - self.process_chunk(); - self.update_fuzzy_filtered(); - } - let n = self.filtered_suggestions.len(); - if n == 0 { - return None; - } - if self.selected_coord.is_none() { - self.set_selected_by_idx(0); - } else if self.selected_is_inserted(buffer) { - self.set_selected_by_idx((self.current_1d_index()? + 1) % n); - } - self.insert_selected(buffer) + /// Selected candidate and its character match positions. Background menus + /// have no selection until the user explicitly chooses an entry. + pub fn selected_suggestion(&self) -> Option<(&ProcessedSuggestion, &[usize])> { + let item = self.filtered_suggestions.get(self.current_1d_index()?)?; + Some(( + self.processed_suggestions.get(item.suggestion_idx)?, + &item.matching_indices, + )) } /// Apply fuzzy search filtering to the suggestions based on the given pattern. fn update_fuzzy_filtered(&mut self) { let had_selection = self.selected_coord.is_some(); - // New processing chunks can change the sort order while cycling. - // Preserve the candidate's identity, not its previous filtered index. - // External edits clear `inserted` before updating the filter. - let selected_suggestion_idx = self.inserted.as_ref().and_then(|_| { - self.current_1d_index() - .and_then(|idx| self.filtered_suggestions.get(idx)) - .map(|item| item.suggestion_idx) - }); + // New chunks may reorder the results. Keep the selected candidate so + // the preview and the next acceptance do not unexpectedly change. + let selected_suggestion_idx = self + .current_1d_index() + .and_then(|idx| self.filtered_suggestions.get(idx)) + .map(|item| item.suggestion_idx); let raw_pattern = self.word_under_cursor.s.as_str(); log::debug!( "Applying fuzzy filter with raw_pattern {:?} on {} processed suggestions ({} still unprocessed)", @@ -2662,36 +2592,33 @@ impl ActiveSuggestions { } pub fn accept_selected_filtered_item(&mut self, buffer: &mut TextBuffer) { - let Some(suggestion) = self.selected_suggestion() else { + let selected_idx = if let Some(selected_idx) = self.current_1d_index() { + selected_idx + } else if self.filtered_suggestions.len() == 1 { + 0 + } else { log::warn!("No selected suggestion to accept"); return; }; - let Some(target) = self.replacement_span(buffer) else { + let Some(filtered_item) = self.filtered_suggestions.get(selected_idx) else { + log::warn!("No suggestion at selected index {}", selected_idx); return; }; - if let Err(e) = buffer.replace_word_under_cursor(&suggestion.formatted(), target) { - log::error!("Failed to apply suggestion: {}", e); - } - } - /// Replace the original word or the previous insertion with the selected - /// candidate and record the resulting buffer state for the next cycle. - fn insert_selected(&mut self, buffer: &mut TextBuffer) -> Option { - let text = self.selected_suggestion()?.formatted(); - let target = self.replacement_span(buffer)?; - match buffer.replace_word_under_cursor(&text, target) { - Ok(new_span) => { - self.inserted = Some(InsertedSuggestion { - span: new_span.clone(), - state: CompletionBufferState::new(buffer), - }); - Some(new_span) - } - Err(e) => { - log::warn!("Could not insert suggestion: {}", e); - None - } + let Some(suggestion) = self.processed_suggestions.get(filtered_item.suggestion_idx) else { + log::warn!( + "Suggestion index {} out of bounds (processed len={})", + filtered_item.suggestion_idx, + self.processed_suggestions.len() + ); + return; + }; + + if let Err(e) = + buffer.replace_word_under_cursor(&suggestion.formatted(), &self.word_under_cursor) + { + log::error!("Failed to apply suggestion: {}", e); } } @@ -2726,27 +2653,24 @@ impl ActiveSuggestions { joined.push_str(s); } - let Some(target) = self.replacement_span(buffer) else { - return; - }; - if let Err(e) = buffer.replace_word_under_cursor(&joined, target) { + if let Err(e) = buffer.replace_word_under_cursor(&joined, &self.word_under_cursor) { log::error!("Failed to apply all suggestions: {}", e); } } } #[cfg(test)] -mod cycle_tests { +mod preview_selection_tests { use super::*; - fn suggestions(buffer: &TextBuffer, start: usize, values: &[&str]) -> ActiveSuggestions { + fn suggestions() -> ActiveSuggestions { ActiveSuggestions::new( ActiveSuggestionsBuilder::from_processed( - values.iter().map(|s| ProcessedSuggestion::new(*s, "", "")), + ["far", "foo", "fzz"].map(|s| ProcessedSuggestion::new(s, "", "")), ), SubString { - start, - s: buffer.buffer()[start..].to_string(), + start: 4, + s: "f".into(), }, std::time::Duration::ZERO, false, @@ -2756,173 +2680,67 @@ mod cycle_tests { } #[test] - fn cycles_and_wraps_before_first_render() { - let mut buffer = TextBuffer::new("cmd f"); - let mut active = suggestions(&buffer, 4, &["far ", "foo "]); - for expected in ["cmd far ", "cmd foo ", "cmd far "] { - active.cycle_insert(&mut buffer).unwrap(); - assert_eq!(buffer.buffer(), expected); - assert!(active.selected_is_inserted(&buffer)); - assert_eq!(active.filtered_suggestions_len(), 2); - } - } - - #[test] - fn cycles_across_rendered_columns() { - let mut buffer = TextBuffer::new("cmd f"); - let mut active = suggestions(&buffer, 4, &["faa", "fbb", "fcc", "fdd", "fee"]); - for value in ["faa", "fbb", "fcc", "fdd", "fee", "faa"] { - active.into_grid(2, 80, &Palette::default(), None); - active.cycle_insert(&mut buffer).unwrap(); - assert_eq!(buffer.buffer(), format!("cmd {value}")); - } - } - - #[test] - fn resizing_preserves_the_inserted_candidate_and_cycle_order() { + fn navigation_and_resize_keep_preview_and_acceptance_in_sync() { + let mut active = suggestions(); let mut buffer = TextBuffer::new("cmd f"); - let mut active = suggestions(&buffer, 4, &["faa", "fbb", "fcc", "fdd", "fee"]); active.into_grid(2, 80, &Palette::default(), None); - for _ in 0..4 { - active.cycle_insert(&mut buffer).unwrap(); - } - assert_eq!(buffer.buffer(), "cmd fdd"); + active.on_tab(false); + assert_eq!(active.selected_suggestion().unwrap().0.s, "foo"); for rows in [1, 3, 2] { active.into_list(2, &Palette::default()); - assert!(active.selected_is_inserted(&buffer)); active.into_grid(rows, 40, &Palette::default(), None); - assert!(active.selected_is_inserted(&buffer)); - assert_eq!(active.current_1d_index(), Some(3)); + assert_eq!(active.selected_suggestion().unwrap().0.s, "foo"); } - active.cycle_insert(&mut buffer).unwrap(); - assert_eq!(buffer.buffer(), "cmd fee"); - } - - #[test] - fn new_results_preserve_the_highlighted_candidate_during_a_cycle() { - let mut buffer = TextBuffer::new("cmd f"); - let mut active = suggestions(&buffer, 4, &["foo", "fzz"]); - active.cycle_insert(&mut buffer).unwrap(); - // A later chunk inserts an entry before the selected candidate. - active - .unprocessed_suggestions - .push_back(UnprocessedSuggestion { - raw_text: "far".into(), - full_path: None, - flags: shell::CompletionFlags { - no_suffix_desired: true, - ..Default::default() - }, - word_under_cursor: "f".into(), - is_git_command: false, - custom_prefix: None, - }); - active.into_grid(2, 80, &Palette::default(), None); - assert!(active.selected_is_inserted(&buffer)); - assert_eq!(active.current_1d_index(), Some(1)); - // Also preserve a candidate highlighted by navigation, before insertion. - active.set_selected_by_idx(2); - active.update_fuzzy_filtered(); - assert_eq!(active.selected_suggestion().unwrap().s, "fzz"); - active.cycle_insert(&mut buffer).unwrap(); - assert_eq!(buffer.buffer(), "cmd fzz"); - } - - #[test] - fn promotes_background_suggestions_without_a_grid() { - let mut buffer = TextBuffer::new("cmd f"); - let mut active = suggestions(&buffer, 4, &["far", "foo"]); - active.auto_started = true; - active.selected_coord = None; - active.cycle_insert(&mut buffer).unwrap(); - assert_eq!(buffer.buffer(), "cmd far"); - assert!(!active.auto_started); - } - - #[test] - fn navigation_accepts_highlighted_candidate_without_skipping_it() { - let mut buffer = TextBuffer::new("cmd f"); - let mut active = suggestions(&buffer, 4, &["far", "foo", "fzz"]); - active.cycle_insert(&mut buffer).unwrap(); - active.set_selected_by_idx(1); - assert!(!active.selected_is_inserted(&buffer)); - active.cycle_insert(&mut buffer).unwrap(); - assert_eq!(buffer.buffer(), "cmd foo"); - active.set_selected_by_idx(2); - assert!(!active.selected_is_inserted(&buffer)); - active.accept_selected_filtered_item(&mut buffer); - assert_eq!(buffer.buffer(), "cmd fzz"); - } - - #[test] - fn accept_all_replaces_entire_inserted_text() { - let mut buffer = TextBuffer::new("cmd f"); - let mut active = suggestions(&buffer, 4, &["far", "foo"]); - active.cycle_insert(&mut buffer).unwrap(); - active.accept_all_filtered_items(&mut buffer); - assert_eq!(buffer.buffer(), "cmd far foo"); - } - - #[test] - fn typing_invalidates_insertion_and_refinement_uses_the_new_word() { - let mut buffer = TextBuffer::new("cmd foo"); - let mut active = suggestions(&buffer, 4, &["foo", "foobar"]); - active.cycle_insert(&mut buffer).unwrap(); - buffer.insert_str("b"); - assert!(!active.insertion_is_current(&buffer)); - assert!(!active.selected_is_inserted(&buffer)); - assert!(active.cycle_insert(&mut buffer).is_none()); - assert_eq!(buffer.buffer(), "cmd foob"); - active.update_word_under_cursor(&SubString { - start: 4, - s: "foob".into(), - }); - active.cycle_insert(&mut buffer).unwrap(); - assert_eq!(buffer.buffer(), "cmd foobar"); - } - - #[test] - fn cursor_movement_and_edits_outside_the_span_end_insertion() { - let mut buffer = TextBuffer::new("cmd f"); - let mut active = suggestions(&buffer, 4, &["far", "foo"]); - active.cycle_insert(&mut buffer).unwrap(); - buffer.move_left(); - assert!(!active.insertion_is_current(&buffer)); - active.accept_all_filtered_items(&mut buffer); - assert_eq!(buffer.buffer(), "cmd far"); - buffer.replace_buffer("new far"); - assert!(!active.insertion_is_current(&buffer)); + assert_eq!(buffer.buffer(), "cmd f"); active.accept_selected_filtered_item(&mut buffer); - assert_eq!(buffer.buffer(), "new far"); + assert_eq!(buffer.buffer(), "cmd foo"); + buffer.undo(); + assert_eq!(buffer.buffer(), "cmd f"); } #[test] - fn quoted_unicode_candidates_replace_the_complete_byte_span() { - let mut buffer = TextBuffer::new("cmd \"é"); - let mut active = suggestions(&buffer, 4, &["\"été un\" ", "\"été deux\" "]); - active.cycle_insert(&mut buffer).unwrap(); - active.cycle_insert(&mut buffer).unwrap(); - assert_eq!(buffer.buffer(), "cmd \"été un\" "); + fn selected_preview_reuses_the_filtered_candidates_unicode_matches() { + let active = ActiveSuggestions::new( + ActiveSuggestionsBuilder::from_processed([ProcessedSuggestion::new( + "été", "rép/", " ", + )]), + SubString { + start: 4, + s: "rép/ét".into(), + }, + std::time::Duration::ZERO, + false, + crate::settings::SuggestionSortOrder::Alphabetical, + crate::settings::FuzzyMode::None, + ); + let (suggestion, matches) = active.selected_suggestion().unwrap(); + assert_eq!(suggestion.formatted(), "rép/été "); + assert_eq!(matches, &[0, 1]); } #[test] - fn undo_restores_the_previous_candidate_and_invalidates_insertion() { - let mut buffer = TextBuffer::new("cmd f"); - let mut active = suggestions(&buffer, 4, &["far", "foo"]); - active.cycle_insert(&mut buffer).unwrap(); - active.cycle_insert(&mut buffer).unwrap(); - buffer.undo(); - assert_eq!(buffer.buffer(), "cmd far"); - assert!(!active.insertion_is_current(&buffer)); + fn later_results_preserve_selected_candidate() { + let mut active = suggestions(); + active.set_selected_by_idx(1); + active + .processed_suggestions + .push(ProcessedSuggestion::new("faa", "", "")); + active.update_fuzzy_filtered(); + assert_eq!(active.selected_suggestion().unwrap().0.s, "foo"); + assert_eq!(active.current_1d_index(), Some(2)); } #[test] - fn empty_results_leave_the_buffer_unchanged() { - let mut buffer = TextBuffer::new("cmd f"); - let mut active = suggestions(&buffer, 4, &[]); - assert!(active.cycle_insert(&mut buffer).is_none()); - assert!(!active.has_insertion()); - assert_eq!(buffer.buffer(), "cmd f"); + fn background_suggestions_need_an_explicit_selection() { + let mut active = suggestions(); + active.auto_started = true; + active.selected_coord = None; + active.update_fuzzy_filtered(); + assert!(active.selected_suggestion().is_none()); + active.on_tab(false); + assert_eq!(active.selected_suggestion().unwrap().0.s, "far"); + active.on_tab(false); + assert_eq!(active.selected_suggestion().unwrap().0.s, "foo"); } } diff --git a/src/app/actions/keyboard.rs b/src/app/actions/keyboard.rs index ff85d80e..7472a775 100644 --- a/src/app/actions/keyboard.rs +++ b/src/app/actions/keyboard.rs @@ -78,10 +78,6 @@ pub enum KeyEventAction { TabCompletionPrevSuggestion, #[strum(message = "Move to the next tab completion suggestion")] TabCompletionNextSuggestion, - #[strum( - message = "Write the selected suggestion into the buffer, replacing the one written by the previous press" - )] - TabCompletionCycleInsert, #[strum(message = "Promote background tab completion to user-visible completion")] TabCompletionPromote, #[strum(message = "Scroll up through fuzzy history search results")] @@ -496,13 +492,12 @@ impl KeyEventAction { ContentMode::TabCompletion(suggestions) => Some(suggestions), _ => None, }; - app.start_tab_complete(false, previous_suggestions, false); + app.start_tab_complete(false, previous_suggestions); } else if let ContentMode::TabCompletion(active_suggestions) = &mut app.content_mode { active_suggestions.on_tab(false); } } - KeyEventAction::TabCompletionCycleInsert => app.cycle_insert_tab_completion(), KeyEventAction::FuzzyHistorySelectPrev => { let source = match &app.content_mode { ContentMode::FuzzyHistorySearch(s) => *s, @@ -652,7 +647,7 @@ impl KeyEventAction { } _ => {} }, - KeyEventAction::RunTabCompletion => app.start_tab_complete(false, None, false), + KeyEventAction::RunTabCompletion => app.start_tab_complete(false, None), KeyEventAction::RunFlycomp => app.force_start_flycomp(), KeyEventAction::ToggleMouse => { if matches!( @@ -1102,9 +1097,9 @@ impl KeyEventAction { // Capture the word-under-cursor when dismissing tab completion, so we don't // auto-suggest on the same word the user just dismissed. match &app.content_mode { - ContentMode::TabCompletion(_) => { + ContentMode::TabCompletion(active_suggestions) => { app.dismissed_tab_completion_wuc = - Some(app.get_completion_context().word_under_cursor.s.clone()); + Some(active_suggestions.word_under_cursor.s.to_string()); } ContentMode::TabCompletionWaiting { wuc_substring, .. } => { app.dismissed_tab_completion_wuc = Some(wuc_substring.s.to_string()); @@ -2476,6 +2471,14 @@ pub static DEFAULT_BINDINGS: LazyLock> = LazyLock::new(|| { ContextVar::TabCompletionAvailable.into(), &[KeyEventAction::TabCompletionAcceptAll], ), + Binding::new( + &expand_variations![KC::Enter.into()], + ContextVar::TabCompletionPreviewAvailable.into(), + &[ + KeyEventAction::TabCompletionAcceptEntry, + KeyEventAction::SubmitOrNewline, + ], + ), Binding::new( &expand_variations![KC::Enter.into()], ContextVar::TabCompletionEntrySelected.into(), @@ -2874,6 +2877,13 @@ pub static DEFAULT_BINDINGS: LazyLock> = LazyLock::new(|| { ContextVar::Always.into(), &[KeyEventAction::MoveLeft], ), + Binding::new( + &expand_variations![KC::Right.into(), KC::End.into()], + ContextVar::TabCompletionPreviewAvailable + + ContextVar::CursorAtEnd + + !ContextVar::TabCompletionMultiColAvailable, + &[KeyEventAction::TabCompletionAcceptEntry], + ), Binding::new( &expand_variations![KC::Right.into(), KC::End.into()], ContextVar::InlineSuggestionAvailable @@ -4656,10 +4666,10 @@ pub(crate) enum ContextVar { TabCompletionAvailable, #[strum(message = "Tab completion overlay has at least one candidate and a selected entry")] TabCompletionEntrySelected, + #[strum(message = "The selected completion is previewed in the command line")] + TabCompletionPreviewAvailable, #[strum(message = "Tab completion overlay is active and has exactly one filtered candidate")] TabCompletionOneResult, - #[strum(message = "The selected tab completion suggestion is already written into the buffer")] - TabCompletionInserted, #[strum(message = "Tab completion overlay is showing more than one column of candidates")] TabCompletionMultiColAvailable, #[strum(message = "Tab completion overlay is active but fuzzy filtering has no matches")] @@ -4773,10 +4783,6 @@ impl ContextVar { &app.content_mode, ContentMode::TabCompletion(active) if active.filtered_suggestions_len() == 1 ), - ContextVar::TabCompletionInserted => matches!( - &app.content_mode, - ContentMode::TabCompletion(active) if active.selected_is_inserted(&app.buffer) - ), ContextVar::TabCompletionMultiColAvailable => matches!( &app.content_mode, ContentMode::TabCompletion(active) @@ -4813,7 +4819,10 @@ impl ContextVar { ContextVar::AgentModeError => { matches!(app.content_mode, ContentMode::AgentError { .. }) } - ContextVar::InlineSuggestionAvailable => app.inline_history_suggestion.is_some(), + ContextVar::TabCompletionPreviewAvailable => app.completion_preview().is_some(), + ContextVar::InlineSuggestionAvailable => { + app.inline_history_suggestion.is_some() && app.completion_preview().is_none() + } ContextVar::CursorAtEnd => app.buffer.is_cursor_at_end(), ContextVar::CursorAtEndTrimmed => app.buffer.is_cursor_at_trimmed_end(), ContextVar::CursorAtStart => app.buffer.is_cursor_at_start(), diff --git a/src/app/completion_preview.rs b/src/app/completion_preview.rs new file mode 100644 index 00000000..9890efca --- /dev/null +++ b/src/app/completion_preview.rs @@ -0,0 +1,853 @@ +//! Display-only projection of a selected completion onto the command buffer. + +use super::formatted_buffer::FormattedBuffer; +use super::{App, ContentMode}; +use crate::active_suggestions::ProcessedSuggestion; +use crate::content::Tag; +use crate::grammar::TokenKind; +use ratatui::prelude::*; +use std::ops::Range; +use unicode_segmentation::UnicodeSegmentation; + +/// One span of real input and its corresponding span in the displayed candidate. +/// The same mapping drives emphasis, cursor placement and mouse hit-testing. +struct SourceMapping { + source: Range, + display: Range, +} + +pub(super) struct CompletionPreview { + range: Range, + text: String, + cursor: usize, + cursor_in_preview: usize, + mapping: Vec, +} + +impl App<'_> { + /// Shared by rendering and key contexts so hidden history suggestions can + /// never override the completion currently shown in the command line. + pub(super) fn completion_preview(&self) -> Option { + if !self.mode.is_running() || !crate::settings().preview { + return None; + } + let ContentMode::TabCompletion(active) = &self.content_mode else { + return None; + }; + let (suggestion, matches) = active.selected_suggestion()?; + CompletionPreview::new(&self.buffer, &active.word_under_cursor, suggestion, matches) + } +} + +impl CompletionPreview { + pub(super) fn new( + buffer: &flybuffer::TextBuffer, + target: &flybuffer::SubString, + suggestion: &ProcessedSuggestion, + matching_indices: &[usize], + ) -> Option { + let text = suggestion.formatted(); + let end = target.start.checked_add(target.s.len())?; + let cursor = buffer.cursor_byte_pos(); + if buffer.selection_byte().is_some() + || !(target.start..=end).contains(&cursor) + || buffer.buffer().get(target.start..end)? != target.s + || text.is_empty() + { + return None; + } + let prefix_len = if target.s.starts_with(&suggestion.prefix) { + suggestion.prefix.len() + } else { + 0 + }; + // Preserve only a real closing quote, never a separator space which + // may instead be an escaped character belonging to the filename. + let closing_quote = suggestion + .suffix + .chars() + .next() + .filter(|q| matches!(q, '\'' | '"')) + .filter(|q| { + target.s.starts_with(*q) + && target.s.ends_with(*q) + && target.s.len() > prefix_len + && target.s.len() > 1 + }); + let body_end = target.s.len() - closing_quote.map_or(0, char::len_utf8); + let display_body: Vec<_> = suggestion.s.char_indices().collect(); + // Align case-insensitive prefixes in lowercase coordinates: one input + // character may correspond to several candidate characters or vice versa. + let expand_case = !matching_indices.is_empty() + && matching_indices + .iter() + .copied() + .eq(0..matching_indices.len()) + && suggestion + .s + .to_lowercase() + .starts_with(&target.s[prefix_len..body_end].to_lowercase()); + let mut matches = matching_indices + .iter() + .filter_map(|&index| display_body.get(index)) + .flat_map(|&(byte, ch)| { + std::iter::repeat_n( + (byte, ch), + if expand_case { + ch.to_lowercase().count() + } else { + 1 + }, + ) + }); + // With no match metadata (e.g. globs), map only a shared literal prefix. + let literal_end = if matching_indices.is_empty() { + target + .s + .chars() + .zip(text.chars()) + .take_while(|(a, b)| a == b) + .map(|(ch, _)| ch.len_utf8()) + .sum() + } else { + 0 + }; + let mapping: Vec<_> = target + .s + .char_indices() + .flat_map(|(source, ch)| { + std::iter::repeat_n( + (source, ch), + if expand_case && (prefix_len..body_end).contains(&source) { + ch.to_lowercase().count() + } else { + 1 + }, + ) + }) + .filter_map(|(source, ch)| { + let displayed = if source < prefix_len { + Some((source, ch)) + } else if closing_quote.is_some() && source == body_end { + Some((suggestion.prefix.len() + suggestion.s.len(), ch)) + } else if matching_indices.is_empty() { + (source < literal_end).then_some((source, ch)) + } else { + matches + .next() + .map(|(byte, matched)| (suggestion.prefix.len() + byte, matched)) + }?; + Some(SourceMapping { + source: source..source + ch.len_utf8(), + display: displayed.0..displayed.0 + displayed.1.len_utf8(), + }) + }) + .collect(); + let mapped_cursor = mapping + .iter() + .rev() + .find(|entry| entry.source.end <= cursor - target.start) + .map_or(0, |entry| entry.display.end); + // Keep the cursor outside combining-character/emoji graphemes. + let cursor_in_preview = if mapped_cursor == 0 { + 0 + } else { + text.grapheme_indices(true) + .map(|(byte, graph)| byte + graph.len()) + .find(|end| *end >= mapped_cursor) + .unwrap_or(text.len()) + }; + Some(Self { + range: target.start..end, + text, + cursor, + cursor_in_preview, + mapping, + }) + } +} + +pub(super) struct DrawableBufferSpan { + pub span: Span<'static>, + pub tags: Vec, + pub is_cursor: bool, + pub is_in_selection: bool, + pub newline: bool, +} + +impl FormattedBuffer { + /// Splice a preview into the rendered spans, leaving text, undo history, + /// syntax tokens and mouse offsets in the editor's real buffer untouched. + pub(super) fn drawable_spans( + &self, + animation_time: Option, + selection_range: Option>, + preview: Option<&CompletionPreview>, + preview_style: Style, + matched_style: Style, + ) -> Vec { + let mut out = Vec::new(); + let mut inserted = false; + let mut cursor_after_preview = false; + for part in &self.parts { + for (span, tags, is_cursor, _, is_in_selection) in + part.get_spans(animation_time, selection_range.clone()) + { + let Some(preview) = preview else { + out.push(DrawableBufferSpan { + span, + tags, + is_cursor, + is_in_selection, + newline: part.token.token.kind == TokenKind::Newline, + }); + continue; + }; + // Splitting at grapheme boundaries also handles targets spanning + // several syntax tokens (quotes, escapes and fuzzy matches). + for (graph, tag) in span.content.graphemes(true).zip(tags) { + let Tag::Command(byte) = tag else { continue }; + if !inserted && byte >= preview.range.start { + cursor_after_preview = + Self::push_preview(&mut out, preview, preview_style, matched_style); + inserted = true; + } + if preview.range.contains(&byte) { + continue; + } + out.push(DrawableBufferSpan { + span: Span::styled(graph.to_owned(), span.style), + tags: vec![tag], + is_cursor: std::mem::take(&mut cursor_after_preview), + is_in_selection, + newline: part.token.token.kind == TokenKind::Newline, + }); + } + } + } + if let Some(preview) = preview + && !inserted + { + cursor_after_preview = + Self::push_preview(&mut out, preview, preview_style, matched_style); + } + if cursor_after_preview { + out.push(Self::cursor_marker()); + } + out + } + + fn push_preview( + out: &mut Vec, + preview: &CompletionPreview, + style: Style, + matched_style: Style, + ) -> bool { + let mut mapping = preview.mapping.iter().peekable(); + for (byte, graph) in preview.text.grapheme_indices(true) { + while mapping + .peek() + .is_some_and(|entry| entry.display.end <= byte) + { + mapping.next(); + } + let source = mapping + .peek() + .filter(|entry| entry.display.start < byte + graph.len()) + .map(|entry| preview.range.start + entry.source.start); + let is_match = source.is_some(); + let is_cursor = byte == preview.cursor_in_preview; + if is_cursor && !is_match { + // Anchor before ghost text wraps: a wide suggested glyph must + // not move the real insertion point to the next terminal row. + out.push(Self::cursor_marker()); + } + let style = if is_match { + matched_style + .remove_modifier(Modifier::DIM) + .add_modifier(Modifier::BOLD | Modifier::ITALIC) + } else { + style.add_modifier(Modifier::ITALIC) + }; + let newline = graph == "\n" || graph == "\r\n"; + out.push(DrawableBufferSpan { + span: Span::styled(if newline { " " } else { graph }.to_owned(), style), + tags: vec![Tag::Command(source.unwrap_or(preview.cursor))], + is_cursor: is_cursor && is_match, + is_in_selection: false, + newline, + }); + } + // At the candidate's end, let the following real grapheme position the + // cursor (and wrap if needed). Only end-of-buffer needs a blank marker. + preview.cursor_in_preview == preview.text.len() + } + + fn cursor_marker() -> DrawableBufferSpan { + DrawableBufferSpan { + span: Span::raw(""), + tags: vec![], + is_cursor: true, + is_in_selection: false, + newline: false, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::active_suggestions::ProcessedSuggestion; + use crate::palette::Palette; + use flybuffer::{SubString, TextBuffer}; + use ratatui::text::StyledGrapheme; + + fn render(input: &str, target: &str, replacement: &str) -> Vec { + render_matched( + input, + target, + &ProcessedSuggestion::new(replacement, "", ""), + &[], + &Palette::dark(), + ) + } + + fn render_matched( + input: &str, + target: &str, + suggestion: &ProcessedSuggestion, + matches: &[usize], + palette: &Palette, + ) -> Vec { + render_at(input, target, suggestion, matches, palette, target.len()) + } + + fn render_at( + input: &str, + target: &str, + suggestion: &ProcessedSuggestion, + matches: &[usize], + palette: &Palette, + cursor_in_word: usize, + ) -> Vec { + let start = input.find(target).unwrap(); + let mut buffer = TextBuffer::new(input); + buffer.try_move_cursor_to_byte_pos(start + cursor_in_word, true); + let preview = CompletionPreview::new( + &buffer, + &SubString { + start, + s: target.into(), + }, + suggestion, + matches, + ) + .unwrap(); + FormattedBuffer::from(input, buffer.cursor_byte_pos(), None).drawable_spans( + None, + None, + Some(&preview), + palette.inline_suggestion(), + palette.normal_text(), + ) + } + + fn before_cursor(spans: &[DrawableBufferSpan]) -> String { + assert_eq!(spans.iter().filter(|span| span.is_cursor).count(), 1); + let index = spans.iter().position(|span| span.is_cursor).unwrap(); + text(&spans[..index]) + } + + fn layout(spans: Vec, width: u16) -> (crate::content::Coord, Vec) { + let mut content = crate::content::Contents::new(width); + let mut cursor = None; + for span in spans { + if span.is_cursor { + let graph = span + .span + .styled_graphemes(span.span.style) + .next() + .unwrap_or_else(|| StyledGrapheme::new(" ", Style::default())); + content.move_to_next_insertion_point(&graph, false, None); + assert!(cursor.replace(content.cursor_position()).is_none()); + } + content.write_tagged_span_dont_overwrite(&crate::content::TaggedSpan::per_grapheme( + span.span, span.tags, + )); + if span.newline { + content.newline(); + content.write_tagged_span(&crate::content::TaggedSpan::new( + Span::raw("> "), + Tag::Prompt, + )); + } + } + (cursor.unwrap(), content.get_buffer_lines()) + } + + #[test] + fn preview_cursor_follows_source_position_and_fuzzy_match_indices() { + for (input, candidate, matches, cursor, expected) in [ + ("f", "far", vec![0], 1, "f"), + ("fb", "foo_bar", vec![0, 4], 2, "foo_b"), + ("fb", "foo_bar", vec![0, 4], 1, "f"), + ("fo", "foo", vec![0, 1], 1, "f"), + ("fo", "foo", vec![0, 1], 0, ""), + ("FO", "foo", vec![0, 1], 2, "fo"), + ("f", "f/f", vec![2], 1, "f/f"), + ("e", "e\u{301}clair", vec![0], 1, "e\u{301}"), + ("é", "été", vec![0], "é".len(), "é"), + ("f*", "far", vec![], 2, "f"), + ] { + let spans = render_at( + &format!("cmd {input} tail"), + input, + &ProcessedSuggestion::new(candidate, "", " "), + &matches, + &Palette::dark(), + cursor, + ); + assert_eq!( + before_cursor(&spans), + format!("cmd {expected}"), + "input {input:?}, cursor {cursor}" + ); + assert_eq!(text(&spans), format!("cmd {candidate} tail")); + } + } + + #[test] + fn cursor_maps_preserved_paths_and_both_sides_of_a_closing_quote() { + let path = render_matched( + "cmd rép/é", + "rép/é", + &ProcessedSuggestion::new("été", "rép/", " "), + &[0], + &Palette::dark(), + ); + assert_eq!(before_cursor(&path), "cmd rép/é"); + let suggestion = ProcessedSuggestion::new("été", "\"", "\""); + for (cursor, expected) in [("\"é".len(), "cmd \"é"), ("\"é\"".len(), "cmd \"été\"")] { + let spans = render_at( + "cmd \"é\" tail", + "\"é\"", + &suggestion, + &[0], + &Palette::dark(), + cursor, + ); + assert_eq!(before_cursor(&spans), expected); + } + } + + #[test] + fn cursor_stays_at_the_start_of_an_empty_word() { + let buffer = TextBuffer::new("cmd "); + let preview = CompletionPreview::new( + &buffer, + &SubString { + start: 4, + s: String::new(), + }, + &ProcessedSuggestion::new("far", "", ""), + &[], + ) + .unwrap(); + let spans = FormattedBuffer::from("cmd ", 4, None).drawable_spans( + None, + None, + Some(&preview), + Style::default(), + Style::default(), + ); + assert_eq!(before_cursor(&spans), "cmd "); + assert_eq!(text(&spans), "cmd far"); + } + + #[test] + fn cursor_coordinates_follow_input_when_preview_wraps_or_contains_newlines() { + let spans = || { + render_matched( + "cmd f", + "f", + &ProcessedSuggestion::new("far", "", ""), + &[0], + &Palette::dark(), + ) + }; + assert_eq!(layout(spans(), 20).0, crate::content::Coord::new(0, 5)); + assert_eq!(layout(spans(), 5).0, crate::content::Coord::new(1, 0)); + + let wide_ghost = render_matched( + "cmd f", + "f", + &ProcessedSuggestion::new("f界", "", ""), + &[0], + &Palette::dark(), + ); + let (cursor, lines) = layout(wide_ghost, 6); + assert_eq!(cursor, crate::content::Coord::new(0, 5)); + assert!(lines[1].starts_with("界")); + + // A real wide character following the replaced word behaves like a + // normal editor cursor, rather than the virtual ghost-text boundary. + let wide_suffix = render_matched( + "cmd f界", + "f", + &ProcessedSuggestion::new("f", "", ""), + &[0], + &Palette::dark(), + ); + assert_eq!(layout(wide_suffix, 6).0, crate::content::Coord::new(1, 0)); + + let multiline = render_matched( + "cmd fb\ntail", + "fb", + &ProcessedSuggestion::new("foo\nbar", "", ""), + &[0, 4], + &Palette::dark(), + ); + assert_eq!(text(&multiline), "cmd foo\nbar\ntail"); + assert_eq!(multiline.iter().filter(|span| span.newline).count(), 2); + assert_eq!(layout(multiline, 20).0, crate::content::Coord::new(1, 3)); + } + + fn emphasized_text(spans: &[DrawableBufferSpan]) -> String { + spans + .iter() + .filter(|s| { + s.span + .style + .add_modifier + .contains(Modifier::BOLD | Modifier::ITALIC) + }) + .map(|s| s.span.content.as_ref()) + .collect() + } + + #[test] + fn typed_prefix_has_normal_contrast_and_generated_text_keeps_preview_style() { + for palette in [Palette::dark(), Palette::light()] { + let spans = render_matched( + "cmd fo", + "fo", + &ProcessedSuggestion::new("foo", "", " "), + &[0, 1], + &palette, + ); + assert_eq!(text(&spans), "cmd foo "); + assert_eq!(emphasized_text(&spans), "fo"); + for span in spans + .iter() + .filter(|s| s.span.style.add_modifier.contains(Modifier::ITALIC)) + { + let expected = if span.span.style.add_modifier.contains(Modifier::BOLD) { + palette + .normal_text() + .remove_modifier(Modifier::DIM) + .add_modifier(Modifier::BOLD | Modifier::ITALIC) + } else { + palette.inline_suggestion().add_modifier(Modifier::ITALIC) + }; + assert_eq!(span.span.style, expected); + } + } + } + + #[test] + fn fuzzy_match_highlights_typed_letters_at_their_actual_positions() { + let spans = render_matched( + "cmd fb", + "fb", + &ProcessedSuggestion::new("foo_bar", "", " "), + &[0, 4], + &Palette::dark(), + ); + assert_eq!(text(&spans), "cmd foo_bar "); + assert_eq!(emphasized_text(&spans), "fb"); + } + + #[test] + fn mouse_positions_share_the_same_unicode_mapping_as_emphasis() { + let spans = render_matched( + "cmd rép/é", + "rép/é", + &ProcessedSuggestion::new("été", "rép/", " "), + &[0], + &Palette::dark(), + ); + let typed: Vec<_> = spans + .iter() + .filter(|span| { + span.span + .style + .add_modifier + .contains(Modifier::BOLD | Modifier::ITALIC) + }) + .map(|span| (span.span.content.as_ref(), span.tags[0])) + .collect(); + assert_eq!( + typed, + vec![ + ("r", Tag::Command(4)), + ("é", Tag::Command(5)), + ("p", Tag::Command(7)), + ("/", Tag::Command(8)), + ("é", Tag::Command(9)) + ] + ); + assert_eq!(before_cursor(&spans), "cmd rép/é"); + assert_eq!(text(&spans), "cmd rép/été "); + assert_eq!(emphasized_text(&spans), "rép/é"); + } + + #[test] + fn case_expanding_prefixes_preserve_emphasis_cursor_and_mouse_positions() { + use crate::active_suggestions::{ActiveSuggestions, ActiveSuggestionsBuilder}; + + for (input, candidate, matches, typed) in [ + ("i\u{307}", "İabc", vec![0], vec![("İ", Tag::Command(4))]), + ( + "İ", + "i\u{307}xyz", + vec![0, 1], + vec![("i\u{307}", Tag::Command(4))], + ), + ( + "İi\u{307}", + "i\u{307}İabc", + vec![0, 1, 2], + vec![("i\u{307}", Tag::Command(4)), ("İ", Tag::Command(6))], + ), + ] { + let active = ActiveSuggestions::new( + ActiveSuggestionsBuilder::from_processed([ProcessedSuggestion::new( + candidate, "", "", + )]), + SubString { + start: 4, + s: input.into(), + }, + std::time::Duration::ZERO, + false, + crate::settings::SuggestionSortOrder::Alphabetical, + crate::settings::FuzzyMode::None, + ); + let (suggestion, actual_matches) = active.selected_suggestion().unwrap(); + assert_eq!( + actual_matches, matches, + "input {input:?}, candidate {candidate:?}" + ); + let spans = render_matched( + &format!("cmd {input}"), + input, + suggestion, + actual_matches, + &Palette::dark(), + ); + let actual_typed: Vec<_> = spans + .iter() + .filter(|span| span.span.style.add_modifier.contains(Modifier::BOLD)) + .map(|span| (span.span.content.as_ref(), span.tags[0])) + .collect(); + assert_eq!(actual_typed, typed); + assert_eq!( + before_cursor(&spans), + format!("cmd {}", emphasized_text(&spans)) + ); + assert_eq!(text(&spans), format!("cmd {candidate}")); + } + } + + #[test] + fn escaped_space_is_input_not_a_generated_separator() { + let spans = render_matched( + "cmd foo\\ ", + "foo\\ ", + &ProcessedSuggestion::new("foo\\ one", "", " "), + &[0, 1, 2, 3, 4], + &Palette::dark(), + ); + assert_eq!(text(&spans), "cmd foo\\ one "); + assert_eq!(before_cursor(&spans), "cmd foo\\ "); + assert_eq!(emphasized_text(&spans), "foo\\ "); + assert!( + !spans + .last() + .unwrap() + .span + .style + .add_modifier + .contains(Modifier::BOLD) + ); + let (cursor, _) = layout(spans, 30); + assert_eq!(cursor, crate::content::Coord::new(0, 9)); + } + + #[test] + fn matched_combining_character_styles_the_entire_grapheme() { + let spans = render_matched( + "cmd e", + "e", + &ProcessedSuggestion::new("e\u{301}clair", "", ""), + &[0], + &Palette::dark(), + ); + assert_eq!(emphasized_text(&spans), "e\u{301}"); + let first = spans.iter().find(|s| s.span.content == "e\u{301}").unwrap(); + assert_eq!(first.tags, vec![Tag::Command(4)]); + } + + #[test] + fn preserves_typed_quotes_and_escaped_fuzzy_matches() { + let quoted = render_matched( + "cmd \"é\"", + "\"é\"", + &ProcessedSuggestion::new("été", "\"", "\""), + &[0], + &Palette::dark(), + ); + assert_eq!(text("ed), "cmd \"été\""); + assert_eq!(emphasized_text("ed), "\"é\""); + let escaped = render_matched( + "cmd fb", + "fb", + &ProcessedSuggestion::new("foo\\ bar", "", " "), + &[0, 5], + &Palette::dark(), + ); + assert_eq!(text(&escaped), "cmd foo\\ bar "); + assert_eq!(emphasized_text(&escaped), "fb"); + } + + fn text(spans: &[DrawableBufferSpan]) -> String { + spans + .iter() + .map(|s| if s.newline { "\n" } else { &s.span.content }) + .collect() + } + + #[test] + fn replaces_whole_fuzzy_match_and_preserves_suffix_mouse_offsets() { + let spans = render_matched( + "cmd fb tail", + "fb", + &ProcessedSuggestion::new("foo\\ bar", "", " "), + &[0, 5], + &Palette::dark(), + ); + assert_eq!(text(&spans), "cmd foo\\ bar tail"); + let italic: Vec<_> = spans + .iter() + .filter(|s| s.span.style.add_modifier.contains(Modifier::ITALIC)) + .collect(); + assert_eq!( + italic + .iter() + .map(|s| s.span.content.as_ref()) + .collect::(), + "foo\\ bar " + ); + assert_eq!( + italic.iter().find(|s| s.span.content == "f").unwrap().tags, + vec![Tag::Command(4)] + ); + assert_eq!( + italic.iter().find(|s| s.span.content == "b").unwrap().tags, + vec![Tag::Command(5)] + ); + assert!( + italic + .iter() + .filter(|s| !s.span.style.add_modifier.contains(Modifier::BOLD)) + .all(|s| s.tags == vec![Tag::Command(6)]) + ); + let tail = spans.iter().find(|s| s.span.content == "t").unwrap(); + assert_eq!(tail.tags, vec![Tag::Command(7)]); + let cursor = spans.iter().position(|s| s.is_cursor).unwrap(); + assert_eq!(text(&spans[..cursor]), "cmd foo\\ b"); + assert_eq!(spans.iter().filter(|s| s.is_cursor).count(), 1); + } + + #[test] + fn quoted_unicode_target_can_span_syntax_tokens() { + let spans = render("cmd \"é\" tail", "\"é\"", "\"été deux\" "); + assert_eq!(text(&spans), "cmd \"été deux\" tail"); + } + + #[test] + fn wide_preview_wraps_in_narrow_terminals_without_corrupting_tags() { + for width in [2, 3, 8, 20] { + let spans = render("cmd f tail", "f", "界é界"); + let mut content = crate::content::Contents::new(width); + for drawable in spans { + content.write_tagged_span_dont_overwrite( + &crate::content::TaggedSpan::per_grapheme(drawable.span, drawable.tags), + ); + } + let command_tags: Vec<_> = content + .buf + .iter() + .flat_map(|row| row.iter()) + .filter_map(|cell| match cell.tag { + Tag::Command(byte) => Some(byte), + _ => None, + }) + .collect(); + assert!(command_tags.contains(&5)); // Preview maps to the real cursor. + assert!(command_tags.contains(&9)); // Last suffix byte keeps its real offset. + assert!(command_tags.iter().all(|byte| *byte < "cmd f tail".len())); + } + } + + #[test] + fn refuses_stale_targets_cursor_moves_and_selections() { + let mut buffer = TextBuffer::new("cmd f tail"); + let target = SubString { + start: 4, + s: "f".into(), + }; + assert!( + CompletionPreview::new( + &buffer, + &target, + &ProcessedSuggestion::new("foo", "", ""), + &[] + ) + .is_none() + ); + buffer.try_move_cursor_to_byte_pos(5, true); + let stale = SubString { + start: 4, + s: "z".into(), + }; + assert!( + CompletionPreview::new( + &buffer, + &stale, + &ProcessedSuggestion::new("foo", "", ""), + &[] + ) + .is_none() + ); + assert!( + CompletionPreview::new( + &buffer, + &target, + &ProcessedSuggestion::new("foo", "", ""), + &[] + ) + .is_some() + ); + buffer.start_selection_if_none(); + assert!( + CompletionPreview::new( + &buffer, + &target, + &ProcessedSuggestion::new("foo", "", ""), + &[] + ) + .is_none() + ); + } +} diff --git a/src/app/mod.rs b/src/app/mod.rs index 1e7a06cb..2f31f318 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1,5 +1,6 @@ pub(crate) mod actions; pub(crate) mod auto_close; +mod completion_preview; pub(crate) mod formatted_buffer; mod ui; use crate::subshell_ipc::{self, IpcStatus, SubshellHandle}; @@ -306,8 +307,6 @@ pub(crate) enum ContentMode { wuc_substring: SubString, start_time: std::time::Instant, auto_started: bool, - cycle_insert: bool, - buffer_state: crate::active_suggestions::CompletionBufferState, last_active_suggestions: Option>, }, /// AI command is running as a child process. The child is polled each @@ -1768,8 +1767,6 @@ impl<'a> App<'a> { ref handle, ref wuc_substring, auto_started, - cycle_insert, - ref buffer_state, .. } = self.content_mode { @@ -1781,11 +1778,10 @@ impl<'a> App<'a> { handle.pid ); let wuc = wuc_substring.clone(); - let cycle_insert = cycle_insert && buffer_state.matches(&self.buffer); self.content_mode = ContentMode::Normal; if let Some((builder, elapsed)) = completion_res { - self.finish_tab_complete(builder, wuc, elapsed, auto_started, cycle_insert); + self.finish_tab_complete(builder, wuc, elapsed, auto_started); self.on_possible_buffer_change(); } return true; @@ -1840,7 +1836,7 @@ impl<'a> App<'a> { .resolve_and_write_completion_script(&cmd_word, &script, output_dir); let _ = shell::backend().evaluate_shell_string(&script); self.content_mode = ContentMode::Normal; - self.start_tab_complete(false, None, false); + self.start_tab_complete(false, None); return true; } IpcStatus::Disconnected => { @@ -2169,23 +2165,6 @@ impl<'a> App<'a> { } fn on_possible_buffer_change(&mut self) { - // Keep the original candidate set while cycling. Any external edit or - // cursor movement ends the cycle, including a pending first insertion. - let (keep_cycle, end_cycle) = match &self.content_mode { - ContentMode::TabCompletion(active) => { - let current = active.insertion_is_current(&self.buffer); - (current, active.has_insertion() && !current) - } - ContentMode::TabCompletionWaiting { - cycle_insert: true, - buffer_state, - .. - } => (false, !buffer_state.matches(&self.buffer)), - _ => (false, false), - }; - if end_cycle { - self.take_active_suggestions(); - } if let ContentMode::AgentOutputSelection(ref mut selection) = self.content_mode { let current_buf = self.buffer.buffer(); if current_buf != selection.last_buffer_content { @@ -2267,7 +2246,6 @@ impl<'a> App<'a> { || crate::settings().auto_suggest_inline || is_tab_completion_active) && self.last_key.is_some() - && (!keep_cycle || navigated_history) { #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum CompletionAction { @@ -2481,11 +2459,7 @@ impl<'a> App<'a> { CompletionAction::Restart { carry_over } => { self.dismissed_tab_completion_wuc = None; let prev = self.take_active_suggestions().filter(|_| carry_over); - self.start_tab_complete( - prev.as_ref().is_none_or(|p| p.auto_started), - prev, - false, - ); + self.start_tab_complete(prev.as_ref().is_none_or(|p| p.auto_started), prev); } } } diff --git a/src/app/ui.rs b/src/app/ui.rs index 70fcec06..e5a036f5 100644 --- a/src/app/ui.rs +++ b/src/app/ui.rs @@ -706,52 +706,43 @@ impl App<'_> { None }; - let total_lines = self - .formatted_buffer_cache - .parts - .iter() - .filter(|part| part.token.token.kind == TokenKind::Newline) - .count() - + 1; + let preview = self.completion_preview(); + let animation_time = + (self.mode.is_running() && crate::settings().show_animations).then_some(now); + let spans = self.formatted_buffer_cache.drawable_spans( + animation_time, + selection_range, + preview.as_ref(), + crate::settings().colour_palette.inline_suggestion(), + crate::settings().colour_palette.normal_text(), + ); + let total_lines = spans.iter().filter(|span| span.newline).count() + 1; let max_digits = total_lines.to_string().len(); - let is_cancelled = matches!( self.mode, AppRunningState::Exiting(ExitState::WithoutCommand) ); - for part in self.formatted_buffer_cache.parts.iter() { - let animation_time = if self.mode.is_running() && crate::settings().show_animations { - Some(now) - } else { - None - }; - - for (mut sub_span, tags, is_cursor, _is_sel_byte, is_in_selection) in - part.get_spans(animation_time, selection_range.clone()) - { - if is_cancelled { - sub_span.style = crate::settings().colour_palette.secondary_text(); - } else if is_in_selection { - sub_span.style = crate::settings() - .colour_palette - .convert_to_selected(sub_span.style); - } - - if is_cursor && cursor_pos_maybe.is_none() { - // Skip past any already-filled cells so cursor_position() - // reflects the actual cell the cursor grapheme will land - // on. This mirrors the skip done inside write_span_internal. - if let Some(g) = sub_span.styled_graphemes(sub_span.style).next() { - content.move_to_next_insertion_point(&g, false, None); - } - cursor_pos_maybe = Some(content.cursor_position()); - } - - content.write_tagged_span_dont_overwrite(&TaggedSpan::per_grapheme(sub_span, tags)); + for drawable in spans { + let mut span = drawable.span; + if is_cancelled { + span.style = crate::settings().colour_palette.secondary_text(); + } else if drawable.is_in_selection { + span.style = crate::settings() + .colour_palette + .convert_to_selected(span.style); } - - if part.token.token.kind == TokenKind::Newline { + if drawable.is_cursor && cursor_pos_maybe.is_none() { + let g = span + .styled_graphemes(span.style) + .next() + .unwrap_or_else(|| StyledGrapheme::new(" ", Style::default())); + content.move_to_next_insertion_point(&g, false, None); + cursor_pos_maybe = Some(content.cursor_position()); + } + content + .write_tagged_span_dont_overwrite(&TaggedSpan::per_grapheme(span, drawable.tags)); + if drawable.newline { line_idx += 1; content.newline(); let ps2_spans = self.prompt_manager.get_ps2( @@ -764,7 +755,7 @@ impl App<'_> { } } } - if self.formatted_buffer_cache.draw_cursor_at_end { + if self.formatted_buffer_cache.draw_cursor_at_end && preview.is_none() { let space = StyledGrapheme::new(" ", Style::default()); content.move_to_next_insertion_point(&space, false, None); cursor_pos_maybe = Some(content.cursor_position()); @@ -844,6 +835,7 @@ impl App<'_> { } if let Some((sug_opt, suf)) = &self.inline_history_suggestion + && preview.is_none() && self.mode.is_running() { suf.lines() diff --git a/src/cli.rs b/src/cli.rs index 4ebe9613..a7ed9bb5 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -101,6 +101,10 @@ struct FlylineArgs { /// Show animations #[arg(long = "show-animations", default_missing_value = "true", num_args = 0..=1)] show_animations: Option, + /// Preview the selected completion in italics and submit it with Enter (default true). + /// When disabled, Enter accepts the completion without submitting the command. + #[arg(long, default_missing_value = "true", num_args = 0..=1)] + preview: Option, /// Run matrix animation in the terminal background. Use `on` to always show it, `off` to /// disable it, or an integer number of seconds to show it after that many seconds of /// inactivity (no keypress or mouse event). Defaults to `off`; passing the flag without a @@ -763,7 +767,7 @@ enum KeySubcommands { /// /// Available context variables: always, bufferIsEmpty, bufferIsTrimmedEmpty, /// fuzzyHistorySearch, tabCompletionWaiting, tabCompletion, - /// tabCompletionAvailable, tabCompletionOneResult, tabCompletionInserted, + /// tabCompletionAvailable, tabCompletionOneResult, tabCompletionPreviewAvailable, /// tabCompletionMultiColAvailable, tabCompletionNoFilteredResults, /// tabCompletionNoResults, agentModeWaiting, agentOutputSelection, /// agentModeError, inlineSuggestionAvailable, cursorAtEnd, @@ -1116,6 +1120,10 @@ pub(crate) fn call(words: *const bash_symbols::WordList) -> c_int { settings.show_animations = enabled; } + if let Some(enabled) = parsed.preview { + settings.preview = enabled; + } + if let Some(val) = parsed.matrix_animation { log::info!("Matrix animation set to {:?}", val); settings.matrix_animation = val; @@ -2369,6 +2377,31 @@ mod tests { assert!(!settings.flycomp.is_blacklisted("vim")); } + #[test] + fn test_completion_preview_cli() { + assert!(settings::Settings::default().preview); + assert_eq!( + FlylineArgs::try_parse_from(["flyline"]).unwrap().preview, + None + ); + for args in [ + vec!["flyline", "--preview"], + vec!["flyline", "--preview", "true"], + ] { + assert_eq!( + FlylineArgs::try_parse_from(args).unwrap().preview, + Some(true) + ); + } + assert_eq!( + FlylineArgs::try_parse_from(["flyline", "--preview", "false"]) + .unwrap() + .preview, + Some(false) + ); + assert!(FlylineArgs::try_parse_from(["flyline", "--preview", "invalid"]).is_err()); + } + #[test] fn test_flyline_enable_easter_eggs_parse() { let args = diff --git a/src/completions/tab_completion.rs b/src/completions/tab_completion.rs index 4955e669..eaa7344b 100644 --- a/src/completions/tab_completion.rs +++ b/src/completions/tab_completion.rs @@ -1116,7 +1116,6 @@ impl App<'_> { wuc_substring: SubString, load_time: std::time::Duration, auto_started: bool, - cycle_insert: bool, ) { let completion_context = self.get_completion_context(); let command_word = completion_context @@ -1159,7 +1158,7 @@ impl App<'_> { self.content_mode = ContentMode::Normal; } TabCompleteBufferOutcome::Pending { final_wuc } => { - let mut suggestions = ActiveSuggestions::new( + let suggestions = ActiveSuggestions::new( builder, final_wuc, load_time, @@ -1167,45 +1166,11 @@ impl App<'_> { crate::settings().suggestion_sort_order, crate::settings().fuzzy_mode, ); - if cycle_insert { - suggestions.cycle_insert(&mut self.buffer); - } self.content_mode = ContentMode::TabCompletion(Box::new(suggestions)); } } } } - - /// Backing action for `tabCompletionCycleInsert`: the first press starts tab - /// completion and writes the first suggestion into the buffer, further - /// presses replace that text with the next suggestion. - pub fn cycle_insert_tab_completion(&mut self) { - match &mut self.content_mode { - ContentMode::TabCompletion(active) => { - if active.cycle_insert(&mut self.buffer).is_none() - && active.filtered_suggestions_len() == 0 - { - let previous = self.take_active_suggestions(); - self.start_tab_complete(false, previous, true); - } - } - ContentMode::TabCompletionWaiting { - auto_started, - cycle_insert, - buffer_state, - .. - } if buffer_state.matches(&self.buffer) => { - // Promote the request already in flight instead of killing and - // restarting a slow completion on every Tab press. - *auto_started = false; - *cycle_insert = true; - } - ContentMode::Normal | ContentMode::TabCompletionWaiting { .. } => { - self.start_tab_complete(false, None, true); - } - _ => {} - } - } pub(crate) fn start_flycomp_prompt( &mut self, command_word: String, @@ -1251,7 +1216,6 @@ impl App<'_> { &mut self, auto_started: bool, previous_suggestions: Option>, - cycle_insert: bool, ) { // Stop the current tab completion process if one is running by dropping its handle if let ContentMode::TabCompletionWaiting { handle, .. } = @@ -1318,8 +1282,6 @@ impl App<'_> { wuc_substring, start_time, auto_started, - cycle_insert, - buffer_state: crate::active_suggestions::CompletionBufferState::new(&self.buffer), last_active_suggestions, }; diff --git a/src/settings.rs b/src/settings.rs index 95423387..48ccba56 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -305,6 +305,8 @@ pub struct Settings { pub tutorial_step: TutorialStep, /// Whether to show all animations (cursor movement, cursor fading, dynamic time). pub show_animations: bool, + /// Whether to preview the selected completion in the command line. + pub preview: bool, /// Whether to show inline history suggestions. pub show_inline_history: bool, /// Whether to show metadata (index and timestamp) for inline history suggestions. @@ -419,6 +421,7 @@ impl Default for Settings { run_tutorial: false, tutorial_step: TutorialStep::default(), show_animations: true, + preview: true, show_inline_history: true, auto_suggest: true, auto_suggest_inline: true, diff --git a/tests/tab_cycle_pty.py b/tests/tab_cycle_pty.py index 6d29a44f..9b31fd9c 100755 --- a/tests/tab_cycle_pty.py +++ b/tests/tab_cycle_pty.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Exercise completion cycling in a real Bash PTY, without Docker. +"""Exercise selected-completion previews in a real Bash PTY, without Docker. Usage: python3 tests/tab_cycle_pty.py --flyline target/release/libflyline.so """ @@ -27,12 +27,16 @@ class Shell: def __init__( - self, library, directory, bash_path, *, automatic=False, inline=False, delay=0 + self, library, directory, bash_path, *, automatic=False, inline=False, preview=None, + delay=0, mouse=False, files=(), setup="" ): self.output = bytearray() self.queries = {b"\x1b[>c": 0, b"\x1b[6n": 0} self.requests = directory / "requests" rcfile = directory / "bashrc" + for filename in files: + (directory / filename).touch() + completion_setup = "" if files else "complete -o nospace -F __complete_cycle __cycle\n" rcfile.write_text( "PS1='$ '\n" "HISTFILE=/dev/null\n" @@ -42,25 +46,25 @@ def __init__( f" sleep {delay}\n" " COMPREPLY=()\n" " local value\n" - " for value in foo foobar; do\n" + " for value in far foo; do\n" ' [[ $value == "${COMP_WORDS[COMP_CWORD]}"* ]] && COMPREPLY+=("$value")\n' " done\n" " return 0\n" "}\n" - "complete -o nospace -F __complete_cycle __cycle\n" + f"{completion_setup}" f"enable -f {shlex.quote(str(library))} flyline || exit 1\n" "flyline --set-delayed-startup-ms 0\n" - "flyline mouse --mode disabled\n" + "flyline --show-animations false\n" + f"flyline mouse --mode {'simple' if mouse else 'disabled'}\n" "flyline suggestions --sort-order alphabetical " f"--auto-suggest {str(automatic).lower()} " f"--auto-suggest-inline {str(inline).lower()}\n" - "flyline key bind Tab 'editingBufferMode=tabCompletionCycleInsert'\n" - "flyline key bind Tab 'tabCompletionBackgroundActive=tabCompletionCycleInsert'\n" - "flyline key bind Tab 'tabCompletionWaiting=tabCompletionCycleInsert'\n" - "flyline key bind Tab 'tabCompletionAvailable=tabCompletionCycleInsert'\n" - "flyline key bind Enter 'tabCompletionInserted=submitOrNewline'\n" - "flyline key bind Ctrl+g 'always=submitOrNewline'\n" - "flyline key bind Ctrl+y 'tabCompletionAvailable=tabCompletionAcceptAll'\n", + "flyline editor --show-inline-history false\n" + + (f"flyline --preview {str(preview).lower()}\n" if preview is not None else "") + + "flyline key bind Ctrl+g 'always=submitOrNewline'\n" + "flyline key bind Ctrl+y 'tabCompletionAvailable=tabCompletionAcceptAll'\n" + "flyline key bind Ctrl+t 'tabCompletionEntrySelected=tabCompletionAcceptEntry'\n" + + setup, encoding="utf-8", ) self.pid, self.fd = pty.fork() @@ -132,7 +136,8 @@ def close(self): def run_case( - library, name, steps, expected, *, bash_path, request_count=None, **options + library, name, steps, expected, *, bash_path, request_count=None, + italic_after=None, cursor_after=None, no_result_after=(), menu_marker=b"CommandComp", **options ): with tempfile.TemporaryDirectory(prefix="flyline-cycle-test-") as directory: shell = Shell(library, Path(directory), bash_path, **options) @@ -141,9 +146,35 @@ def run_case( while b"\x1b[?2004h" not in shell.output and time.monotonic() < deadline: shell.pump(0.02) assert b"\x1b[?2004h" in shell.output, "Flyline did not initialize the terminal" - shell.pump(0.15) + shell.pump(0.7) for index, (keys, wait) in enumerate(steps): + output_start = len(shell.output) shell.send(keys, wait) + if b"\t" in keys and not options.get("delay"): + # Wait for the actual completion menu, not a fixed delay: + # concurrent builds can leave the first request in flight. + deadline = time.monotonic() + 3 + while menu_marker not in shell.output and time.monotonic() < deadline: + shell.pump(0.05) + assert menu_marker in shell.output, "Completion menu did not appear" + if index == italic_after: + codes = re.findall(rb"\x1b\[([0-9;]*)m", shell.output[output_start:]) + italic = any(b"3" in code.split(b";") for code in codes) + assert italic == (options.get("preview") is not False), ( + "Selected completion preview did not honor the italic setting" + ) + if cursor_after and index in cursor_after: + # Flyline restores the terminal cursor after drawing each + # frame. CHA columns are one-based; PS1 is the fixed "$ ". + columns = re.findall(rb"\x1b\[(\d+)G", shell.output) + expected_column = cursor_after[index] + assert columns and int(columns[-1]) == expected_column, ( + f"After step {index}: expected cursor column {expected_column}, got {columns[-1:]!r}" + ) + if index in no_result_after: + assert not re.search(rb"\r?\nCYCLE_RESULT:<", shell.output), ( + "Completion was executed before the second Enter press" + ) if index == 0 and options.get("delay"): deadline = time.monotonic() + 3 while not shell.requests.exists() and time.monotonic() < deadline: @@ -170,61 +201,129 @@ def main(): bash_path=arguments.bash.resolve(strict=True), ) run( - "cycle then Enter", - [(b"__cycle f", 0.15), (b"\t", 0.2), (b"\t", 0.1), (b"\r", 0.1)], - "foobar", + "Tab cycling, one Enter accepts and executes", + [(b"__cycle f", 0.15), (b"\t", 0.5), (b"\t", 0.1), + (b"\r", 0.1)], "foo", italic_after=1, cursor_after={1: 12, 2: 12}, + ) + run( + "Escape preserves original input", + [(b"__cycle f\t", 0.5), (b"\t", 0.1), (ESCAPE, 0.15), (b"\x07", 0.1)], "f", + ) + run( + "typing refines original input", + [(b"__cycle f\t", 0.5), (b"o", 0.15), (ESCAPE, 0.1), (b"\x07", 0.1)], + "fo", cursor_after={0: 12, 1: 13}, + ) + run( + "accept all uses original replacement span", + [(b"__cycle f\t", 0.5), (b"\x19", 0.1), (b"\x07", 0.1)], "far foo", ) run( - "type after insertion", - [(b"__cycle f\t", 0.2), (b"b", 0.1), (b"\t", 0.2), (b"\x07", 0.1)], - "foobar", + "arrow navigation then one Enter executes", + [(b"__cycle f\t", 0.5), (b"\x1b[B", 0.1), (b"\r", 0.1)], "foo", ) run( - "accept all after insertion", - [(b"__cycle f\t", 0.2), (b"\x19", 0.1), (b"\x07", 0.1)], - "foo foobar", + "Shift Tab wraps backwards then one Enter executes", + [(b"__cycle f\t", 0.5), (b"\x1b[Z", 0.1), (b"\r", 0.1)], "foo", ) run( - "navigate then accept", - [(b"__cycle f\t", 0.2), (b"\x1b[B", 0.1), (b"\r", 0.1), (b"\x07", 0.1)], - "foobar", + "unselected background becomes selected on Tab", + [(b"\x1b[200~__cycle f\x1b[201~", 0.1), (b"\x1b[C", 0.5), (b"\t", 0.15), (b"\t", 0.1), + (b"\r", 0.1)], "foo", inline=True, ) run( - "hidden background completion", - [(b"__cycle f", 0.3), (b"\t", 0.15), (b"\t", 0.1), (b"\r", 0.1)], - "foobar", - inline=True, + "automatic menu cancellation", + [(b"\x1b[200~__cycle f\x1b[201~", 0.1), (b"\x1b[C", 0.5), (b"\x1b[B", 0.1), (ESCAPE, 0.15), (b"\x07", 0.1)], + "f", automatic=True, ) run( - "repeated Tab while loading", - [(b"__cycle f\t", 0.05), (b"\t", 0.5), (b"\r", 0.1)], - "foo", - delay=0.35, - request_count=1, + "Escape cancels pending completion", + [(b"__cycle f\t", 0.05), (ESCAPE, 0.5), (b"\x07", 0.1)], "f", delay=0.35, ) run( - "Escape cancels pending insertion", - [(b"__cycle f\t", 0.05), (ESCAPE, 0.5), (b"\x07", 0.1)], - "f", - delay=0.35, + "typing cancels pending preview", + [(b"__cycle f\t", 0.05), (b"b", 0.5), (b"\x07", 0.1)], "fb", delay=0.35, ) + for enter in [b"\r", b"\n"]: + run( + f"disabled preview accepts without execution until the second Enter ({enter!r})", + [(b"__cycle f\t", 0.5), (b"\t", 0.1), (enter, 0.3), (enter, 0.1)], + "foo", preview=False, italic_after=0, no_result_after={2}, + ) + run( + "explicitly enabled preview accepts and executes with one Enter", + [(b"__cycle f\t", 0.5), (b"\t", 0.1), (b"\r", 0.1)], "foo", preview=True, + ) + run( + "preview preserves trailing arguments", + [(b"__cycle f tail", 0.15), (b"\x1b[D" * 5, 0.1), (b"\t", 0.5), + (b"\t", 0.1), (b"\r", 0.1)], "foo tail", + ) + run( + "Ctrl J also accepts and executes in one press", + [(b"__cycle f\t", 0.5), (b"\t", 0.1), (b"\n", 0.1)], "foo", + ) + run( + "unselected automatic suggestion is not accepted by Enter", + [(b"\x1b[200~__cycle f\x1b[201~", 0.1), (b"\x1b[C", 0.5), (b"\r", 0.1)], + "f", automatic=True, + ) + run( + "selected automatic suggestion executes with one Enter", + [(b"\x1b[200~__cycle f\x1b[201~", 0.1), (b"\x1b[C", 0.5), + (b"\x1b[B", 0.1), (b"\r", 0.1)], "far", automatic=True, + ) + for accept in [b"\x1b[C", b"\x1b[F"]: + run( + f"selected preview accepted by {accept!r} survives Escape", + [(b"\x1b[200~__cycle f\x1b[201~", 0.1), (b"\x1b[C", 0.6), + (b"\x1b[B", 0.2), (b"\x1b[B", 0.2), (accept, 0.2), + (ESCAPE, 0.1), (b"\x07", 0.1)], + "foo", automatic=True, inline=True, + ) + run( + "hidden inline suggestion cannot be accepted word by word", + [(b"\x1b[200~__cycle f\x1b[201~", 0.1), (b"\x1b[C", 0.6), + (b"\x1b[B", 0.2), (b"\x1b[B", 0.2), (b"\x1b[1;5C", 0.2), + (ESCAPE, 0.1), (b"\x07", 0.1)], "f", automatic=True, inline=True, + ) + run( + "disabling preview preserves original inline acceptance", + [(b"\x1b[200~__cycle f\x1b[201~", 0.1), (b"\x1b[C", 0.6), + (b"\x1b[B", 0.2), (b"\x1b[B", 0.2), (b"\x1b[C", 0.2), (b"\r", 0.1)], + "far", automatic=True, inline=True, preview=False, + ) + for preview in [True, False]: + run( + f"mouse click on typed letter retains its real position (preview={preview})", + [(b"__cycle f\t", 0.6), (b"\x1b[<0;11;1M", 0.15), + (b"\x1b[<0;11;1m", 0.15), (b"X", 0.2), (ESCAPE, 0.1), (b"\x07", 0.1)], + "Xf", mouse=True, preview=preview, + ) + for typed, browse, expected in [("i\u0307", b"\t", "İabc"), ("İ", b"", "i\u0307xyz")]: + run( + f"case-expanding Unicode prefix keeps cursor at typed text ({typed!r})", + [(f"__cycle {typed}\t".encode(), 0.6), (browse, 0.2), (b"\r", 0.1)], + expected, cursor_after={0: 12, 1: 12}, + setup=( + "flyline suggestions set-fuzzy-mode none\n" + "__complete_cycle() { COMPREPLY=('İabc' 'i\u0307xyz'); }\n" + ), + ) run( - "typing cancels pending insertion", - [(b"__cycle f\t", 0.05), (b"b", 0.5), (b"\x07", 0.1)], - "fb", - delay=0.35, + "escaped filename space retains the cursor and executes the selected file", + [(b"\x1b[200~__cycle foo\\ \x1b[201~", 0.6), (b"\t", 0.6), (b"\r", 0.1)], + "foo one", files=("foo one", "foo two"), menu_marker=b"FilenameExpansion", + cursor_after={0: 16, 1: 16}, ) run( - "cursor movement cancels pending insertion", - [(b"__cycle f\t", 0.05), (b"\x1b[D", 0.5), (b"\x07", 0.1)], - "f", - delay=0.35, + "incomplete command continues on the next line after accepting", + [(b"if __cycle f\t", 0.5), (b"\r", 0.1), (b"then :; fi\r", 0.1)], "far", ) run( - "Escape retains inserted text", - [(b"__cycle f", 0.3), (b"\t", 0.2), (ESCAPE, 0.2), (b"\x07", 0.1)], - "foo", - automatic=True, + "explicit accept without execution is one undo step", + [(b"__cycle f\t", 0.5), (b"\t", 0.1), (b"\x14", 0.1), + (b"\x1a", 0.1), (b"\x07", 0.1)], "f", )