use std::io::{self, IsTerminal, Write}; use std::os::unix::fs::PermissionsExt; 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 state = DrawState::default(); self.history_index = self.history.len(); self.draft.clear(); draw(prompt, &buffer, cursor, &mut state)?; loop { let event = event::read()?; match event { Event::Paste(text) => { insert(&mut buffer, &mut cursor, &text); draw(prompt, &buffer, cursor, &mut state)?; } Event::Resize(_, _) => { // The terminal has already reflowed the block and moved the // caret with it, so drawing again here would duplicate the // prompt. Recompute only where the caret now sits relative // to the block; the next redraw moves up from there. let width = terminal_width(); let (cursor_row, _) = layout(prompt, &buffer, cursor, width); state.cursor_row = cursor_row; state.rows = layout(prompt, &buffer, buffer.len(), width).0 + 1; } 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(), &mut state)?; 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, &mut state)?; } _ => {} } } } 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]`. /// /// Columns are 0-based, matching the cursor-move escape. Wrapping is modelled /// the way terminals actually behave: filling the last column leaves the cursor /// *in* that column, and only the next character wraps. Getting this wrong makes /// the redraw move up one row too many and erase the line above the prompt. fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, usize) { let width = width.max(1); let mut row = 0usize; let mut col = 0usize; let mut pending_wrap = false; for ch in prompt .chars() .chain(buffer[..upto.min(buffer.len())].iter().copied()) { if ch == '\n' { row += 1; col = 0; pending_wrap = false; continue; } if pending_wrap { row += 1; col = 0; pending_wrap = false; } let cells = cells(ch, col); if cells == 0 { // Combining marks draw on top of the previous cell. continue; } if col + cells > width { row += 1; col = 0; } col += cells; if col >= width { col = width - 1; pending_wrap = true; } } (row, col) } /// Columns a character occupies at the given cursor position. Terminals expand /// a tab to the next multiple of eight; wide characters occupy two cells. fn cells(ch: char, col: usize) -> usize { if ch == '\t' { return 8 - (col % 8); } unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1) } /// Where the caret physically is, relative to the first row of the input block. /// The previous draw can leave the caret on any row, so a redraw must move up by /// that row, not by the number of rows the block occupies. #[derive(Default, Clone, Copy)] struct DrawState { rows: usize, cursor_row: usize, } fn draw( prompt: &str, buffer: &[char], cursor: usize, state: &mut DrawState, ) -> io::Result<()> { let mut out = io::stdout(); draw_to(&mut out, prompt, buffer, cursor, state)?; out.flush() } fn draw_to( out: &mut W, prompt: &str, buffer: &[char], cursor: usize, state: &mut DrawState, ) -> io::Result<()> { let width = terminal_width(); let (end_row, _) = layout(prompt, buffer, buffer.len(), width); let (cursor_row, cursor_col) = layout(prompt, buffer, cursor, width); if state.cursor_row > 0 { execute!(out, MoveUp(clamp(state.cursor_row)))?; } 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())?; if end_row > cursor_row { execute!(out, MoveUp(clamp(end_row - cursor_row)))?; } execute!(out, MoveToColumn(clamp(cursor_col)))?; state.rows = end_row + 1; state.cursor_row = cursor_row; Ok(()) } fn clamp(value: usize) -> u16 { value.min(u16::MAX as usize) as u16 } 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 path = history_path(); let text = std::fs::read_to_string(&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); // Keep the file from growing without bound, not just the in-memory list. if lines.len() * 2 < text.lines().count() { let body: Vec = lines.iter().map(|line| line.replace('\n', "\u{0}")).collect(); let _ = std::fs::write(&path, format!("{}\n", body.join("\n"))); } } 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 Some(parent) = path.parent() { let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)); } if let Ok(mut file) = std::fs::OpenOptions::new() .create(true) .append(true) .open(&path) { let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); // 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_lazily_at_the_terminal_width() { let buffer: Vec = "abcdef".chars().collect(); // Prompt takes 2 columns, so six more fill the 8-column row exactly. // The cursor stays in the last column until another character arrives; // counting a new row here is what used to erase the line above. assert_eq!(layout("> ", &buffer, 6, 8), (0, 7)); assert_eq!(layout("> ", &buffer, 3, 8), (0, 5)); let mut longer = buffer.clone(); longer.push('g'); assert_eq!(layout("> ", &longer, 7, 8), (1, 1)); } #[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); } fn drawn(prompt: &str, buffer: &str, cursor: usize, state: &mut DrawState) -> String { let chars: Vec = buffer.chars().collect(); let mut out = Vec::new(); draw_to(&mut out, prompt, &chars, cursor, state).unwrap(); String::from_utf8(out).unwrap() } #[test] fn redraw_moves_up_by_the_caret_row_not_the_block_height() { let mut state = DrawState::default(); // First draw with the caret at the end of a two-line buffer. let first = drawn("> ", "one\ntwo", 7, &mut state); assert_eq!(state.cursor_row, 1, "caret ends on the second row"); assert!(!first.contains("\u{1b}[1A"), "first draw must not move up"); // Move the caret to the first row. The previous caret was on row 1, so // the redraw may move up exactly one row — not `rows - 1` from row 0, // which would land on the line above the prompt and erase it. let second = drawn("> ", "one\ntwo", 0, &mut state); assert!( second.starts_with("\u{1b}[1A"), "expected one MoveUp, got {:?}", second ); assert_eq!(state.cursor_row, 0); // Drawing again with the caret already on row 0 must not move up // *before* clearing; the only MoveUp is the one after writing, which // puts the caret back on the first row. let third = drawn("> ", "one\ntwo", 0, &mut state); assert!( !third.starts_with("\u{1b}[1A"), "must not move up before clearing: {third:?}" ); assert_eq!( third.matches("\u{1b}[1A").count(), 1, "exactly one repositioning move after writing: {third:?}" ); } #[test] fn layout_counts_wide_and_combining_characters() { let wide: Vec = "日本語".chars().collect(); assert_eq!(layout("> ", &wide, 3, 20), (0, 8)); let combining: Vec = "e\u{0301}".chars().collect(); assert_eq!(layout("", &combining, 2, 20), (0, 1)); } #[test] fn layout_expands_tabs_to_the_next_stop() { let tab: Vec = "\t".chars().collect(); assert_eq!(layout("> ", &tab, 1, 80), (0, 8)); assert_eq!(layout("", &tab, 1, 80), (0, 8)); } #[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"); } }