diff --git a/README.md b/README.md index de152eff..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. diff --git a/src/active_suggestions.rs b/src/active_suggestions.rs index 13132d82..8ab0943c 100644 --- a/src/active_suggestions.rs +++ b/src/active_suggestions.rs @@ -1984,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 { @@ -2013,6 +2018,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 +2215,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 +2350,6 @@ impl ActiveSuggestions { self.last_num_visible_cols = final_grid.len(); - self.last_num_rows_per_col = max_rows; final_grid } @@ -2346,7 +2360,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 +2367,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) @@ -2446,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; @@ -2479,9 +2503,25 @@ impl ActiveSuggestions { self.update_fuzzy_filtered(); } + /// 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 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)", @@ -2528,6 +2568,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()]; } @@ -2612,6 +2659,91 @@ impl ActiveSuggestions { } } +#[cfg(test)] +mod preview_selection_tests { + use super::*; + + fn suggestions() -> ActiveSuggestions { + ActiveSuggestions::new( + ActiveSuggestionsBuilder::from_processed( + ["far", "foo", "fzz"].map(|s| ProcessedSuggestion::new(s, "", "")), + ), + SubString { + start: 4, + s: "f".into(), + }, + std::time::Duration::ZERO, + false, + crate::settings::SuggestionSortOrder::Alphabetical, + crate::settings::FuzzyMode::None, + ) + } + + #[test] + fn navigation_and_resize_keep_preview_and_acceptance_in_sync() { + let mut active = suggestions(); + let mut buffer = TextBuffer::new("cmd f"); + active.into_grid(2, 80, &Palette::default(), None); + 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()); + active.into_grid(rows, 40, &Palette::default(), None); + assert_eq!(active.selected_suggestion().unwrap().0.s, "foo"); + } + assert_eq!(buffer.buffer(), "cmd f"); + active.accept_selected_filtered_item(&mut buffer); + assert_eq!(buffer.buffer(), "cmd foo"); + buffer.undo(); + assert_eq!(buffer.buffer(), "cmd f"); + } + + #[test] + 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 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 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"); + } +} + #[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..7472a775 100644 --- a/src/app/actions/keyboard.rs +++ b/src/app/actions/keyboard.rs @@ -2471,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(), @@ -2869,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 @@ -4651,6 +4666,8 @@ 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 = "Tab completion overlay is showing more than one column of candidates")] @@ -4802,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 64c10436..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}; 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 9dc20967..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, + /// 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/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 new file mode 100755 index 00000000..9b31fd9c --- /dev/null +++ b/tests/tab_cycle_pty.py @@ -0,0 +1,331 @@ +#!/usr/bin/env python3 +"""Exercise selected-completion previews 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, 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" + "__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 far foo; do\n" + ' [[ $value == "${COMP_WORDS[COMP_CWORD]}"* ]] && COMPREPLY+=("$value")\n' + " done\n" + " return 0\n" + "}\n" + f"{completion_setup}" + f"enable -f {shlex.quote(str(library))} flyline || exit 1\n" + "flyline --set-delayed-startup-ms 0\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 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() + 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, + 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) + 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.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: + 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( + "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( + "arrow navigation then one Enter executes", + [(b"__cycle f\t", 0.5), (b"\x1b[B", 0.1), (b"\r", 0.1)], "foo", + ) + run( + "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( + "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( + "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( + "Escape cancels pending completion", + [(b"__cycle f\t", 0.05), (ESCAPE, 0.5), (b"\x07", 0.1)], "f", delay=0.35, + ) + run( + "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( + "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( + "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( + "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", + ) + + +if __name__ == "__main__": + main()