From 37184044609997604bfa1ab08be356d8b4e5e19d Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:07:45 +0100 Subject: Input editor: history, bracketed paste, in-line editing - crossterm raw mode only for the duration of a prompt, so SIGINT keeps working during a turn - persisted history with prompt commands excluded and newlines escaped - bracketed paste inserts one multi-line buffer instead of firing N turns - ctrl-a/e/u/k/w editing, ctrl-c abandons the line, ctrl-d exits - ctrl-j submits, so pipes and pty harnesses work - width fallback: a 0-column pty is 80 columns, not 1 --- src/line.rs | 415 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 415 insertions(+) create mode 100644 src/line.rs (limited to 'src/line.rs') diff --git a/src/line.rs b/src/line.rs new file mode 100644 index 0000000..6b93f06 --- /dev/null +++ b/src/line.rs @@ -0,0 +1,415 @@ +use std::io::{self, IsTerminal, Write}; +use std::path::PathBuf; + +use crossterm::cursor::{MoveToColumn, MoveUp}; +use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; +use crossterm::event::{DisableBracketedPaste, EnableBracketedPaste}; +use crossterm::terminal::{self, Clear, ClearType}; +use crossterm::execute; + +const HISTORY_LIMIT: usize = 200; + +pub struct Editor { + interactive: bool, + history: Vec, + history_index: usize, + draft: Vec, +} + +impl Editor { + pub fn new() -> Self { + Self { + interactive: std::io::stdin().is_terminal() && std::io::stdout().is_terminal(), + history: load_history(), + history_index: 0, + draft: Vec::new(), + } + } + + pub fn is_interactive(&self) -> bool { + self.interactive + } + + /// Reads one prompt. `None` means end of input (Ctrl-D or EOF). + /// + /// Raw mode is enabled only for the duration of this call, so Ctrl-C during + /// a turn is still a signal handled by `signal`, not a keystroke. + pub fn read(&mut self, prompt: &str) -> io::Result> { + if !self.interactive { + return read_plain(); + } + + let guard = RawGuard::enable()?; + let mut buffer: Vec = Vec::new(); + let mut cursor = 0usize; + let mut rows = 1usize; + + self.history_index = self.history.len(); + self.draft.clear(); + + let width = terminal_width(); + draw(prompt, &buffer, cursor, width, &mut rows)?; + + loop { + let event = event::read()?; + match event { + Event::Paste(text) => { + insert(&mut buffer, &mut cursor, &text); + draw(prompt, &buffer, cursor, width, &mut rows)?; + } + Event::Key(key) if key.kind == KeyEventKind::Press => { + match handle_key(key, &mut buffer, &mut cursor, self) { + Action::Continue => {} + Action::Submit => { + // Redraw with the caret at the end so the submitted + // line looks complete before we move on. + draw(prompt, &buffer, buffer.len(), width, &mut rows)?; + drop(guard); + let line: String = buffer.iter().collect(); + self.remember(&line); + println!(); + return Ok(Some(line)); + } + Action::Eof => { + drop(guard); + println!(); + return Ok(None); + } + Action::Cancel => { + drop(guard); + println!("^C"); + return Ok(Some(String::new())); + } + } + draw(prompt, &buffer, cursor, width, &mut rows)?; + } + _ => {} + } + } + } + + fn remember(&mut self, line: &str) { + if line.trim().is_empty() { + return; + } + // Prompt-mode commands are not worth recalling. + if matches!(line.trim(), "/exit" | "/quit" | "/help" | "/paste") { + return; + } + if self.history.last().map(|last| last.as_str()) == Some(line) { + return; + } + self.history.push(line.to_string()); + if self.history.len() > HISTORY_LIMIT { + self.history.remove(0); + } + append_history(line); + } +} + +/// Plain line reading for pipes, scripts and tests. Identical contract. +fn read_plain() -> io::Result> { + let mut line = String::new(); + if io::stdin().read_line(&mut line)? == 0 { + return Ok(None); + } + Ok(Some(line.trim_end_matches(['\n', '\r']).to_string())) +} + +enum Action { + Continue, + Submit, + Eof, + Cancel, +} + +fn handle_key( + key: KeyEvent, + buffer: &mut Vec, + cursor: &mut usize, + editor: &mut Editor, +) -> Action { + let ctrl = key.modifiers.contains(KeyModifiers::CONTROL); + + match key.code { + KeyCode::Enter => return Action::Submit, + // Ctrl-J is what a pipe or a test harness sends for a newline; terminals + // send CR for Enter, so both have to submit. + KeyCode::Char('j') if ctrl => return Action::Submit, + KeyCode::Char('d') if ctrl => { + if buffer.is_empty() { + return Action::Eof; + } + if *cursor < buffer.len() { + buffer.remove(*cursor); + } + } + KeyCode::Char('c') if ctrl => return Action::Cancel, + KeyCode::Char('a') if ctrl => *cursor = 0, + KeyCode::Char('e') if ctrl => *cursor = buffer.len(), + KeyCode::Char('u') if ctrl => { + buffer.clear(); + *cursor = 0; + } + KeyCode::Char('k') if ctrl => buffer.truncate(*cursor), + KeyCode::Char('w') if ctrl => { + let mut end = *cursor; + while end > 0 && buffer[end - 1].is_whitespace() { + end -= 1; + } + while end > 0 && !buffer[end - 1].is_whitespace() { + end -= 1; + } + buffer.drain(end..*cursor); + *cursor = end; + } + KeyCode::Char(ch) if !ctrl => { + buffer.insert(*cursor, ch); + *cursor += 1; + } + KeyCode::Tab => { + for _ in 0..4 { + buffer.insert(*cursor, ' '); + *cursor += 1; + } + } + KeyCode::Backspace => { + if *cursor > 0 { + buffer.remove(*cursor - 1); + *cursor -= 1; + } + } + KeyCode::Delete => { + if *cursor < buffer.len() { + buffer.remove(*cursor); + } + } + KeyCode::Left => *cursor = cursor.saturating_sub(1), + KeyCode::Right => *cursor = (*cursor + 1).min(buffer.len()), + KeyCode::Home => *cursor = 0, + KeyCode::End => *cursor = buffer.len(), + KeyCode::Up => editor.history_up(buffer, cursor), + KeyCode::Down => editor.history_down(buffer, cursor), + _ => {} + } + Action::Continue +} + +impl Editor { + fn history_up(&mut self, buffer: &mut Vec, cursor: &mut usize) { + if self.history.is_empty() || self.history_index == 0 { + return; + } + if self.history_index == self.history.len() { + self.draft = buffer.clone(); + } + self.history_index -= 1; + *buffer = self.history[self.history_index].chars().collect(); + *cursor = buffer.len(); + } + + fn history_down(&mut self, buffer: &mut Vec, cursor: &mut usize) { + if self.history_index >= self.history.len() { + return; + } + self.history_index += 1; + if self.history_index == self.history.len() { + *buffer = self.draft.clone(); + } else { + *buffer = self.history[self.history_index].chars().collect(); + } + *cursor = buffer.len(); + } +} + +fn insert(buffer: &mut Vec, cursor: &mut usize, text: &str) { + let normalized = text.replace("\r\n", "\n").replace('\r', "\n"); + for (offset, ch) in normalized.chars().enumerate() { + buffer.insert(*cursor + offset, ch); + } + *cursor += normalized.chars().count(); +} + +fn terminal_width() -> usize { + match terminal::size() { + // A pty with no size reported reports 0 columns; treating that as 1 + // would make every character wrap onto its own line. + Ok((cols, _)) if cols > 0 => cols as usize, + _ => 80, + } +} + +/// Position of the cursor after consuming `prompt` plus `buffer[..upto]`. +/// Approximates every character as one column; good enough for a prompt line. +fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, usize) { + let mut row = 0usize; + let mut col = 0usize; + for ch in prompt.chars().chain(buffer[..upto.min(buffer.len())].iter().copied()) { + advance(ch, &mut row, &mut col, width); + } + (row, col) +} + +fn advance(ch: char, row: &mut usize, col: &mut usize, width: usize) { + if ch == '\n' { + *row += 1; + *col = 0; + return; + } + *col += 1; + if *col >= width { + *col = 0; + *row += 1; + } +} + +fn draw( + prompt: &str, + buffer: &[char], + cursor: usize, + width: usize, + rows: &mut usize, +) -> io::Result<()> { + let mut out = io::stdout(); + + let total = layout(prompt, buffer, buffer.len(), width).0 + 1; + let (cursor_row, cursor_col) = layout(prompt, buffer, cursor, width); + + if *rows > 1 { + execute!(out, MoveUp((*rows - 1) as u16))?; + } + execute!(out, MoveToColumn(0), Clear(ClearType::FromCursorDown))?; + + let mut text = String::with_capacity(prompt.len() + buffer.len()); + text.push_str(prompt); + for ch in buffer { + if *ch == '\n' { + text.push_str("\r\n"); + } else { + text.push(*ch); + } + } + out.write_all(text.as_bytes())?; + + let end_row = total - 1; + if end_row > cursor_row { + execute!(out, MoveUp((end_row - cursor_row) as u16))?; + } + execute!(out, MoveToColumn(cursor_col as u16))?; + out.flush()?; + + *rows = total; + Ok(()) +} + +struct RawGuard; + +impl RawGuard { + fn enable() -> io::Result { + terminal::enable_raw_mode()?; + execute!(io::stdout(), EnableBracketedPaste)?; + Ok(RawGuard) + } +} + +impl Drop for RawGuard { + fn drop(&mut self) { + let _ = execute!(io::stdout(), DisableBracketedPaste); + let _ = terminal::disable_raw_mode(); + } +} + +fn history_path() -> PathBuf { + crate::session::data_root().join("history") +} + +fn load_history() -> Vec { + let text = std::fs::read_to_string(history_path()).unwrap_or_default(); + let mut lines: Vec = text + .split('\n') + .filter(|line| !line.trim().is_empty() && !line.starts_with('\u{0}')) + .map(|line| line.replace('\u{0}', "\n")) + .collect(); + if lines.len() > HISTORY_LIMIT { + lines.drain(..lines.len() - HISTORY_LIMIT); + } + lines +} + +fn append_history(line: &str) { + let path = history_path(); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + { + // One record per line, so newlines inside a prompt are escaped. + let _ = writeln!(file, "{}", line.replace('\n', "\u{0}")); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layout_accounts_for_newlines() { + let buffer: Vec = "ab\ncd".chars().collect(); + assert_eq!(layout("> ", &buffer, 0, 80), (0, 2)); + assert_eq!(layout("> ", &buffer, 2, 80), (0, 4)); + assert_eq!(layout("> ", &buffer, 3, 80), (1, 0)); + assert_eq!(layout("> ", &buffer, 5, 80), (1, 2)); + } + + #[test] + fn layout_wraps_at_the_terminal_width() { + let buffer: Vec = "abcdef".chars().collect(); + // Prompt takes 2 columns, so the 6 chars fill exactly 8. + assert_eq!(layout("> ", &buffer, 6, 8), (1, 0)); + assert_eq!(layout("> ", &buffer, 3, 8), (0, 5)); + } + + #[test] + fn width_falls_back_when_the_terminal_reports_none() { + // Cannot control the real terminal here, but the fallback path must not + // produce a one-column layout. + assert!(terminal_width() >= 1); + } + + #[test] + fn insert_normalises_line_endings() { + let mut buffer = vec!['a']; + let mut cursor = 1; + insert(&mut buffer, &mut cursor, "b\r\nc"); + assert_eq!(buffer, vec!['a', 'b', '\n', 'c']); + assert_eq!(cursor, 4); + } + + #[test] + fn history_walks_both_ways() { + let mut editor = Editor { + interactive: false, + history: vec!["one".into(), "two".into()], + history_index: 0, + draft: Vec::new(), + }; + editor.history_index = editor.history.len(); + + let mut buffer = vec!['x']; + let mut cursor = 1; + editor.history_up(&mut buffer, &mut cursor); + assert_eq!(buffer.iter().collect::(), "two"); + editor.history_up(&mut buffer, &mut cursor); + assert_eq!(buffer.iter().collect::(), "one"); + editor.history_up(&mut buffer, &mut cursor); + assert_eq!(buffer.iter().collect::(), "one"); + + editor.history_down(&mut buffer, &mut cursor); + assert_eq!(buffer.iter().collect::(), "two"); + editor.history_down(&mut buffer, &mut cursor); + assert_eq!(buffer.iter().collect::(), "x"); + } +} -- cgit v1.2.3