From 9f1972315dab37dbcf8cdf4a2f3e7dc26abcb05a Mon Sep 17 00:00:00 2001 From: AsumiChan Date: Sun, 25 Oct 2026 08:57:32 -0400 Subject: [PATCH 1/2] Add a searchable, navigable history picker (#24) --- README.md | 31 +- src/commands/builtins.rs | 5 +- src/config.rs | 23 + src/history_search.rs | 1048 ++++++++++++++++++++++++++++++++++++++ src/main.rs | 365 ++++++++++++- src/syntax_highlight.rs | 257 ++++++++++ 6 files changed, 1713 insertions(+), 16 deletions(-) create mode 100644 src/history_search.rs create mode 100644 src/syntax_highlight.rs diff --git a/README.md b/README.md index 46116bd..f8aaf74 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ Built-in commands (also listed by `help`): | `ls [--show-hidden] [dir]` | List files in columns; dotfiles hidden unless `--show-hidden` | | `cd [dir]` | Change directory (`-` = previous, `~` = home) | | `pwd` | Print working directory | -| `history [n]` | Show recent commands (last n) | +| `history [n]` | Show recent commands (last n); Ctrl-R searches them interactively | | `export VAR=val` | Set a session environment variable | | `unset VAR` | Remove a session environment variable | | `alias ` | Manage aliases: `create `, `ls`, `rm ` | @@ -107,12 +107,38 @@ false && echo skipped || echo ran history 20 | tail ``` +### History search + +`Ctrl-R` opens a searchable, navigable history picker. It starts with whatever +is already on the prompt, so `git ch` followed by `Ctrl-R` jumps straight to +the matching commands: + +``` + Ash history search 3/48 +> git ch +──────────────────────────────────────────────────────── +> git checkout main + git checkout -b feature + git cherry-pick HEAD~1 + 1/3 ↑↓ move · enter edit · esc cancel +``` + +Type to narrow the list (case-insensitive, with commands that start with the +query listed first). Move with `↑`/`↓` or `Ctrl-P`/`Ctrl-N`, page with +`PgUp`/`PgDn`, and jump with `Home`/`End`. `Enter` puts the selected command +back on the prompt so it can still be edited before running; `Esc` (or +`Ctrl-C`) restores whatever was being typed. `Ctrl-U` clears the query and +`Ctrl-W` deletes its last word. + +With a partial command typed, `↑` opens the same picker filtered by that text. +On an empty prompt, `↑` keeps its old job of walking back through history. + ## Configuration Everything lives in `~/.aeroshell/`: - `config.json` — settings, colors, aliases -- `history.txt` — persistent command history (up/down arrows recall) +- `history.txt` — persistent command history (up/down arrows recall, Ctrl-R searches) Handy session variables (`export`) survive per session; aliases are persistent in `config.json`, e.g @@ -177,6 +203,7 @@ cargo run Code layout: - `src/main.rs` — REPL, arg parsing, pipelines, login-shell handling +- `src/history_search.rs` — searchable history picker (Ctrl-R / Up) - `src/commands/builtins.rs` — built-in commands - `src/commands/aepkg.rs` — package manager command - `src/config.rs` — config, themes, prompt rendering diff --git a/src/commands/builtins.rs b/src/commands/builtins.rs index 4c8ed90..6b3b188 100644 --- a/src/commands/builtins.rs +++ b/src/commands/builtins.rs @@ -222,7 +222,10 @@ const HELP: &[HelpEntry] = &[ "Change directory ('-' = previous, '~' = home)", ), cmd("pwd", "Print working directory"), - cmd("history [n]", "Show recent commands (last n)"), + cmd( + "history [n]", + "Show recent commands (last n); Ctrl-R searches them interactively", + ), cmd("export VAR=val", "Set a session environment variable"), cmd("unset VAR", "Remove a session environment variable"), HelpEntry { diff --git a/src/config.rs b/src/config.rs index 9bd0c1d..4d9d169 100644 --- a/src/config.rs +++ b/src/config.rs @@ -90,6 +90,12 @@ impl Config { colors.insert("strikethrough".into(), "\x1b[9m".into()); colors.insert("dim".into(), "\x1b[2m".into()); colors.insert("highlight".into(), "\x1b[7m".into()); + colors.insert("autosuggestion".into(), "\x1b[38;5;244m".into()); + colors.insert("syntax_command".into(), "\x1b[96m".into()); + colors.insert("syntax_argument".into(), "\x1b[37m".into()); + colors.insert("syntax_redirect".into(), "\x1b[33m".into()); + colors.insert("syntax_pipe".into(), "\x1b[95m".into()); + colors.insert("syntax_quote".into(), "\x1b[92m".into()); colors.insert("orange".into(), "\x1b[38;5;208m".into()); colors.insert("purple".into(), "\x1b[38;5;213m".into()); colors.insert("brown".into(), "\x1b[38;5;130m".into()); @@ -250,6 +256,16 @@ pub fn load_config() -> Result { .or_insert_with(|| value.clone()); } + if config + .colors + .get("autosuggestion") + .is_some_and(|color| color == "\x1b[2m") + { + config + .colors + .insert("autosuggestion".into(), "\x1b[38;5;244m".into()); + } + // Migrate old ls palettes to the current one. let ls_migrations = [ ("ls_dir", "\x1b[31m", "\x1b[32m"), @@ -581,9 +597,16 @@ mod tests { "ls_file", "ls_script", "bold", + "autosuggestion", + "syntax_command", + "syntax_argument", + "syntax_redirect", + "syntax_pipe", + "syntax_quote", ] { assert!(cfg.colors.contains_key(key), "missing color {key}"); } + assert_eq!(cfg.colors["autosuggestion"], "\x1b[38;5;244m"); assert!(cfg.prompt_template.contains("{hostname}")); assert!(cfg.prompt_template.contains("{pwd}")); assert_eq!(cfg.prompt_template, default_prompt_template()); diff --git a/src/history_search.rs b/src/history_search.rs new file mode 100644 index 0000000..bdacb2b --- /dev/null +++ b/src/history_search.rs @@ -0,0 +1,1048 @@ +//! A searchable, navigable history picker. +//! +//! The REPL hands control here when the user asks for history search (Ctrl-R, +//! or Up on a partial command). The picker filters the whole history as the +//! query is typed, moves through the matches with the arrow keys, and hands +//! the chosen command back to the prompt for editing. +//! +//! The state machine and drawing are kept apart from the terminal layer +//! (`pick`) so matching, navigation and layout can be tested without a TTY. + +use std::io::{self, IsTerminal, Write}; + +use aeroshell::config; + +// Terminal styling for the picker itself, independent of the prompt theme. +const RESET: &str = "\x1b[0m"; +const BOLD: &str = "\x1b[1m"; +const DIM: &str = "\x1b[2m"; +const REVERSE: &str = "\x1b[7m"; +const REVERSE_OFF: &str = "\x1b[27m"; +const MATCH_ON: &str = "\x1b[1;4m"; +const MATCH_OFF: &str = "\x1b[22;24m"; + +/// What the user asked for with one keystroke. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Key { + Char(char), + Backspace, + CtrlW, + Clear, + Up, + Down, + PageUp, + PageDown, + Home, + End, + Enter, + Cancel, + Ignore, +} + +/// What the REPL should do after a keystroke. +#[derive(Debug, PartialEq, Eq)] +pub enum Action { + Continue, + Accept(String), + Cancel, +} + +/// One history entry, prepared for searching and display. +struct Row { + /// The command as stored, handed back verbatim on accept. + text: String, + /// One-line rendering: newlines flattened, control characters removed. + line: String, + /// `line` lowercased for case-insensitive matching (same byte length). + lower: String, +} + +impl Row { + fn new(text: String) -> Self { + let line = display_text(&text); + let lower = line.to_ascii_lowercase(); + Self { text, line, lower } + } +} + +/// One rendered picker frame. +#[derive(Debug, PartialEq, Eq)] +pub struct Frame { + pub lines: Vec, + /// Zero-based (row, column) where the terminal cursor belongs. + pub cursor: (usize, usize), +} + +/// The picker's state machine: query, matches, selection and scrolling. +pub struct HistoryPicker { + rows: Vec, + matching: Vec, + query: String, + selected: usize, + offset: usize, + page: usize, +} + +impl HistoryPicker { + /// Build a picker over `entries`, oldest first, with an initial query. + /// Empty entries are dropped; they can never be selected anyway. + pub fn new(entries: Vec, initial: &str) -> Self { + let rows: Vec = entries + .into_iter() + .filter(|entry| !entry.is_empty()) + .map(Row::new) + .collect(); + let mut picker = Self { + rows, + matching: Vec::new(), + query: initial.to_string(), + selected: 0, + offset: 0, + page: 10, + }; + picker.refilter(); + picker + } + + #[cfg(test)] + pub fn query(&self) -> &str { + &self.query + } + + #[cfg(test)] + pub fn selected(&self) -> usize { + self.selected + } + + #[cfg(test)] + pub fn offset(&self) -> usize { + self.offset + } + + #[cfg(test)] + pub fn match_count(&self) -> usize { + self.matching.len() + } + + pub fn selected_entry(&self) -> Option<&str> { + self.matching + .get(self.selected) + .map(|&index| self.rows[index].text.as_str()) + } + + /// Apply one keystroke. + pub fn handle(&mut self, key: Key) -> Action { + match key { + Key::Char(c) => { + self.query.push(c); + self.refilter(); + } + Key::Backspace => { + if self.query.pop().is_some() { + self.refilter(); + } + } + Key::CtrlW => { + delete_last_word(&mut self.query); + self.refilter(); + } + Key::Clear => { + if !self.query.is_empty() { + self.query.clear(); + self.refilter(); + } + } + Key::Up => self.move_selection(-1), + Key::Down => self.move_selection(1), + Key::PageUp => self.move_page(-1), + Key::PageDown => self.move_page(1), + Key::Home => { + if !self.matching.is_empty() { + self.selected = 0; + } + } + Key::End => { + if !self.matching.is_empty() { + self.selected = self.matching.len() - 1; + } + } + Key::Enter => { + if let Some(entry) = self.selected_entry() { + return Action::Accept(entry.to_string()); + } + } + Key::Cancel => return Action::Cancel, + Key::Ignore => {} + } + Action::Continue + } + + /// Recompute the matches for the current query. Prefix matches come first + /// (they are usually what the user means), then substring matches; each + /// group keeps history order, newest first. + fn refilter(&mut self) { + self.matching.clear(); + if self.query.is_empty() { + self.matching.extend((0..self.rows.len()).rev()); + } else { + let needle = self.query.to_ascii_lowercase(); + let mut prefixes = Vec::new(); + let mut substrings = Vec::new(); + for (index, row) in self.rows.iter().enumerate() { + if let Some(pos) = row.lower.find(&needle) { + if pos == 0 { + prefixes.push(index); + } else { + substrings.push(index); + } + } + } + prefixes.reverse(); + substrings.reverse(); + self.matching.extend(prefixes); + self.matching.extend(substrings); + } + self.selected = 0; + self.offset = 0; + } + + fn move_selection(&mut self, delta: isize) { + if self.matching.is_empty() { + return; + } + let last = self.matching.len() - 1; + let next = self.selected as isize + delta; + self.selected = next.clamp(0, last as isize) as usize; + } + + fn move_page(&mut self, pages: isize) { + let step = self.page.max(1) as isize * pages; + self.move_selection(step); + } + + /// Draw one frame. `height` includes the header, query line, separator and + /// footer; whatever is left is the scrolling match window. Visible lines + /// never exceed `width` columns, so the frame cannot wrap and damage the + /// full-screen layout. + pub fn render(&mut self, width: usize, height: usize, color: bool) -> Frame { + let width = width.max(1); + let height = height.max(1); + + let mut lines: Vec = Vec::with_capacity(height); + if height >= 4 { + lines.push(self.header_line(width, color)); + } + let query_row = lines.len(); + let (query_line, cursor_col) = self.query_line(width, color); + lines.push(query_line); + if height >= 3 { + lines.push(self.separator_line(width, color)); + } + + let footer_reserved = height > lines.len(); + let list_rows = height.saturating_sub(lines.len() + usize::from(footer_reserved)); + self.page = list_rows; + + if list_rows > 0 { + self.ensure_visible(list_rows); + let mut drawn = 0; + for slot in 0..list_rows { + if let Some(&index) = self.matching.get(self.offset + slot) { + let selected = self.offset + slot == self.selected; + lines.push(self.row_line(&self.rows[index], selected, width, color)); + drawn += 1; + } else if slot == 0 && self.matching.is_empty() { + let message = if self.rows.is_empty() { + " no history yet" + } else { + " no matching commands" + }; + lines.push(style(fit(message, width), DIM, color)); + drawn += 1; + } else { + break; + } + } + // Keep the frame exactly `height` rows so nothing stale is left + // behind when a later frame is shorter. + for _ in drawn..list_rows { + lines.push(String::new()); + } + } + + if footer_reserved { + lines.push(self.footer_line(width, color)); + } + while lines.len() < height { + lines.push(String::new()); + } + lines.truncate(height); + + Frame { + lines, + cursor: (query_row, cursor_col), + } + } + + fn ensure_visible(&mut self, list_rows: usize) { + let list_rows = list_rows.max(1); + if self.selected < self.offset { + self.offset = self.selected; + } + if self.selected >= self.offset + list_rows { + self.offset = self.selected + 1 - list_rows; + } + let max_offset = self.matching.len().saturating_sub(list_rows); + self.offset = self.offset.min(max_offset); + } + + fn header_line(&self, width: usize, color: bool) -> String { + let title = " Ash history search "; + let counts = format!("{}/{} ", self.matching.len(), self.rows.len()); + if title.chars().count() + counts.chars().count() <= width { + let padding = width - title.chars().count() - counts.chars().count(); + style( + format!("{title}{}{counts}", " ".repeat(padding)), + BOLD, + color, + ) + } else { + style(fit(&format!("{title}{counts}"), width), BOLD, color) + } + } + + fn query_line(&self, width: usize, color: bool) -> (String, usize) { + let prefix = if width >= 2 { "> " } else { "" }; + let available = width - prefix.chars().count(); + let total = self.query.chars().count(); + let shown: String = if total <= available { + self.query.clone() + } else { + // Keep the end of a long query visible, like a text field. + self.query.chars().skip(total - available).collect() + }; + let cursor = (prefix.chars().count() + shown.chars().count()).min(width - 1); + let mut line = String::new(); + if color && !prefix.is_empty() { + line.push_str(BOLD); + line.push_str(prefix); + line.push_str(RESET); + } else { + line.push_str(prefix); + } + line.push_str(&shown); + (line, cursor) + } + + fn separator_line(&self, width: usize, color: bool) -> String { + style("─".repeat(width), DIM, color) + } + + fn footer_line(&self, width: usize, color: bool) -> String { + let position = if self.matching.is_empty() { + "0/0".to_string() + } else { + format!("{}/{}", self.selected + 1, self.matching.len()) + }; + let text = + format!(" {position} \u{2191}\u{2193} move \u{00b7} enter edit \u{00b7} esc cancel"); + style(fit(&text, width), DIM, color) + } + + fn row_line(&self, row: &Row, selected: bool, width: usize, color: bool) -> String { + // One column is enough for the selection marker on very narrow + // terminals; two keep the text aligned when there is room. + let prefix = match (selected, width) { + (true, 0..=1) => ">", + (true, _) => "> ", + (false, 0..=1) => " ", + (false, _) => " ", + }; + let prefix_width = prefix.chars().count(); + let text = fit(&row.line, width.saturating_sub(prefix_width)); + let (before, matched, after) = split_match(&text, &self.query); + + let mut out = String::new(); + if color { + if selected { + out.push_str(REVERSE); + } + out.push_str(prefix); + out.push_str(before); + if !matched.is_empty() { + out.push_str(MATCH_ON); + out.push_str(matched); + out.push_str(MATCH_OFF); + } + out.push_str(after); + if selected { + // A full-width bar reads better than a reverse patch that + // stops at the end of a short entry. + let used = prefix_width + text.chars().count(); + out.push_str(&" ".repeat(width.saturating_sub(used))); + out.push_str(REVERSE_OFF); + } + } else { + out.push_str(prefix); + out.push_str(&text); + } + out + } +} + +/// The terminal-facing result of asking for a search. +#[derive(Debug, PartialEq, Eq)] +pub enum Picked { + Entry(String), + Cancelled, + Unavailable, +} + +/// Run the picker on the terminal. Returns `Unavailable` when there is nothing +/// to search or stdin/stdout are not a TTY, so the caller can keep the normal +/// prompt without opening an empty screen. +pub fn pick(entries: Vec, initial: &str) -> Picked { + if entries.is_empty() || !io::stdin().is_terminal() || !io::stdout().is_terminal() { + return Picked::Unavailable; + } + let Some(mut terminal) = Terminal::enter() else { + return Picked::Unavailable; + }; + let color = config::active_config().map(|cfg| cfg.color).unwrap_or(true); + let mut picker = HistoryPicker::new(entries, initial); + loop { + let (width, height) = terminal_size(); + let frame = picker.render(width, height, color); + if terminal.draw(&frame).is_err() { + return Picked::Cancelled; + } + let Ok(key) = terminal.read_key() else { + return Picked::Cancelled; + }; + match picker.handle(key) { + Action::Continue => {} + Action::Accept(entry) => return Picked::Entry(entry), + Action::Cancel => return Picked::Cancelled, + } + } +} + +/// Clear the prompt line that the picker interrupted, so the resumed prompt +/// replaces it instead of leaving a stale copy in the transcript. Only acts +/// when the prompt and its text fit on one terminal row; a wrapped or +/// multi-line edit is left exactly as the line editor drew it. +pub fn erase_prompt_line(prompt: &str, line: &str, hint_len: usize) { + if line.contains('\n') || prompt.contains('\n') { + return; + } + let (width, _) = terminal_size(); + if visible_width(prompt) + line.chars().count() + hint_len >= width { + return; + } + let mut stdout = io::stdout(); + let _ = stdout.write_all(b"\x1b[1A\r\x1b[2K"); + let _ = stdout.flush(); +} + +/// Width of `text` on screen, ignoring ANSI escape sequences. +fn visible_width(text: &str) -> usize { + let mut width = 0; + let mut escape = false; + for character in text.chars() { + if escape { + if character.is_ascii_alphabetic() { + escape = false; + } + } else if character == '\x1b' { + escape = true; + } else { + width += 1; + } + } + width +} + +/// Raw mode plus the alternate screen, restored on drop (including panics). +struct Terminal { + original: libc::termios, +} + +impl Terminal { + fn enter() -> Option { + let mut original = unsafe { std::mem::zeroed::() }; + if unsafe { libc::tcgetattr(libc::STDIN_FILENO, &mut original) } != 0 { + return None; + } + let mut raw = original; + unsafe { libc::cfmakeraw(&mut raw) }; + if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &raw) } != 0 { + return None; + } + let mut stdout = io::stdout(); + let _ = stdout.write_all(b"\x1b[?1049h\x1b[?25l\x1b[H\x1b[2J"); + let _ = stdout.flush(); + Some(Self { original }) + } + + fn draw(&mut self, frame: &Frame) -> io::Result<()> { + let mut out = String::from("\x1b[?25l\x1b[H"); + for (index, line) in frame.lines.iter().enumerate() { + out.push_str("\x1b[2K"); + out.push_str(line); + if index + 1 < frame.lines.len() { + out.push_str("\r\n"); + } + } + out.push_str(&format!( + "\x1b[{};{}H\x1b[?25h", + frame.cursor.0 + 1, + frame.cursor.1 + 1 + )); + let mut stdout = io::stdout(); + stdout.write_all(out.as_bytes())?; + stdout.flush() + } + + fn read_key(&mut self) -> io::Result { + let byte = read_byte()?; + match byte { + b'\x1b' => self.read_escape(), + 0x03 | 0x07 | 0x04 => Ok(Key::Cancel), // Ctrl-C, Ctrl-G, Ctrl-D + b'\r' | b'\n' => Ok(Key::Enter), + 0x7f | 0x08 => Ok(Key::Backspace), + 0x15 => Ok(Key::Clear), // Ctrl-U + 0x17 => Ok(Key::CtrlW), + 0x10 => Ok(Key::Up), // Ctrl-P + 0x0e => Ok(Key::Down), // Ctrl-N + 0x12 => Ok(Key::Up), // Ctrl-R steps back through matches + byte if byte < 0x20 => Ok(Key::Ignore), + byte if byte < 0x80 => Ok(Key::Char(byte as char)), + byte => self.read_utf8(byte), + } + } + + /// Parse the rest of an escape sequence. A lone Esc cancels; terminal + /// arrows and paging keys arrive as CSI/SS3 sequences. + fn read_escape(&mut self) -> io::Result { + if !wait_readable(20) { + return Ok(Key::Cancel); + } + let first = read_byte()?; + match first { + b'[' => { + let mut sequence = vec![b'[']; + loop { + if sequence.len() > 8 { + return Ok(Key::Ignore); + } + let byte = read_byte()?; + sequence.push(byte); + if (0x40..=0x7e).contains(&byte) { + break; + } + } + Ok(match sequence.as_slice() { + b"[A" => Key::Up, + b"[B" => Key::Down, + b"[H" | b"[1~" | b"[7~" => Key::Home, + b"[F" | b"[4~" | b"[8~" => Key::End, + b"[5~" => Key::PageUp, + b"[6~" => Key::PageDown, + _ => Key::Ignore, + }) + } + b'O' => { + let byte = read_byte()?; + Ok(match byte { + b'A' => Key::Up, + b'B' => Key::Down, + b'H' => Key::Home, + b'F' => Key::End, + _ => Key::Ignore, + }) + } + _ => Ok(Key::Ignore), + } + } + + fn read_utf8(&mut self, first: u8) -> io::Result { + let extra = match first { + 0xc0..=0xdf => 1, + 0xe0..=0xef => 2, + 0xf0..=0xf7 => 3, + _ => return Ok(Key::Ignore), + }; + let mut bytes = vec![first]; + for _ in 0..extra { + bytes.push(read_byte()?); + } + Ok(std::str::from_utf8(&bytes) + .ok() + .and_then(|text| text.chars().next()) + .map_or(Key::Ignore, Key::Char)) + } +} + +impl Drop for Terminal { + fn drop(&mut self) { + let mut stdout = io::stdout(); + let _ = stdout.write_all(b"\x1b[?25h\x1b[?1049l"); + let _ = stdout.flush(); + unsafe { + libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &self.original); + } + } +} + +fn terminal_size() -> (usize, usize) { + #[cfg(unix)] + { + let mut size = unsafe { std::mem::zeroed::() }; + if unsafe { libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut size) } == 0 + && size.ws_col > 0 + && size.ws_row > 0 + { + return (size.ws_col as usize, size.ws_row as usize); + } + } + (80, 24) +} + +fn read_byte() -> io::Result { + let mut byte = [0u8; 1]; + loop { + let read = unsafe { libc::read(libc::STDIN_FILENO, byte.as_mut_ptr().cast(), 1) }; + if read == 1 { + return Ok(byte[0]); + } + if read == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "stdin closed")); + } + let error = io::Error::last_os_error(); + if error.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(error); + } +} + +fn wait_readable(timeout_ms: i32) -> bool { + let mut poll = libc::pollfd { + fd: libc::STDIN_FILENO, + events: libc::POLLIN, + revents: 0, + }; + loop { + let ready = unsafe { libc::poll(&mut poll, 1, timeout_ms) }; + if ready >= 0 { + return ready > 0; + } + if io::Error::last_os_error().kind() != io::ErrorKind::Interrupted { + return false; + } + } +} + +/// The searchable, printable form of a stored command: newlines become a +/// visible marker, tabs become spaces, and other control characters (which +/// could otherwise inject terminal escapes) are dropped. +fn display_text(entry: &str) -> String { + let mut out = String::with_capacity(entry.len()); + for character in entry.chars() { + match character { + '\n' => out.push_str(" \u{23ce} "), + '\t' => out.push_str(" "), + c if c.is_control() => {} + c => out.push(c), + } + } + out +} + +fn delete_last_word(query: &mut String) { + while query.ends_with(' ') { + query.pop(); + } + while let Some(last) = query.chars().next_back() { + if last == ' ' { + break; + } + query.pop(); + } +} + +/// Split `text` around its first case-insensitive occurrence of `query`. +fn split_match<'a>(text: &'a str, query: &str) -> (&'a str, &'a str, &'a str) { + if query.is_empty() { + return (text, "", ""); + } + let haystack = text.to_ascii_lowercase(); + let needle = query.to_ascii_lowercase(); + match haystack.find(&needle) { + Some(start) => { + let end = start + needle.len(); + // ASCII lowercasing preserves byte length and every non-ASCII + // character, so these are still valid boundaries in `text`. + (&text[..start], &text[start..end], &text[end..]) + } + None => (text, "", ""), + } +} + +/// Crop `text` to `width` characters, ending in an ellipsis when it had to cut. +fn fit(text: &str, width: usize) -> String { + if width == 0 { + return String::new(); + } + if text.chars().count() <= width { + return text.to_string(); + } + let mut out: String = text.chars().take(width - 1).collect(); + out.push('\u{2026}'); + out +} + +fn style(text: String, code: &str, color: bool) -> String { + if color { + format!("{code}{text}{RESET}") + } else { + text + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn picker(entries: &[&str]) -> HistoryPicker { + HistoryPicker::new(entries.iter().map(|entry| entry.to_string()).collect(), "") + } + + fn picker_with(entries: &[&str], query: &str) -> HistoryPicker { + HistoryPicker::new( + entries.iter().map(|entry| entry.to_string()).collect(), + query, + ) + } + + /// Drop the SGR sequences this module emits, leaving visible text. + fn plain(line: &str) -> String { + let mut out = String::new(); + let mut chars = line.chars(); + while let Some(character) = chars.next() { + if character == '\x1b' { + for code in chars.by_ref() { + if code.is_ascii_alphabetic() { + break; + } + } + } else { + out.push(character); + } + } + out + } + + fn body(frame: &Frame) -> String { + frame + .lines + .iter() + .map(|line| plain(line)) + .collect::>() + .join("\n") + } + + #[test] + fn newest_entries_come_first() { + let mut picker = picker(&["old", "middle", "new"]); + assert_eq!(picker.match_count(), 3); + assert_eq!(picker.selected_entry(), Some("new")); + + let frame = picker.render(40, 8, false); + let text = body(&frame); + assert!(text.find("new").unwrap() < text.find("middle").unwrap()); + assert!(text.find("middle").unwrap() < text.find("old").unwrap()); + } + + #[test] + fn search_is_case_insensitive_and_filters() { + let mut picker = picker_with(&["Git status", "cargo test", "git log"], "GIT"); + assert_eq!(picker.match_count(), 2); + assert_eq!(picker.selected_entry(), Some("git log")); + + picker = picker_with(&["Git status", "cargo test", "git log"], "cArGo"); + assert_eq!(picker.match_count(), 1); + assert_eq!(picker.selected_entry(), Some("cargo test")); + } + + #[test] + fn prefix_matches_rank_before_other_contains() { + let picker = picker_with(&["echo git", "git status", "legit"], "git"); + let entries: Vec<&str> = picker + .matching + .iter() + .map(|&index| picker.rows[index].text.as_str()) + .collect(); + // Prefix match first, then substring matches newest first. + assert_eq!(entries, vec!["git status", "legit", "echo git"]); + } + + #[test] + fn navigation_stops_at_the_ends() { + let mut picker = picker(&["one", "two", "three"]); + assert_eq!(picker.selected(), 0); + picker.handle(Key::Up); + assert_eq!(picker.selected(), 0); + picker.handle(Key::Down); + picker.handle(Key::Down); + assert_eq!(picker.selected(), 2); + picker.handle(Key::Down); + assert_eq!(picker.selected(), 2); + picker.handle(Key::Up); + assert_eq!(picker.selected(), 1); + } + + #[test] + fn page_and_home_end_keys_move_selection() { + let entries: Vec = (0..30).map(|n| format!("entry {n}")).collect(); + let mut picker = HistoryPicker::new(entries, ""); + // Height 10 leaves six list rows: header, query, separator, footer. + picker.render(40, 10, false); + assert_eq!(picker.page, 6); + + picker.handle(Key::PageDown); + assert_eq!(picker.selected(), 6); + picker.handle(Key::PageDown); + assert_eq!(picker.selected(), 12); + picker.handle(Key::PageUp); + assert_eq!(picker.selected(), 6); + picker.handle(Key::End); + assert_eq!(picker.selected(), 29); + picker.handle(Key::Home); + assert_eq!(picker.selected(), 0); + } + + #[test] + fn changing_the_query_resets_selection_and_scroll() { + let entries: Vec = (0..30).map(|n| format!("cmd {n}")).collect(); + let mut picker = HistoryPicker::new(entries, ""); + picker.render(40, 10, false); + picker.handle(Key::PageDown); + assert_eq!(picker.selected(), 6); + picker.render(40, 10, false); + assert_eq!(picker.offset(), 1); + + picker.handle(Key::Char('c')); + assert_eq!(picker.selected(), 0); + assert_eq!(picker.offset(), 0); + assert_eq!(picker.match_count(), 30); + } + + #[test] + fn backspace_and_ctrl_u_widen_the_search() { + let mut picker = picker(&["cargo build", "git status"]); + picker.handle(Key::Char('g')); + assert_eq!(picker.match_count(), 2); + picker.handle(Key::Char('i')); + assert_eq!(picker.match_count(), 1); + picker.handle(Key::Backspace); + assert_eq!(picker.match_count(), 2); + picker.handle(Key::Clear); + assert_eq!(picker.query(), ""); + assert_eq!(picker.match_count(), 2); + } + + #[test] + fn ctrl_w_deletes_the_last_word() { + let mut picker = picker(&["git status"]); + for character in "git sta".chars() { + picker.handle(Key::Char(character)); + } + assert_eq!(picker.query(), "git sta"); + picker.handle(Key::CtrlW); + assert_eq!(picker.query(), "git "); + } + + #[test] + fn enter_accepts_the_selected_entry_verbatim() { + let mut picker = picker(&["echo one", "echo two"]); + picker.handle(Key::Down); + assert_eq!( + picker.handle(Key::Enter), + Action::Accept("echo one".to_string()) + ); + } + + #[test] + fn enter_restores_newlines_in_a_multiline_entry() { + let mut picker = picker(&["cat < git log")); + + let unselected = &frame.lines[4]; + assert!(!unselected.contains(REVERSE)); + assert!(plain(unselected).starts_with(" git status")); + } + + #[test] + fn color_free_render_uses_a_marker_for_selection() { + let mut picker = picker(&["git status", "git log"]); + let frame = picker.render(60, 8, false); + assert!(!frame.lines.iter().any(|line| line.contains('\x1b'))); + assert!(frame.lines[3].starts_with("> git log")); + assert!(frame.lines[4].starts_with(" git status")); + } + + #[test] + fn frames_fit_the_terminal_width() { + let long = "x".repeat(200); + let mut picker = picker(&[long.as_str(), "short"]); + picker.handle(Key::Char('x')); + for width in [1, 2, 5, 20, 79] { + let frame = picker.render(width, 10, true); + for line in &frame.lines { + assert!( + plain(line).chars().count() <= width, + "line {line:?} exceeds width {width}" + ); + } + assert!(frame.cursor.1 < width.max(1)); + } + } + + #[test] + fn long_queries_show_their_tail() { + let mut picker = picker(&["unrelated"]); + for character in "abcdefghijklmnopqrstuvwxyz".chars() { + picker.handle(Key::Char(character)); + } + let frame = picker.render(12, 6, false); + let query_line = plain(&frame.lines[1]); + assert!(query_line.starts_with("> ")); + assert!(query_line.ends_with("xyz")); + assert_eq!(frame.cursor, (1, 11)); + } + + #[test] + fn frames_are_exactly_the_terminal_height() { + let mut picker = picker(&["one", "two"]); + for height in 1..=12 { + let frame = picker.render(40, height, false); + assert_eq!(frame.lines.len(), height, "height {height}"); + } + } + + #[test] + fn list_area_scrolls_to_keep_the_selection_visible() { + let entries: Vec = (0..100).map(|n| format!("cmd {n:02}")).collect(); + let mut picker = HistoryPicker::new(entries, ""); + picker.handle(Key::End); + let frame = picker.render(40, 8, false); + let text = body(&frame); + assert!(text.contains("> cmd 00")); + assert_eq!(picker.offset(), 96); + + picker.handle(Key::Home); + let frame = picker.render(40, 8, false); + assert!(body(&frame).contains("> cmd 99")); + assert_eq!(picker.offset(), 0); + } + + #[test] + fn newlines_are_flattened_and_control_characters_dropped() { + let mut picker = picker(&["echo hi\nthere", "esc \x1b[31mred"]); + let frame = picker.render(60, 8, false); + let text = body(&frame); + assert!(text.contains("echo hi \u{23ce} there")); + assert!(!text.contains('\x1b')); + assert!(text.contains("esc [31mred")); + } + + #[test] + fn no_matches_shows_a_message_and_zero_counts() { + let mut picker = picker_with(&["git status"], "zzz"); + let frame = picker.render(50, 8, false); + let text = body(&frame); + assert!(text.contains("no matching commands")); + assert!(text.contains("0/0")); + assert!(text.contains("0/1")); + } + + #[test] + fn empty_history_is_reported_in_the_ui() { + let mut picker = picker(&[]); + let frame = picker.render(50, 8, false); + assert!(body(&frame).contains("no history yet")); + assert_eq!(picker.handle(Key::Enter), Action::Continue); + } + + #[test] + fn header_and_footer_show_counts_and_help() { + let mut picker = picker(&["one", "two", "three"]); + let frame = picker.render(60, 8, false); + assert!(body(&frame).contains("3/3")); + assert!(body(&frame).contains("1/3")); + assert!(body(&frame).contains("enter edit")); + assert!(body(&frame).contains("esc cancel")); + } + + #[test] + fn display_text_sanitizes_each_entry() { + assert_eq!(display_text("a\tb"), "a b"); + assert_eq!(display_text("a\nb"), "a \u{23ce} b"); + assert_eq!(display_text("a\x07b"), "ab"); + assert_eq!(display_text("plain"), "plain"); + } + + #[test] + fn fit_crops_with_an_ellipsis() { + assert_eq!(fit("hello", 10), "hello"); + assert_eq!(fit("hello", 5), "hello"); + assert_eq!(fit("hello", 4), "hel\u{2026}"); + assert_eq!(fit("hello", 1), "\u{2026}"); + assert_eq!(fit("hello", 0), ""); + } + + #[test] + fn visible_width_ignores_escape_sequences() { + assert_eq!(visible_width("plain"), 5); + assert_eq!(visible_width("\x1b[32m➜\x1b[0m ~ $"), 5); + assert_eq!(visible_width("\x1b[1;36mheader\x1b[0m"), 6); + assert_eq!(visible_width(""), 0); + } + + #[test] + fn split_match_finds_ascii_case_insensitively() { + assert_eq!(split_match("Git Status", "git"), ("", "Git", " Status")); + assert_eq!(split_match("run Git now", "GIT"), ("run ", "Git", " now")); + assert_eq!(split_match("nothing", "zzz"), ("nothing", "", "")); + assert_eq!(split_match("anything", ""), ("anything", "", "")); + } +} diff --git a/src/main.rs b/src/main.rs index d257db9..a09aaa7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,10 @@ use anyhow::Result; -use rustyline::highlight::Highlighter; -use rustyline::history::DefaultHistory; -use rustyline::{CompletionType, Config as RLConfig, Editor}; +use rustyline::highlight::{CmdKind, Highlighter}; +use rustyline::history::{DefaultHistory, History, SearchDirection}; +use rustyline::{ + Cmd, CompletionType, ConditionalEventHandler, Config as RLConfig, Editor, Event, EventContext, + EventHandler, KeyCode, KeyEvent, Modifiers, Movement, RepeatCount, +}; use shlex; use std::borrow::Cow; use std::io::{IsTerminal, Write}; @@ -9,10 +12,14 @@ use std::os::fd::{AsRawFd, FromRawFd, RawFd}; #[cfg(unix)] use std::os::unix::process::CommandExt; use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicBool, Ordering}; use aeroshell::{config, packages, registry}; mod commands; +mod history_search; +mod syntax_highlight; use commands::aepkg as aepkg_cmd; use commands::builtins; @@ -107,9 +114,24 @@ fn quiet_exit_code(status: &ExitStatus) -> i32 { status.code().unwrap_or(1) } +#[derive(Clone, Default)] +struct HintState(Arc); + +impl HintState { + fn shown(&self) -> bool { + self.0.load(Ordering::Relaxed) + } + + fn set(&self, shown: bool) { + self.0.store(shown, Ordering::Relaxed); + } +} + // Feeds the (pre-styled) prompt back to rustyline and strips ANSI codes for // width computation, so colored prompts keep correct cursor positioning. -struct AeroHelper; +struct AeroHelper { + hint_state: HintState, +} impl rustyline::completion::Completer for AeroHelper { type Candidate = String; @@ -146,8 +168,126 @@ impl rustyline::completion::Completer for AeroHelper { } impl rustyline::hint::Hinter for AeroHelper { type Hint = String; + + fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option { + let hint = history_suggestion(line, pos, ctx.history(), ctx.history_index()); + self.hint_state.set(hint.is_some()); + hint + } +} + +fn history_suggestion( + line: &str, + pos: usize, + history: &dyn History, + history_index: usize, +) -> Option { + if line.is_empty() || pos < line.len() || line.contains('\n') { + return None; + } + + // While browsing history, stay at or before the entry being edited. + let mut start = if history_index >= history.len() { + history.len().saturating_sub(1) + } else { + history_index + }; + loop { + let found = history + .starts_with(line, start, SearchDirection::Reverse) + .ok() + .flatten()?; + let suffix = &found.entry[line.len()..]; + if !suffix.is_empty() && !suffix.contains('\n') { + return Some(suffix.to_string()); + } + // An exact entry (or a multi-line one) offers nothing to show; try + // the entry before it. + if found.idx == 0 { + return None; + } + start = found.idx - 1; + } +} + +// The line being edited when history search was requested, plus the width of +// any inline hint drawn after it. The line is restored at its original cursor +// position if the picker is cancelled, and the hint width lets the caller know +// whether the interrupted prompt occupied more than one terminal row. +#[derive(Clone, Default)] +struct SearchRequest(Arc>>); + +impl SearchRequest { + fn set(&self, line: &str, pos: usize, hint_len: usize) { + *self.0.lock().expect("search request lock poisoned") = + Some((line.to_string(), pos, hint_len)); + } + + fn take(&self) -> Option<(String, usize, usize)> { + self.0 + .lock() + .expect("search request lock poisoned") + .take() + } + + fn clear(&self) { + *self.0.lock().expect("search request lock poisoned") = None; + } +} + +// Ctrl-R opens the history picker from anywhere on the line. Up does it only +// when a partial command has been typed (so plain Up still browses history on +// an empty prompt, the way it always has). +struct OpenHistorySearch { + request: SearchRequest, + needs_prefix: bool, +} + +impl ConditionalEventHandler for OpenHistorySearch { + fn handle( + &self, + _event: &Event, + _count: RepeatCount, + _positive: bool, + ctx: &EventContext, + ) -> Option { + if self.needs_prefix && ctx.line().trim().is_empty() { + return Some(Cmd::PreviousHistory); + } + let hint_len = ctx.hint_text().map_or(0, |hint| hint.chars().count()); + self.request.set(ctx.line(), ctx.pos(), hint_len); + Some(Cmd::Interrupt) + } +} + +struct AcceptHint { + hint_state: HintState, + fallback: Cmd, +} + +impl ConditionalEventHandler for AcceptHint { + fn handle( + &self, + _event: &Event, + count: RepeatCount, + _positive: bool, + ctx: &EventContext, + ) -> Option { + if self.hint_state.shown() && ctx.pos() == ctx.line().len() { + return Some(Cmd::CompleteHint); + } + Some(match self.fallback { + Cmd::Move(Movement::ForwardChar(_)) => Cmd::Move(Movement::ForwardChar(count)), + ref other => other.clone(), + }) + } } + impl Highlighter for AeroHelper { + fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> { + Cow::Owned(syntax_highlight::highlight(line)) + } + fn highlight_prompt<'b, 's: 'b, 'p: 'b>( &'s self, prompt: &'p str, @@ -155,6 +295,28 @@ impl Highlighter for AeroHelper { ) -> Cow<'b, str> { Cow::Borrowed(prompt) } + + fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> { + Cow::Owned(config::colorize(hint, "autosuggestion")) + } + + fn highlight_candidate<'c>( + &self, + candidate: &'c str, + _completion: CompletionType, + ) -> Cow<'c, str> { + Cow::Owned(config::colorize(candidate, "autosuggestion")) + } + + fn highlight_char(&self, line: &str, pos: usize, kind: CmdKind) -> bool { + // Ask for a repaint when the cursor leaves the end of the line so the + // now-stale suggestion is erased. It stays hidden until an edit makes + // rustyline compute a hint again. + if kind == CmdKind::MoveCursor && self.hint_state.shown() && pos < line.len() { + self.hint_state.set(false); + } + true + } } impl rustyline::validate::Validator for AeroHelper {} impl rustyline::Helper for AeroHelper {} @@ -260,8 +422,44 @@ fn main() -> Result<()> { .build(); let mut rl: Editor = Editor::with_history(rl_config, DefaultHistory::new())?; - // with_history() leaves the helper unset; Tab needs it explicitly. - rl.set_helper(Some(AeroHelper)); + let hint_state = HintState::default(); + rl.set_helper(Some(AeroHelper { + hint_state: hint_state.clone(), + })); + let accept_keys = [ + ( + KeyEvent(KeyCode::Right, Modifiers::NONE), + Cmd::Move(Movement::ForwardChar(1)), + ), + ( + KeyEvent(KeyCode::End, Modifiers::NONE), + Cmd::Move(Movement::EndOfLine), + ), + (KeyEvent::ctrl('E'), Cmd::Move(Movement::EndOfLine)), + (KeyEvent::ctrl('F'), Cmd::Move(Movement::ForwardChar(1))), + ]; + for (key, fallback) in accept_keys { + let _ = rl.bind_sequence( + key, + EventHandler::Conditional(Box::new(AcceptHint { + hint_state: hint_state.clone(), + fallback, + })), + ); + } + let search_request = SearchRequest::default(); + for (key, needs_prefix) in [ + (KeyEvent::ctrl('R'), false), + (KeyEvent(KeyCode::Up, Modifiers::NONE), true), + ] { + let _ = rl.bind_sequence( + key, + EventHandler::Conditional(Box::new(OpenHistorySearch { + request: search_request.clone(), + needs_prefix, + })), + ); + } if let Ok(path) = config::history_path() { let _ = rl.load_history(&path); @@ -275,19 +473,16 @@ fn main() -> Result<()> { let template = config_guard.prompt_template.clone(); let prompt = config::format_prompt(&template); - let mut line = match rl.readline(&prompt) { - Ok(l) => l, - Err(rustyline::error::ReadlineError::Interrupted) => continue, - Err(rustyline::error::ReadlineError::Eof) => { + let mut line = match read_prompt_line(&mut rl, &prompt, &search_request)? { + PromptLine::Line(line) => line, + PromptLine::Interrupted => continue, + PromptLine::Eof => { // Ctrl-D is normal here; EOF from a closed pipe ends input. if std::io::stdin().is_terminal() { continue; } break; } - Err(e) => { - return Err(e.into()); - } }; // An opened heredoc is read from the following lines, up to its @@ -303,6 +498,10 @@ fn main() -> Result<()> { } Err(rustyline::error::ReadlineError::Interrupted) | Err(rustyline::error::ReadlineError::Eof) => { + // Ctrl-R inside a heredoc body cancels the heredoc rather + // than searching; make sure it cannot leak into the next + // prompt's Ctrl-C handling. + search_request.clear(); registry::print_colored( &format!("ash: heredoc '{delimiter}' cancelled"), "warning", @@ -337,6 +536,70 @@ fn main() -> Result<()> { Ok(()) } +// The result of reading at the interactive prompt. +enum PromptLine { + Line(String), + Interrupted, + Eof, +} + +// Read one prompt line, interposing the history picker when Ctrl-R (or Up on +// a partial command) asked for it. A picker accepts a command back into the +// prompt for editing; cancelling restores the line and cursor that were being +// edited before the search. +fn read_prompt_line( + rl: &mut Editor, + prompt: &str, + search: &SearchRequest, +) -> rustyline::Result { + // (text before the cursor, text after it) for the next readline call. + let mut resume: Option<(String, String)> = None; + loop { + let read = match &resume { + Some((left, right)) => rl.readline_with_initial(prompt, (left.as_str(), right.as_str())), + None => rl.readline(prompt), + }; + match read { + Ok(line) => return Ok(PromptLine::Line(line)), + Err(rustyline::error::ReadlineError::Interrupted) => { + let Some((line, pos, hint_len)) = search.take() else { + return Ok(PromptLine::Interrupted); + }; + let entries = history_entries(rl); + let picked = history_search::pick(entries, &line); + history_search::erase_prompt_line(prompt, &line, hint_len); + resume = Some(match picked { + history_search::Picked::Entry(entry) => (entry, String::new()), + history_search::Picked::Cancelled => split_at_cursor(line, pos), + history_search::Picked::Unavailable => { + registry::print_colored("ash: no history to search yet", "warning"); + split_at_cursor(line, pos) + } + }); + } + Err(rustyline::error::ReadlineError::Eof) => return Ok(PromptLine::Eof), + Err(error) => return Err(error), + } + } +} + +// Every in-memory history entry, oldest first. +fn history_entries(rl: &Editor) -> Vec { + rl.history().iter().cloned().collect() +} + +// Split `text` at `pos`, backing up to the nearest character boundary so the +// pair can be handed back to rustyline safely. +fn split_at_cursor(text: String, pos: usize) -> (String, String) { + let mut at = pos.min(text.len()); + while at > 0 && !text.is_char_boundary(at) { + at -= 1; + } + let right = text[at..].to_string(); + let left = text[..at].to_string(); + (left, right) +} + // Run one command line: pipelines joined by `&&`, `||` and `;`, with each // stage's redirections applied. Heredoc bodies are read from the lines that // follow the command, and anything after the last delimiter runs in turn. @@ -1766,6 +2029,7 @@ fn set_default_shell() -> Result<()> { #[cfg(test)] mod tests { use super::*; + use rustyline::hint::Hinter; fn v(items: &[&str]) -> Vec { items.iter().map(|s| s.to_string()).collect() @@ -1989,6 +2253,23 @@ mod tests { assert!(args_error(&["-c"])); } + #[test] + fn split_at_cursor_stays_on_character_boundaries() { + assert_eq!( + split_at_cursor("abc".to_string(), 1), + ("a".to_string(), "bc".to_string()) + ); + assert_eq!( + split_at_cursor("abc".to_string(), 99), + ("abc".to_string(), String::new()) + ); + // Byte 2 is inside "é"; the split backs up to the boundary before it. + assert_eq!( + split_at_cursor("aé".to_string(), 2), + ("a".to_string(), "é".to_string()) + ); + } + fn with_join(join: Option) -> Step { Step { stages: Vec::new(), @@ -2005,4 +2286,62 @@ mod tests { assert!(step_runs_after(&with_join(Some(Join::Semi)), 1)); assert!(step_runs_after(&with_join(None), 1)); } + + fn hint_for(line: &str, pos: usize, entries: &[&str]) -> Option { + let mut history = rustyline::history::MemHistory::new(); + for entry in entries { + history.add(entry).unwrap(); + } + let helper = AeroHelper { + hint_state: HintState::default(), + }; + helper.hint(line, pos, &rustyline::Context::new(&history)) + } + + #[test] + fn history_hint_suggests_the_rest_of_the_newest_match() { + let entries = ["echo old", "echo new"]; + assert_eq!(hint_for("ec", 2, &entries), Some("ho new".into())); + assert_eq!(hint_for("git st", 6, &["git status"]), Some("atus".into())); + } + + #[test] + fn history_hint_stays_out_of_the_way_when_it_has_nothing_to_add() { + let entries = ["echo hi"]; + assert_eq!(hint_for("", 0, &entries), None); + assert_eq!(hint_for("zzz", 3, &entries), None); + assert_eq!(hint_for("ec", 1, &entries), None); // cursor mid-line + assert_eq!(hint_for("ec", 2, &["echo a\necho b"]), None); // multi-line entry + assert_eq!(hint_for("ec", 2, &[]), None); + } + + #[test] + fn history_hint_skips_exact_and_multi_line_entries() { + // The newest entry is an exact match, so an older completion wins. + assert_eq!( + hint_for("echo hi", 7, &["echo hi there", "echo hi"]), + Some(" there".into()) + ); + // A multi-line heredoc entry is skipped, not rendered as a hint. + assert_eq!( + hint_for("ec", 2, &["echo old", "echo a\necho b"]), + Some("ho old".into()) + ); + } + + #[test] + fn moving_off_the_end_marks_the_hint_hidden() { + let helper = AeroHelper { + hint_state: HintState::default(), + }; + let mut history = rustyline::history::MemHistory::new(); + history.add("echo hi").unwrap(); + let ctx = rustyline::Context::new(&history); + + assert_eq!(helper.hint("ec", 2, &ctx), Some("ho hi".into())); + assert!(helper.hint_state.shown()); + assert!(helper.highlight_char("ec", 2, CmdKind::MoveCursor)); + assert!(helper.highlight_char("ec", 1, CmdKind::MoveCursor)); + assert!(!helper.hint_state.shown()); + } } diff --git a/src/syntax_highlight.rs b/src/syntax_highlight.rs new file mode 100644 index 0000000..df5f2b0 --- /dev/null +++ b/src/syntax_highlight.rs @@ -0,0 +1,257 @@ +use crate::config; + +struct Span { + start: usize, + end: usize, + color: &'static str, +} + +pub fn highlight(line: &str) -> String { + let Ok(cfg) = config::active_config() else { + return line.to_owned(); + }; + if !cfg.color { + return line.to_owned(); + } + + render(line, &cfg, &spans(line)) +} + +fn render(line: &str, cfg: &config::Config, spans: &[Span]) -> String { + let reset = cfg + .colors + .get("reset") + .map(String::as_str) + .unwrap_or("\x1b[0m"); + let mut rendered = String::with_capacity(line.len() + spans.len() * 12); + let mut cursor = 0; + for span in spans { + rendered.push_str(&line[cursor..span.start]); + if let Some(color) = cfg.colors.get(span.color).filter(|color| !color.is_empty()) { + rendered.push_str(color); + rendered.push_str(&line[span.start..span.end]); + rendered.push_str(reset); + } else { + rendered.push_str(&line[span.start..span.end]); + } + cursor = span.end; + } + rendered.push_str(&line[cursor..]); + rendered +} + +fn spans(line: &str) -> Vec { + let bytes = line.as_bytes(); + let mut spans = Vec::new(); + let (mut i, mut command, mut redirect_target) = (0, true, false); + + while i < bytes.len() { + if bytes[i].is_ascii_whitespace() { + i += 1; + continue; + } + + let start = i; + if bytes[i] == b'|' || bytes[i] == b';' || starts_with(bytes, i, b"&&") { + i += if starts_with(bytes, i, b"&&") || starts_with(bytes, i, b"||") { + 2 + } else { + 1 + }; + spans.push(Span { + start, + end: i, + color: "syntax_pipe", + }); + command = true; + redirect_target = false; + continue; + } + + let operator = if starts_with(bytes, i, b"&>") { + Some((i + 2, true)) + } else { + let digits_end = (i..bytes.len()) + .find(|&at| !bytes[at].is_ascii_digit()) + .unwrap_or(i); + let op_start = if bytes.get(digits_end) == Some(&b'>') { + digits_end + } else { + i + }; + match bytes.get(op_start) { + Some(b'<' | b'>') => { + let op = bytes[op_start]; + let mut end = op_start + 1; + if bytes.get(end) == Some(&op) { + end += 1; + if op == b'<' && bytes.get(end) == Some(&b'-') { + end += 1; + } + } + let duplicate = op == b'>' + && bytes.get(end) == Some(&b'&') + && bytes.get(end + 1).is_some_and(u8::is_ascii_digit); + if duplicate { + end += 2; + while bytes.get(end).is_some_and(u8::is_ascii_digit) { + end += 1; + } + } + Some((end, !duplicate)) + } + _ => None, + } + }; + if let Some((end, has_target)) = operator { + i = end; + spans.push(Span { + start, + end: i, + color: "syntax_redirect", + }); + redirect_target = has_target; + continue; + } + + let word_start = i; + let mut quote = None; + let mut quote_start = 0; + let mut quoted = Vec::new(); + while i < bytes.len() { + let byte = bytes[i]; + if let Some(delimiter) = quote { + if delimiter == b'"' && byte == b'\\' { + i = next_char(bytes, i + 1); + } else if byte == delimiter { + i += 1; + quoted.push((quote_start, i)); + quote = None; + } else { + i = next_char(bytes, i); + } + } else if byte.is_ascii_whitespace() + || matches!(byte, b'|' | b';' | b'<' | b'>') + || starts_with(bytes, i, b"&&") + || starts_with(bytes, i, b"||") + || starts_with(bytes, i, b"&>") + { + break; + } else if byte == b'\\' { + i = next_char(bytes, i + 1); + } else if matches!(byte, b'\'' | b'"') { + quote = Some(byte); + quote_start = i; + i += 1; + } else { + i = next_char(bytes, i); + } + } + if let Some(_) = quote { + quoted.push((quote_start, i)); + } + if i == word_start { + i = next_char(bytes, i); + } + + let color = if redirect_target { + redirect_target = false; + "syntax_redirect" + } else if command { + command = false; + "syntax_command" + } else { + "syntax_argument" + }; + let mut cursor = word_start; + for (quoted_start, quoted_end) in quoted { + if cursor < quoted_start { + spans.push(Span { + start: cursor, + end: quoted_start, + color, + }); + } + spans.push(Span { + start: quoted_start, + end: quoted_end, + color: "syntax_quote", + }); + cursor = quoted_end; + } + if cursor < i { + spans.push(Span { + start: cursor, + end: i, + color, + }); + } + } + spans +} + +fn starts_with(bytes: &[u8], at: usize, needle: &[u8]) -> bool { + bytes.get(at..at + needle.len()) == Some(needle) +} + +fn next_char(bytes: &[u8], at: usize) -> usize { + if at >= bytes.len() { + return at; + } + at + match bytes[at] { + 0x00..=0x7f => 1, + 0xc0..=0xdf => 2, + 0xe0..=0xef => 3, + _ => 4, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn colors(line: &str) -> Vec<(&str, &str)> { + spans(line) + .iter() + .map(|span| (&line[span.start..span.end], span.color)) + .collect() + } + + #[test] + fn classifies_commands_arguments_quotes_redirects_and_pipelines() { + assert_eq!( + colors("git status | grep 'work tree'"), + vec![ + ("git", "syntax_command"), + ("status", "syntax_argument"), + ("|", "syntax_pipe"), + ("grep", "syntax_command"), + ("'work tree'", "syntax_quote"), + ] + ); + assert_eq!( + colors("cat < input >> output"), + vec![ + ("cat", "syntax_command"), + ("<", "syntax_redirect"), + ("input", "syntax_redirect"), + (">>", "syntax_redirect"), + ("output", "syntax_redirect"), + ] + ); + } + + #[test] + fn styles_segments_without_changing_input() { + let line = "echo pre'fixed'"; + let mut cfg = config::default_config(); + cfg.colors.insert("syntax_command".into(), "".into()); + cfg.colors.insert("syntax_argument".into(), "".into()); + cfg.colors.insert("syntax_quote".into(), "".into()); + cfg.colors.insert("reset".into(), "".into()); + assert_eq!( + render(line, &cfg, &spans(line)), + "echo pre'fixed'" + ); + } +} From 1f80b19f62bbeef4ca76417eacdcfa3c54784c41 Mon Sep 17 00:00:00 2001 From: AsumiChan Date: Sun, 25 Oct 2026 10:37:44 -0400 Subject: [PATCH 2/2] Fix arrow direction in the upward history popup (#24) The list is drawn in reverse when the popup sits above the prompt, so map Up/Down and PageUp/PageDown to the visual direction while that layout is active. The downward layout keeps its existing mapping. --- src/history_search.rs | 916 +++++++++++++++++++++++++++++++----------- src/main.rs | 5 +- 2 files changed, 688 insertions(+), 233 deletions(-) diff --git a/src/history_search.rs b/src/history_search.rs index bdacb2b..f8f1dad 100644 --- a/src/history_search.rs +++ b/src/history_search.rs @@ -1,18 +1,23 @@ -//! A searchable, navigable history picker. +//! A compact, searchable history popup for the prompt. //! //! The REPL hands control here when the user asks for history search (Ctrl-R, -//! or Up on a partial command). The picker filters the whole history as the -//! query is typed, moves through the matches with the arrow keys, and hands -//! the chosen command back to the prompt for editing. +//! or Up on a partial command). Instead of taking over the screen, the picker +//! draws a small popup at the prompt: up to five matching commands and one +//! search/status line. The popup opens downwards when there is room below the +//! prompt; at the bottom of the screen it scrolls recent output up just enough +//! to fit above the prompt, which stays visible below it. It is removed again +//! when a command is picked or the search is cancelled. //! -//! The state machine and drawing are kept apart from the terminal layer -//! (`pick`) so matching, navigation and layout can be tested without a TTY. +//! The state machine and drawing are kept apart from the terminal layer so +//! matching, navigation and layout can be tested without a TTY. +use std::collections::VecDeque; use std::io::{self, IsTerminal, Write}; +use std::time::{Duration, Instant}; use aeroshell::config; -// Terminal styling for the picker itself, independent of the prompt theme. +// Terminal styling for the popup itself, independent of the prompt theme. const RESET: &str = "\x1b[0m"; const BOLD: &str = "\x1b[1m"; const DIM: &str = "\x1b[2m"; @@ -21,6 +26,9 @@ const REVERSE_OFF: &str = "\x1b[27m"; const MATCH_ON: &str = "\x1b[1;4m"; const MATCH_OFF: &str = "\x1b[22;24m"; +/// The popup shows up to this many matching commands, plus its query line. +const MAX_MATCH_ROWS: usize = 5; + /// What the user asked for with one keystroke. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Key { @@ -65,15 +73,22 @@ impl Row { } } -/// One rendered picker frame. +/// One rendered popup frame. #[derive(Debug, PartialEq, Eq)] -pub struct Frame { - pub lines: Vec, - /// Zero-based (row, column) where the terminal cursor belongs. - pub cursor: (usize, usize), +pub struct PopupFrame { + /// The search/status line. + pub query: String, + /// Zero-based column where the terminal cursor belongs on the query line. + pub cursor_col: usize, + /// Match rows, top to bottom. Always exactly as many as the popup asked + /// for; unused rows are blank. + pub rows: Vec, + /// Whether the list grows upwards towards the old output (query at the + /// bottom, just above the prompt). + pub upward: bool, } -/// The picker's state machine: query, matches, selection and scrolling. +/// The popup's state machine: query, matches, selection and scrolling. pub struct HistoryPicker { rows: Vec, matching: Vec, @@ -98,7 +113,7 @@ impl HistoryPicker { query: initial.to_string(), selected: 0, offset: 0, - page: 10, + page: 1, }; picker.refilter(); picker @@ -220,108 +235,118 @@ impl HistoryPicker { self.move_selection(step); } - /// Draw one frame. `height` includes the header, query line, separator and - /// footer; whatever is left is the scrolling match window. Visible lines - /// never exceed `width` columns, so the frame cannot wrap and damage the - /// full-screen layout. - pub fn render(&mut self, width: usize, height: usize, color: bool) -> Frame { + /// Draw the match area and query line. `match_rows` is the number of + /// matching commands the popup has room for; the query/status line is + /// drawn separately by the caller. `upward` reverses the visual order so + /// the newest visible match sits closest to the query line at the bottom. + pub fn frame( + &mut self, + width: usize, + match_rows: usize, + upward: bool, + color: bool, + ) -> PopupFrame { let width = width.max(1); - let height = height.max(1); - - let mut lines: Vec = Vec::with_capacity(height); - if height >= 4 { - lines.push(self.header_line(width, color)); - } - let query_row = lines.len(); - let (query_line, cursor_col) = self.query_line(width, color); - lines.push(query_line); - if height >= 3 { - lines.push(self.separator_line(width, color)); - } + let match_rows = match_rows.max(1); + self.page = match_rows; + self.ensure_visible(match_rows); - let footer_reserved = height > lines.len(); - let list_rows = height.saturating_sub(lines.len() + usize::from(footer_reserved)); - self.page = list_rows; - - if list_rows > 0 { - self.ensure_visible(list_rows); - let mut drawn = 0; - for slot in 0..list_rows { - if let Some(&index) = self.matching.get(self.offset + slot) { - let selected = self.offset + slot == self.selected; - lines.push(self.row_line(&self.rows[index], selected, width, color)); - drawn += 1; - } else if slot == 0 && self.matching.is_empty() { - let message = if self.rows.is_empty() { - " no history yet" - } else { - " no matching commands" - }; - lines.push(style(fit(message, width), DIM, color)); - drawn += 1; - } else { - break; - } + let mut rows: Vec = if self.matching.is_empty() { + let message = if self.rows.is_empty() { + " no history yet" + } else { + " no matching commands" + }; + let message = style(fit(message, width), DIM, color); + let mut rows = vec![String::new(); match_rows]; + if upward { + rows[match_rows - 1] = message; + } else { + rows[0] = message; } - // Keep the frame exactly `height` rows so nothing stale is left - // behind when a later frame is shorter. - for _ in drawn..list_rows { - lines.push(String::new()); + rows + } else { + let end = (self.offset + match_rows).min(self.matching.len()); + let mut lines: Vec = (self.offset..end) + .map(|matching_index| { + let row = &self.rows[self.matching[matching_index]]; + self.row_line(row, matching_index == self.selected, width, color) + }) + .collect(); + if upward { + lines.reverse(); + let mut padded = vec![String::new(); match_rows - lines.len()]; + padded.extend(lines); + padded + } else { + lines.resize(match_rows, String::new()); + lines } - } - - if footer_reserved { - lines.push(self.footer_line(width, color)); - } - while lines.len() < height { - lines.push(String::new()); - } - lines.truncate(height); + }; + rows.truncate(match_rows); - Frame { - lines, - cursor: (query_row, cursor_col), + let (query, cursor_col) = self.query_line(width, color); + PopupFrame { + query, + cursor_col, + rows, + upward, } } - fn ensure_visible(&mut self, list_rows: usize) { - let list_rows = list_rows.max(1); + fn ensure_visible(&mut self, match_rows: usize) { + let match_rows = match_rows.max(1); if self.selected < self.offset { self.offset = self.selected; } - if self.selected >= self.offset + list_rows { - self.offset = self.selected + 1 - list_rows; + if self.selected >= self.offset + match_rows { + self.offset = self.selected + 1 - match_rows; } - let max_offset = self.matching.len().saturating_sub(list_rows); + let max_offset = self.matching.len().saturating_sub(match_rows); self.offset = self.offset.min(max_offset); } - fn header_line(&self, width: usize, color: bool) -> String { - let title = " Ash history search "; - let counts = format!("{}/{} ", self.matching.len(), self.rows.len()); - if title.chars().count() + counts.chars().count() <= width { - let padding = width - title.chars().count() - counts.chars().count(); - style( - format!("{title}{}{counts}", " ".repeat(padding)), - BOLD, - color, - ) - } else { - style(fit(&format!("{title}{counts}"), width), BOLD, color) - } - } - + /// `> query` on the left and the position/help on the right. The query is + /// cropped from the left when it is too long for the space available. fn query_line(&self, width: usize, color: bool) -> (String, usize) { let prefix = if width >= 2 { "> " } else { "" }; - let available = width - prefix.chars().count(); + let prefix_width = prefix.chars().count(); + let position = if self.matching.is_empty() { + "0/0".to_string() + } else { + format!("{}/{}", self.selected + 1, self.matching.len()) + }; + let mut status = if width >= 36 { + format!("{position} \u{2191}\u{2193} enter esc") + } else if width >= 10 { + position + } else { + String::new() + }; + let mut status_width = status.chars().count(); + // Keep at least one column between the query and the status. + if status_width > 0 && width <= prefix_width + status_width + 1 { + status.clear(); + status_width = 0; + } + let reserved = if status_width > 0 { + status_width + 1 + } else { + 0 + }; + let available = width.saturating_sub(prefix_width + reserved); let total = self.query.chars().count(); let shown: String = if total <= available { self.query.clone() + } else if available == 0 { + String::new() } else { - // Keep the end of a long query visible, like a text field. self.query.chars().skip(total - available).collect() }; - let cursor = (prefix.chars().count() + shown.chars().count()).min(width - 1); + let shown_width = shown.chars().count(); + let left_width = prefix_width + shown_width; + let gap = width.saturating_sub(left_width + status_width); + let mut line = String::new(); if color && !prefix.is_empty() { line.push_str(BOLD); @@ -331,24 +356,14 @@ impl HistoryPicker { line.push_str(prefix); } line.push_str(&shown); + line.push_str(&" ".repeat(gap)); + if !status.is_empty() { + line.push_str(&style(status, DIM, color)); + } + let cursor = left_width.min(width.saturating_sub(1)); (line, cursor) } - fn separator_line(&self, width: usize, color: bool) -> String { - style("─".repeat(width), DIM, color) - } - - fn footer_line(&self, width: usize, color: bool) -> String { - let position = if self.matching.is_empty() { - "0/0".to_string() - } else { - format!("{}/{}", self.selected + 1, self.matching.len()) - }; - let text = - format!(" {position} \u{2191}\u{2193} move \u{00b7} enter edit \u{00b7} esc cancel"); - style(fit(&text, width), DIM, color) - } - fn row_line(&self, row: &Row, selected: bool, width: usize, color: bool) -> String { // One column is enough for the selection marker on very narrow // terminals; two keep the text aligned when there is room. @@ -398,27 +413,54 @@ pub enum Picked { Unavailable, } -/// Run the picker on the terminal. Returns `Unavailable` when there is nothing -/// to search or stdin/stdout are not a TTY, so the caller can keep the normal -/// prompt without opening an empty screen. -pub fn pick(entries: Vec, initial: &str) -> Picked { - if entries.is_empty() || !io::stdin().is_terminal() || !io::stdout().is_terminal() { +/// Run the popup on the terminal. Returns `Unavailable` when stdin/stdout are +/// not a TTY or the terminal is too small to show even one match, so the +/// caller can keep the normal prompt. +pub fn pick(entries: Vec, initial: &str, prompt: &str, hint_len: usize) -> Picked { + if !io::stdin().is_terminal() || !io::stdout().is_terminal() { return Picked::Unavailable; } let Some(mut terminal) = Terminal::enter() else { return Picked::Unavailable; }; + let (width, height) = terminal_size(); + if width < 2 || height < 2 { + return Picked::Unavailable; + } + + // Leave one row for the query line. The prompt itself already has the row + // it was drawn on, so the popup may use up to `height - 1` match rows. + let match_rows = (height - 2).clamp(1, MAX_MATCH_ROWS); + // After rustyline finishes interrupting the line it leaves the cursor on + // the row below the prompt. Ask the terminal where that is; when it does + // not answer, assume the prompt is at the bottom (one row above the + // cursor). + let cursor_row = terminal.cursor_position().map_or(height, |(row, _)| row); + let last_prompt_row = prompt_row_from_cursor(cursor_row, height); + // A long prompt (or a hint) can wrap over several rows. Anchor the popup + // on the first one and clear the whole block, so the resumed prompt does + // not leave a stale first line behind. + let prompt_rows = prompt_height(prompt, initial, hint_len, width); + let prompt_row = last_prompt_row.saturating_sub(prompt_rows - 1); + let layout = layout(height, prompt_row, match_rows); + let prompt_display = format!("{prompt}{initial}"); + if !terminal.setup(layout, prompt_row, prompt_rows, height, &prompt_display) { + return Picked::Unavailable; + } + let color = config::active_config().map(|cfg| cfg.color).unwrap_or(true); let mut picker = HistoryPicker::new(entries, initial); loop { - let (width, height) = terminal_size(); - let frame = picker.render(width, height, color); + let frame = picker.frame(width, match_rows, layout.upward, color); if terminal.draw(&frame).is_err() { return Picked::Cancelled; } let Ok(key) = terminal.read_key() else { return Picked::Cancelled; }; + // In the upward layout the list is drawn in reverse, so the same + // physical key has to move the selection the other way. + let key = orient_key(key, layout.upward); match picker.handle(key) { Action::Continue => {} Action::Accept(entry) => return Picked::Entry(entry), @@ -427,44 +469,123 @@ pub fn pick(entries: Vec, initial: &str) -> Picked { } } -/// Clear the prompt line that the picker interrupted, so the resumed prompt -/// replaces it instead of leaving a stale copy in the transcript. Only acts -/// when the prompt and its text fit on one terminal row; a wrapped or -/// multi-line edit is left exactly as the line editor drew it. -pub fn erase_prompt_line(prompt: &str, line: &str, hint_len: usize) { - if line.contains('\n') || prompt.contains('\n') { - return; - } - let (width, _) = terminal_size(); - if visible_width(prompt) + line.chars().count() + hint_len >= width { - return; - } - let mut stdout = io::stdout(); - let _ = stdout.write_all(b"\x1b[1A\r\x1b[2K"); - let _ = stdout.flush(); +/// Where the popup's rows live and whether the screen had to scroll. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Layout { + /// Matches above the query line (the screen was scrolled up to make room). + upward: bool, + /// The prompt is left below the popup and has to be redrawn while the + /// picker is open. + prompt_visible: bool, + /// Lines the screen was scrolled up by; undone when the popup closes. + scrolled: usize, + /// First and last (inclusive) terminal row covered by the popup. + popup_start: usize, + popup_end: usize, + /// Row of the query/status line. + query_row: usize, + /// First row of the match area. + match_start: usize, } -/// Width of `text` on screen, ignoring ANSI escape sequences. -fn visible_width(text: &str) -> usize { - let mut width = 0; +/// Number of terminal rows taken by the prompt, the text being edited and the +/// inline hint that follows it. ANSI colour sequences do not take space. +fn prompt_height(prompt: &str, line: &str, hint_len: usize, width: usize) -> usize { + if width == 0 { + return 1; + } + let mut rows = 1usize; + let mut column = 0usize; let mut escape = false; - for character in text.chars() { + for character in prompt.chars().chain(line.chars()) { if escape { if character.is_ascii_alphabetic() { escape = false; } } else if character == '\x1b' { escape = true; + } else if character == '\n' { + rows += 1; + column = 0; } else { - width += 1; + column += 1; + while column > width { + rows += 1; + column -= width; + } + } + } + column += hint_len; + while column > width { + rows += 1; + column -= width; + } + rows +} + +/// Convert the 1-based cursor row reported by the terminal into the 0-based +/// row of the prompt that was just interrupted. Rustyline prints a newline +/// after the interrupted prompt, leaving the cursor one row below it; the +/// other row is the 1-based to 0-based conversion. +fn prompt_row_from_cursor(cursor_row: usize, height: usize) -> usize { + cursor_row.saturating_sub(2).min(height.saturating_sub(1)) +} + +/// Work out where a `match_rows`-tall list plus its query line can go without +/// covering any more output than necessary. Rows are zero-based. +fn layout(height: usize, prompt_row: usize, match_rows: usize) -> Layout { + let popup_rows = match_rows + 1; + if prompt_row + popup_rows <= height { + // There is room below the prompt: replace the prompt line with the + // query and grow downwards. + Layout { + upward: false, + prompt_visible: false, + scrolled: 0, + popup_start: prompt_row, + popup_end: prompt_row + match_rows, + query_row: prompt_row, + match_start: prompt_row + 1, + } + } else if prompt_row >= popup_rows { + // Near the bottom: scroll the output up so the whole popup fits above + // the prompt, then redraw the prompt below it. The prompt stays where + // the user left it and the matches are above the search line. + Layout { + upward: true, + prompt_visible: true, + scrolled: popup_rows, + popup_start: prompt_row - popup_rows, + popup_end: prompt_row - 1, + query_row: prompt_row - 1, + match_start: prompt_row - popup_rows, + } + } else { + // Tiny terminal: there is no room for both the popup and the prompt. + // Fall back to scrolling the prompt out of the way and putting the + // query line at the bottom. + let start = height - 1 - match_rows; + let scrolled = prompt_row.saturating_sub(start); + Layout { + upward: true, + prompt_visible: false, + scrolled, + popup_start: start, + popup_end: height - 1, + query_row: height - 1, + match_start: start, } } - width } -/// Raw mode plus the alternate screen, restored on drop (including panics). +/// Raw mode and a hidden cursor, restored on drop (including panics). struct Terminal { original: libc::termios, + geometry: Option, + prompt_row: usize, + prompt_rows: usize, + /// Bytes read while waiting for a cursor-position reply, replayed as keys. + pending: VecDeque, } impl Terminal { @@ -475,28 +596,124 @@ impl Terminal { } let mut raw = original; unsafe { libc::cfmakeraw(&mut raw) }; - if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &raw) } != 0 { + // Do not flush pending input: a fast typist may already have typed the + // first letters of the query while the popup was opening. Those bytes + // are replayed through `pending` after the cursor-position query. + if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &raw) } != 0 { return None; } + let _ = io::stdout().write_all(b"\x1b[?25l"); + let _ = io::stdout().flush(); + Some(Self { + original, + geometry: None, + prompt_row: 0, + prompt_rows: 0, + pending: VecDeque::new(), + }) + } + + /// Ask the terminal for the cursor position (`CSI 6n`). Best effort: if + /// nothing sensible comes back within a short window, the caller falls + /// back to assuming the prompt is at the bottom of the screen. + fn cursor_position(&mut self) -> Option<(usize, usize)> { let mut stdout = io::stdout(); - let _ = stdout.write_all(b"\x1b[?1049h\x1b[?25l\x1b[H\x1b[2J"); - let _ = stdout.flush(); - Some(Self { original }) + stdout.write_all(b"\x1b[6n").ok()?; + stdout.flush().ok()?; + + let deadline = Instant::now() + Duration::from_millis(120); + let mut bytes = Vec::new(); + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + break; + } + let timeout = (remaining.as_millis().min(20)) as i32; + if !wait_readable(timeout) { + continue; + } + let Ok(byte) = read_byte() else { + break; + }; + bytes.push(byte); + if byte == b'R' { + break; + } + } + if let Some((start, position)) = cursor_reply(&bytes) { + // Anything read before the reply is user input; keep it for the + // picker instead of dropping the first characters typed. + for byte in bytes[..start].iter().rev() { + self.pending.push_front(*byte); + } + return Some(position); + } + for byte in bytes.into_iter().rev() { + self.pending.push_front(byte); + } + None + } + + /// Scroll (if needed), remember the popup geometry, and clear the rows it + /// will occupy as well as any remaining rows of a wrapped prompt. + fn setup( + &mut self, + layout: Layout, + prompt_row: usize, + prompt_rows: usize, + height: usize, + prompt_display: &str, + ) -> bool { + if layout.scrolled > 0 { + let mut stdout = io::stdout(); + if stdout + .write_all(format!("\x1b[{}S", layout.scrolled).as_bytes()) + .and_then(|()| stdout.flush()) + .is_err() + { + return false; + } + } + self.geometry = Some(layout); + self.prompt_row = prompt_row; + self.prompt_rows = prompt_rows; + let end = layout + .popup_end + .max(prompt_row + prompt_rows - 1) + .min(height - 1); + let mut out = String::new(); + for row in layout.popup_start..=end { + out.push_str(&format!("\x1b[{};1H\x1b[2K", row + 1)); + } + if layout.prompt_visible { + out.push_str(&format!("\x1b[{};1H\x1b[2K", prompt_row + 1)); + out.push_str(prompt_display); + } + let mut stdout = io::stdout(); + stdout + .write_all(out.as_bytes()) + .and_then(|()| stdout.flush()) + .is_ok() } - fn draw(&mut self, frame: &Frame) -> io::Result<()> { - let mut out = String::from("\x1b[?25l\x1b[H"); - for (index, line) in frame.lines.iter().enumerate() { - out.push_str("\x1b[2K"); - out.push_str(line); - if index + 1 < frame.lines.len() { - out.push_str("\r\n"); - } + fn draw(&mut self, frame: &PopupFrame) -> io::Result<()> { + let Some(layout) = self.geometry else { + return Ok(()); + }; + let mut out = String::from("\x1b[?25l"); + for (offset, line) in frame.rows.iter().enumerate() { + let row = layout.match_start + offset; + out.push_str(&format!("\x1b[{};1H\x1b[2K{line}", row + 1)); } + out.push_str(&format!( + "\x1b[{};1H\x1b[2K{}", + layout.query_row + 1, + frame.query + )); out.push_str(&format!( "\x1b[{};{}H\x1b[?25h", - frame.cursor.0 + 1, - frame.cursor.1 + 1 + layout.query_row + 1, + frame.cursor_col + 1 )); let mut stdout = io::stdout(); stdout.write_all(out.as_bytes())?; @@ -504,7 +721,7 @@ impl Terminal { } fn read_key(&mut self) -> io::Result { - let byte = read_byte()?; + let byte = self.next_byte()?; match byte { b'\x1b' => self.read_escape(), 0x03 | 0x07 | 0x04 => Ok(Key::Cancel), // Ctrl-C, Ctrl-G, Ctrl-D @@ -521,13 +738,11 @@ impl Terminal { } } - /// Parse the rest of an escape sequence. A lone Esc cancels; terminal - /// arrows and paging keys arrive as CSI/SS3 sequences. fn read_escape(&mut self) -> io::Result { - if !wait_readable(20) { + if self.pending.is_empty() && !wait_readable(20) { return Ok(Key::Cancel); } - let first = read_byte()?; + let first = self.next_byte()?; match first { b'[' => { let mut sequence = vec![b'[']; @@ -535,7 +750,7 @@ impl Terminal { if sequence.len() > 8 { return Ok(Key::Ignore); } - let byte = read_byte()?; + let byte = self.next_byte()?; sequence.push(byte); if (0x40..=0x7e).contains(&byte) { break; @@ -552,7 +767,7 @@ impl Terminal { }) } b'O' => { - let byte = read_byte()?; + let byte = self.next_byte()?; Ok(match byte { b'A' => Key::Up, b'B' => Key::Down, @@ -574,26 +789,89 @@ impl Terminal { }; let mut bytes = vec![first]; for _ in 0..extra { - bytes.push(read_byte()?); + bytes.push(self.next_byte()?); } Ok(std::str::from_utf8(&bytes) .ok() .and_then(|text| text.chars().next()) .map_or(Key::Ignore, Key::Char)) } + + fn next_byte(&mut self) -> io::Result { + match self.pending.pop_front() { + Some(byte) => Ok(byte), + None => read_byte(), + } + } + + /// Remove the popup, undo the scroll, and put the cursor where the prompt + /// should be redrawn. + fn cleanup(&mut self) { + let Some(layout) = self.geometry.take() else { + let _ = io::stdout().write_all(b"\x1b[?25h"); + let _ = io::stdout().flush(); + return; + }; + let mut out = String::new(); + for row in layout.popup_start..=layout.popup_end { + out.push_str(&format!("\x1b[{};1H\x1b[2K", row + 1)); + } + if layout.prompt_visible { + for row in self.prompt_row..self.prompt_row + self.prompt_rows { + out.push_str(&format!("\x1b[{};1H\x1b[2K", row + 1)); + } + } + if layout.scrolled > 0 { + out.push_str(&format!("\x1b[{}T", layout.scrolled)); + } + out.push_str(&format!("\x1b[{};1H\x1b[2K\x1b[?25h", self.prompt_row + 1)); + let mut stdout = io::stdout(); + let _ = stdout.write_all(out.as_bytes()); + let _ = stdout.flush(); + } } impl Drop for Terminal { fn drop(&mut self) { - let mut stdout = io::stdout(); - let _ = stdout.write_all(b"\x1b[?25h\x1b[?1049l"); - let _ = stdout.flush(); + self.cleanup(); unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &self.original); } } } +/// Locate a cursor-position reply inside the bytes read while waiting for it. +/// Returns the reply's offset and `(row, column)`; any bytes before it are +/// typed input that still has to be handled. +fn cursor_reply(bytes: &[u8]) -> Option<(usize, (usize, usize))> { + for start in 0..bytes.len() { + if bytes[start] == 0x1b + && bytes.get(start + 1) == Some(&b'[') + && let Some(position) = parse_cursor_position(&bytes[start..]) + { + return Some((start, position)); + } + } + None +} + +fn parse_cursor_position(bytes: &[u8]) -> Option<(usize, usize)> { + let mut index = 0; + while index + 2 < bytes.len() { + if bytes[index] == 0x1b && bytes[index + 1] == b'[' { + let rest = &bytes[index + 2..]; + let end = rest.iter().position(|&byte| byte == b'R')?; + let body = std::str::from_utf8(&rest[..end]).ok()?; + let (row, column) = body.split_once(';')?; + let row = row.parse().ok()?; + let column = column.parse().ok()?; + return Some((row, column)); + } + index += 1; + } + None +} + fn terminal_size() -> (usize, usize) { #[cfg(unix)] { @@ -643,6 +921,22 @@ fn wait_readable(timeout_ms: i32) -> bool { } } +/// Map vertical movement keys to the visual direction of the popup. The +/// downward layout draws the newest match at the top; the upward layout draws +/// it at the bottom, directly above the query line. +fn orient_key(key: Key, upward: bool) -> Key { + if !upward { + return key; + } + match key { + Key::Up => Key::Down, + Key::Down => Key::Up, + Key::PageUp => Key::PageDown, + Key::PageDown => Key::PageUp, + other => other, + } +} + /// The searchable, printable form of a stored command: newlines become a /// visible marker, tabs become spaces, and other control characters (which /// could otherwise inject terminal escapes) are dropped. @@ -743,9 +1037,9 @@ mod tests { out } - fn body(frame: &Frame) -> String { + fn body(frame: &PopupFrame) -> String { frame - .lines + .rows .iter() .map(|line| plain(line)) .collect::>() @@ -758,10 +1052,10 @@ mod tests { assert_eq!(picker.match_count(), 3); assert_eq!(picker.selected_entry(), Some("new")); - let frame = picker.render(40, 8, false); - let text = body(&frame); - assert!(text.find("new").unwrap() < text.find("middle").unwrap()); - assert!(text.find("middle").unwrap() < text.find("old").unwrap()); + let frame = picker.frame(40, 3, false, false); + assert!(plain(&frame.rows[0]).starts_with("> new")); + assert!(plain(&frame.rows[1]).starts_with(" middle")); + assert!(plain(&frame.rows[2]).starts_with(" old")); } #[test] @@ -787,6 +1081,17 @@ mod tests { assert_eq!(entries, vec!["git status", "legit", "echo git"]); } + #[test] + fn upward_layout_flips_vertical_keys() { + assert_eq!(orient_key(Key::Up, true), Key::Down); + assert_eq!(orient_key(Key::Down, true), Key::Up); + assert_eq!(orient_key(Key::PageUp, true), Key::PageDown); + assert_eq!(orient_key(Key::PageDown, true), Key::PageUp); + assert_eq!(orient_key(Key::Up, false), Key::Up); + assert_eq!(orient_key(Key::PageDown, false), Key::PageDown); + assert_eq!(orient_key(Key::Home, true), Key::Home); + } + #[test] fn navigation_stops_at_the_ends() { let mut picker = picker(&["one", "two", "three"]); @@ -806,16 +1111,16 @@ mod tests { fn page_and_home_end_keys_move_selection() { let entries: Vec = (0..30).map(|n| format!("entry {n}")).collect(); let mut picker = HistoryPicker::new(entries, ""); - // Height 10 leaves six list rows: header, query, separator, footer. - picker.render(40, 10, false); - assert_eq!(picker.page, 6); + // Five match rows plus the query line is the usual popup size. + picker.frame(40, 5, false, false); + assert_eq!(picker.page, 5); picker.handle(Key::PageDown); - assert_eq!(picker.selected(), 6); + assert_eq!(picker.selected(), 5); picker.handle(Key::PageDown); - assert_eq!(picker.selected(), 12); + assert_eq!(picker.selected(), 10); picker.handle(Key::PageUp); - assert_eq!(picker.selected(), 6); + assert_eq!(picker.selected(), 5); picker.handle(Key::End); assert_eq!(picker.selected(), 29); picker.handle(Key::Home); @@ -826,10 +1131,10 @@ mod tests { fn changing_the_query_resets_selection_and_scroll() { let entries: Vec = (0..30).map(|n| format!("cmd {n}")).collect(); let mut picker = HistoryPicker::new(entries, ""); - picker.render(40, 10, false); + picker.frame(40, 5, false, false); picker.handle(Key::PageDown); - assert_eq!(picker.selected(), 6); - picker.render(40, 10, false); + assert_eq!(picker.selected(), 5); + picker.frame(40, 5, false, false); assert_eq!(picker.offset(), 1); picker.handle(Key::Char('c')); @@ -894,19 +1199,55 @@ mod tests { assert_eq!(picker(&["one"]).handle(Key::Cancel), Action::Cancel); } + #[test] + fn downward_frame_puts_the_newest_match_first() { + let mut picker = picker(&["old", "middle", "new"]); + let frame = picker.frame(40, 3, false, false); + assert!(!frame.upward); + assert!(plain(&frame.rows[0]).starts_with("> new")); + assert!(plain(&frame.rows[1]).starts_with(" middle")); + assert!(plain(&frame.rows[2]).starts_with(" old")); + } + + #[test] + fn upward_frame_puts_the_newest_match_nearest_the_query() { + let mut picker = picker(&["old", "middle", "new"]); + let frame = picker.frame(40, 3, true, false); + assert!(frame.upward); + // Rows are top-to-bottom; the selected/newest entry is at the bottom, + // closest to the query line. + assert!(plain(&frame.rows[0]).starts_with(" old")); + assert!(plain(&frame.rows[1]).starts_with(" middle")); + assert!(plain(&frame.rows[2]).starts_with("> new")); + } + + #[test] + fn unused_match_rows_are_padded_away_from_the_query() { + let mut picker = picker(&["one", "two"]); + let downward = picker.frame(40, 4, false, false); + assert_eq!(plain(&downward.rows[2]), ""); + assert_eq!(plain(&downward.rows[3]), ""); + + let upward = picker.frame(40, 4, true, false); + assert_eq!(plain(&upward.rows[0]), ""); + assert_eq!(plain(&upward.rows[1]), ""); + assert!(plain(&upward.rows[2]).starts_with(" one")); + assert!(plain(&upward.rows[3]).starts_with("> two")); + } + #[test] fn render_marks_the_selected_row_and_highlights_the_query() { let mut picker = picker(&["git status", "git log"]); for character in "git".chars() { picker.handle(Key::Char(character)); } - let frame = picker.render(60, 8, true); - let selected = &frame.lines[3]; + let frame = picker.frame(60, 2, false, true); + let selected = &frame.rows[0]; assert!(selected.contains(REVERSE)); assert!(selected.contains(MATCH_ON)); assert!(plain(selected).starts_with("> git log")); - let unselected = &frame.lines[4]; + let unselected = &frame.rows[1]; assert!(!unselected.contains(REVERSE)); assert!(plain(unselected).starts_with(" git status")); } @@ -914,10 +1255,16 @@ mod tests { #[test] fn color_free_render_uses_a_marker_for_selection() { let mut picker = picker(&["git status", "git log"]); - let frame = picker.render(60, 8, false); - assert!(!frame.lines.iter().any(|line| line.contains('\x1b'))); - assert!(frame.lines[3].starts_with("> git log")); - assert!(frame.lines[4].starts_with(" git status")); + for upward in [false, true] { + let frame = picker.frame(60, 2, upward, false); + assert!(!frame.rows.iter().any(|line| line.contains('\x1b'))); + let selected = if upward { + &frame.rows[1] + } else { + &frame.rows[0] + }; + assert!(selected.starts_with("> git log")); + } } #[test] @@ -926,36 +1273,62 @@ mod tests { let mut picker = picker(&[long.as_str(), "short"]); picker.handle(Key::Char('x')); for width in [1, 2, 5, 20, 79] { - let frame = picker.render(width, 10, true); - for line in &frame.lines { + for upward in [false, true] { + let frame = picker.frame(width, 5, upward, true); assert!( - plain(line).chars().count() <= width, - "line {line:?} exceeds width {width}" + plain(&frame.query).chars().count() <= width, + "query {frame:?} exceeds width {width}" ); + for line in &frame.rows { + assert!( + plain(line).chars().count() <= width, + "line {line:?} exceeds width {width}" + ); + } + assert!(frame.cursor_col < width.max(1)); } - assert!(frame.cursor.1 < width.max(1)); } } #[test] - fn long_queries_show_their_tail() { - let mut picker = picker(&["unrelated"]); + fn query_line_shows_position_and_help() { + let mut picker = picker(&["one", "two", "three"]); + let wide = picker.frame(60, 3, false, false); + assert!(plain(&wide.query).contains("1/3")); + assert!(plain(&wide.query).contains("enter")); + assert!(plain(&wide.query).contains("esc")); + + let medium = picker.frame(14, 3, false, false); + assert!(plain(&medium.query).contains("1/3")); + assert!(!plain(&medium.query).contains("enter")); + + let narrow = picker.frame(8, 3, false, false); + assert_eq!(plain(&narrow.query).chars().count(), 8); + } + + #[test] + fn query_line_keeps_the_tail_of_a_long_query() { + let mut picker = picker(&["abcdefghijklmnopqrstuvwxyz"]); for character in "abcdefghijklmnopqrstuvwxyz".chars() { picker.handle(Key::Char(character)); } - let frame = picker.render(12, 6, false); - let query_line = plain(&frame.lines[1]); - assert!(query_line.starts_with("> ")); - assert!(query_line.ends_with("xyz")); - assert_eq!(frame.cursor, (1, 11)); + let frame = picker.frame(12, 4, false, false); + let query = plain(&frame.query); + // Six columns are left for the query after the prompt and the 1/1 + // status; the tail of the query is what stays visible. + assert!(query.starts_with("> uvwxyz")); + assert!(query.ends_with("1/1")); + assert_eq!(frame.cursor_col, 8); } #[test] - fn frames_are_exactly_the_terminal_height() { + fn frames_are_exactly_as_tall_as_requested() { let mut picker = picker(&["one", "two"]); - for height in 1..=12 { - let frame = picker.render(40, height, false); - assert_eq!(frame.lines.len(), height, "height {height}"); + for rows in 1..=8 { + for upward in [false, true] { + let frame = picker.frame(40, rows, upward, false); + assert_eq!(frame.rows.len(), rows); + } } } @@ -964,21 +1337,27 @@ mod tests { let entries: Vec = (0..100).map(|n| format!("cmd {n:02}")).collect(); let mut picker = HistoryPicker::new(entries, ""); picker.handle(Key::End); - let frame = picker.render(40, 8, false); - let text = body(&frame); - assert!(text.contains("> cmd 00")); + let frame = picker.frame(40, 4, false, false); + assert!(body(&frame).contains("> cmd 00")); assert_eq!(picker.offset(), 96); picker.handle(Key::Home); - let frame = picker.render(40, 8, false); + let frame = picker.frame(40, 4, false, false); assert!(body(&frame).contains("> cmd 99")); assert_eq!(picker.offset(), 0); + + // The same holds when the list is drawn upwards. The oldest visible + // entries are at the top, so the selected oldest entry is row 0. + picker.handle(Key::End); + let frame = picker.frame(40, 4, true, false); + assert!(body(&frame).contains("> cmd 00")); + assert!(plain(&frame.rows[0]).starts_with("> cmd 00")); } #[test] fn newlines_are_flattened_and_control_characters_dropped() { let mut picker = picker(&["echo hi\nthere", "esc \x1b[31mred"]); - let frame = picker.render(60, 8, false); + let frame = picker.frame(60, 3, false, false); let text = body(&frame); assert!(text.contains("echo hi \u{23ce} there")); assert!(!text.contains('\x1b')); @@ -986,33 +1365,24 @@ mod tests { } #[test] - fn no_matches_shows_a_message_and_zero_counts() { + fn no_matches_message_sits_next_to_the_query() { let mut picker = picker_with(&["git status"], "zzz"); - let frame = picker.render(50, 8, false); - let text = body(&frame); - assert!(text.contains("no matching commands")); - assert!(text.contains("0/0")); - assert!(text.contains("0/1")); + let downward = picker.frame(50, 3, false, false); + assert!(plain(&downward.rows[0]).contains("no matching commands")); + assert!(plain(&downward.query).contains("0/0")); + + let upward = picker.frame(50, 3, true, false); + assert!(plain(&upward.rows[2]).contains("no matching commands")); } #[test] fn empty_history_is_reported_in_the_ui() { let mut picker = picker(&[]); - let frame = picker.render(50, 8, false); + let frame = picker.frame(50, 3, false, false); assert!(body(&frame).contains("no history yet")); assert_eq!(picker.handle(Key::Enter), Action::Continue); } - #[test] - fn header_and_footer_show_counts_and_help() { - let mut picker = picker(&["one", "two", "three"]); - let frame = picker.render(60, 8, false); - assert!(body(&frame).contains("3/3")); - assert!(body(&frame).contains("1/3")); - assert!(body(&frame).contains("enter edit")); - assert!(body(&frame).contains("esc cancel")); - } - #[test] fn display_text_sanitizes_each_entry() { assert_eq!(display_text("a\tb"), "a b"); @@ -1030,14 +1400,6 @@ mod tests { assert_eq!(fit("hello", 0), ""); } - #[test] - fn visible_width_ignores_escape_sequences() { - assert_eq!(visible_width("plain"), 5); - assert_eq!(visible_width("\x1b[32m➜\x1b[0m ~ $"), 5); - assert_eq!(visible_width("\x1b[1;36mheader\x1b[0m"), 6); - assert_eq!(visible_width(""), 0); - } - #[test] fn split_match_finds_ascii_case_insensitively() { assert_eq!(split_match("Git Status", "git"), ("", "Git", " Status")); @@ -1045,4 +1407,98 @@ mod tests { assert_eq!(split_match("nothing", "zzz"), ("nothing", "", "")); assert_eq!(split_match("anything", ""), ("anything", "", "")); } + + #[test] + fn cursor_replies_are_separated_from_typed_input() { + assert_eq!(cursor_reply(b"\x1b[24;1R"), Some((0, (24, 1)))); + assert_eq!(cursor_reply(b"bet\x1b[7;12R"), Some((3, (7, 12)))); + assert_eq!(cursor_reply(b"\x1b[24;1"), None); + assert_eq!(cursor_reply(b"typed"), None); + assert_eq!(cursor_reply(b"\x1b[?24;1R"), None); + } + + #[test] + fn prompt_height_accounts_for_wrapping_and_hints() { + assert_eq!(prompt_height("\x1b[32m\u{27a4}\x1b[0m ", "", 0, 10), 1); + assert_eq!(prompt_height("12345678", "ab", 0, 10), 1); + assert_eq!(prompt_height("12345678", "ab", 1, 10), 2); + assert_eq!(prompt_height("123456789", "ab", 0, 10), 2); + assert_eq!(prompt_height("12345", "6789012345", 0, 10), 2); + assert_eq!(prompt_height("> ", "a\nb", 0, 10), 2); + } + + #[test] + fn prompt_row_is_one_row_above_the_cursor() { + assert_eq!(prompt_row_from_cursor(24, 24), 22); + assert_eq!(prompt_row_from_cursor(5, 24), 3); + assert_eq!(prompt_row_from_cursor(1, 24), 0); + assert_eq!(prompt_row_from_cursor(2, 24), 0); + } + + #[test] + fn layout_opens_downwards_when_there_is_room_below() { + let layout = layout(24, 5, 5); + assert!(!layout.upward); + assert!(!layout.prompt_visible); + assert_eq!(layout.scrolled, 0); + assert_eq!(layout.popup_start, 5); + assert_eq!(layout.popup_end, 10); + assert_eq!(layout.query_row, 5); + assert_eq!(layout.match_start, 6); + } + + #[test] + fn layout_keeps_the_prompt_visible_at_the_bottom() { + let layout = layout(24, 23, 5); + assert!(layout.upward); + assert!(layout.prompt_visible); + assert_eq!(layout.scrolled, 6); + assert_eq!(layout.popup_start, 17); + assert_eq!(layout.popup_end, 22); + assert_eq!(layout.query_row, 22); + assert_eq!(layout.match_start, 17); + } + + #[test] + fn layout_keeps_the_prompt_visible_near_the_bottom() { + let layout = layout(24, 20, 5); + assert!(layout.upward); + assert!(layout.prompt_visible); + assert_eq!(layout.scrolled, 6); + assert_eq!(layout.popup_start, 14); + assert_eq!(layout.popup_end, 19); + assert_eq!(layout.query_row, 19); + assert_eq!(layout.match_start, 14); + } + + #[test] + fn layout_uses_the_fallback_when_there_is_no_room_above_the_prompt() { + let layout = layout(4, 2, 2); + assert!(layout.upward); + assert!(!layout.prompt_visible); + assert_eq!(layout.scrolled, 1); + assert_eq!(layout.popup_start, 1); + assert_eq!(layout.popup_end, 3); + assert_eq!(layout.query_row, 3); + assert_eq!(layout.match_start, 1); + } + + #[test] + fn layout_handles_tiny_terminals() { + let bottom = layout(3, 2, 1); + assert!(bottom.upward); + assert!(bottom.prompt_visible); + assert_eq!(bottom.scrolled, 2); + assert_eq!(bottom.popup_start, 0); + assert_eq!(bottom.popup_end, 1); + assert_eq!(bottom.query_row, 1); + assert_eq!(bottom.match_start, 0); + + let top = layout(3, 1, 1); + assert!(!top.upward); + assert!(!top.prompt_visible); + assert_eq!(top.scrolled, 0); + assert_eq!(top.popup_start, 1); + assert_eq!(top.query_row, 1); + } } diff --git a/src/main.rs b/src/main.rs index a09aaa7..52bd964 100644 --- a/src/main.rs +++ b/src/main.rs @@ -566,13 +566,12 @@ fn read_prompt_line( return Ok(PromptLine::Interrupted); }; let entries = history_entries(rl); - let picked = history_search::pick(entries, &line); - history_search::erase_prompt_line(prompt, &line, hint_len); + let picked = history_search::pick(entries, &line, prompt, hint_len); resume = Some(match picked { history_search::Picked::Entry(entry) => (entry, String::new()), history_search::Picked::Cancelled => split_at_cursor(line, pos), history_search::Picked::Unavailable => { - registry::print_colored("ash: no history to search yet", "warning"); + registry::print_colored("ash: history search unavailable", "warning"); split_at_cursor(line, pos) } });