//! A line editing library for handling user input. //! //! This module provides a line editor with: //! * History navigation (up/down arrows) //! * Cursor movement (left/right arrows) //! * Basic line editing (backspace, delete) //! * Raw mode terminal handling //! * ANSI escape sequence support #![warn(missing_docs, clippy::unwrap_used)] #![allow(clippy::collapsible_if)] use crate::tui::Text as _; use libc; use std::io; use std::io::{Read, Stdin, Stdout, Write}; mod cursor; use cursor::Cursor; // Special characters. const CTRL_A: u8 = 1; const CTRL_C: u8 = 3; const CTRL_D: u8 = 4; const CTRL_E: u8 = 5; const ENTER: u8 = 13; const NEWLINE: u8 = 10; const BACKSPACE: u8 = 127; const DELETE: u8 = 8; const ESC: u8 = 27; // ANSI escape sequences. const CLEAR_LINE: &str = "\r\x1b[0K"; const CLEAR_SCREEN_FROM_CURSOR: &str = "\x1b[J"; /// Maximum time to wait for another byte in an escape sequence. const ESCAPE_TIMEOUT_MS: u32 = 50; /// Maintains editing state and terminal configuration. pub struct Readline { /// Original terminal settings to restore on drop. previous: libc::termios, /// Saved current line when navigating history. current_line: Option, /// Cached stdout handle. stdout: Stdout, /// Cached stdin handle. stdin: Stdin, /// Readiness sources used while parsing escape sequences. sources: popol::Sources<()>, /// Reusable buffer for input readiness events. events: Vec>, /// Current input buffer. buffer: String, /// History of previously entered lines. history: Vec, /// Current position in history when navigating. history_pos: Option, /// Current cursor position in the buffer. cursor_pos: usize, } impl Readline { /// Creates a new [`Readline`] instance. /// /// Initializes terminal settings and internal buffers. /// Returns error if terminal settings cannot be retrieved. pub fn new() -> io::Result { let mut previous = unsafe { std::mem::zeroed() }; if unsafe { libc::tcgetattr(libc::STDIN_FILENO, &mut previous) } != 0 { return Err(io::Error::last_os_error()); } // Configure raw mode. let mut raw = previous; raw.c_lflag &= !(libc::ECHO | libc::ICANON | libc::IEXTEN | libc::ISIG); raw.c_iflag &= !(libc::IXON | libc::ICRNL); raw.c_oflag &= !(libc::OPOST); raw.c_cc[libc::VMIN] = 1; raw.c_cc[libc::VTIME] = 0; // Apply raw mode settings. if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &raw) } != 0 { return Err(io::Error::last_os_error()); } let stdin = io::stdin(); let mut sources = popol::Sources::with_capacity(1); sources.register((), &stdin, popol::interest::READ); Ok(Readline { buffer: String::with_capacity(1024), previous, history: Vec::new(), history_pos: None, current_line: None, stdout: io::stdout(), stdin, sources, events: Vec::with_capacity(1), cursor_pos: 0, }) } /// Adds a line to the history. /// /// Only non-empty lines are added. Duplicate consecutive entries are ignored. pub fn add_history(&mut self, line: String) { if line.trim().is_empty() { return; } if let Some(last) = self.history.last() { if last == &line { return; } } self.history.push(line); } /// Reads a line of input from the user. /// /// Displays the given prompt and handles user input until submission. /// Returns None if `Ctrl-C` or `Ctrl-D` is pressed. pub fn readline(&mut self, prompt: &str) -> io::Result> { // Start at beginning of line and clear. write!(self.stdout, "{}{}", CLEAR_LINE, prompt)?; self.stdout.flush()?; self.buffer.clear(); let mut buf = [0u8; 8]; self.cursor_pos = 0; self.history_pos = None; self.current_line = None; loop { match self.stdin.read(&mut buf[..1]) { Ok(0) => { if self.buffer.is_empty() { return Ok(None); } break; } Ok(_) => {} Err(e) => return Err(e), } match self.handle_keypress(&mut buf, prompt)? { KeyAction::Exit => return Ok(None), KeyAction::Submit => break, KeyAction::Continue => continue, } } self.add_history(self.buffer.clone()); Ok(Some(&self.buffer)) } } #[derive(Debug)] enum KeyAction { Exit, Submit, Continue, } impl Readline { /// Move to start of line and clear everything after cursor. /// Then, move cursor back to position if needed. fn refresh_line(&mut self, prompt: &str) -> io::Result<()> { write!(self.stdout, "{}{}{}", CLEAR_LINE, prompt, self.buffer)?; let remaining = self.buffer[self.cursor_pos..].width(); if remaining > 0 { write!(self.stdout, "{}", Cursor::left(remaining))?; } self.stdout.flush() } fn read_escape_sequence(&mut self, buf: &mut [u8; 8]) -> io::Result { let mut len = 1; loop { self.events.clear(); match self.sources.poll( &mut self.events, popol::Timeout::from_millis(ESCAPE_TIMEOUT_MS), ) { Ok(_) => {} Err(error) if error.kind() == io::ErrorKind::TimedOut => return Ok(len), Err(error) => return Err(error), } let mut byte = [0]; self.stdin.read_exact(&mut byte)?; if len < buf.len() { buf[len] = byte[0]; len += 1; } if len == 2 && byte[0] != b'[' { return Ok(len); } if len > 2 && (0x40..=0x7e).contains(&byte[0]) { return Ok(len); } } } fn handle_keypress(&mut self, buf: &mut [u8; 8], prompt: &str) -> io::Result { match buf[0] { ESC => { let len = self.read_escape_sequence(buf)?; match &buf[..len] { [ESC, b'[', b'3', b'~'] if self.cursor_pos < self.buffer.len() => { self.buffer.remove(self.cursor_pos); self.refresh_line(prompt)?; } [ESC, b'[', b'A'] => self.handle_up_arrow(prompt)?, [ESC, b'[', b'B'] => self.handle_down_arrow(prompt)?, [ESC, b'[', b'C'] => self.handle_right_arrow()?, [ESC, b'[', b'D'] => self.handle_left_arrow()?, _ => {} } Ok(KeyAction::Continue) } CTRL_A => { if self.cursor_pos > 0 { let columns = self.buffer[..self.cursor_pos].width(); write!(self.stdout, "{}", Cursor::left(columns))?; self.stdout.flush()?; self.cursor_pos = 0; } Ok(KeyAction::Continue) } CTRL_E => { let columns = self.buffer[self.cursor_pos..].width(); if columns > 0 { write!(self.stdout, "{}", Cursor::right(columns))?; self.stdout.flush()?; self.cursor_pos = self.buffer.len(); } Ok(KeyAction::Continue) } CTRL_C | CTRL_D => { write!( self.stdout, "{}\r\n{}", CLEAR_SCREEN_FROM_CURSOR, CLEAR_LINE )?; self.stdout.flush()?; Ok(KeyAction::Exit) } ENTER | NEWLINE => { write!(self.stdout, "\r\n")?; self.stdout.flush()?; Ok(KeyAction::Submit) } BACKSPACE | DELETE => { if self.cursor_pos > 0 { let previous = self.buffer[..self.cursor_pos] .char_indices() .next_back() .map_or(0, |(index, _)| index); self.buffer.drain(previous..self.cursor_pos); self.cursor_pos = previous; self.refresh_line(prompt)?; } Ok(KeyAction::Continue) } c if c.is_ascii() && !c.is_ascii_control() => { self.buffer.insert(self.cursor_pos, c as char); self.cursor_pos += 1; self.refresh_line(prompt)?; Ok(KeyAction::Continue) } c if c >= 0xc2 => { let width = match c { 0xc2..=0xdf => 2, 0xe0..=0xef => 3, 0xf0..=0xf4 => 4, _ => return Ok(KeyAction::Continue), }; self.stdin.read_exact(&mut buf[1..width])?; if let Ok(value) = std::str::from_utf8(&buf[..width]) { self.buffer.insert_str(self.cursor_pos, value); self.cursor_pos += width; self.refresh_line(prompt)?; } Ok(KeyAction::Continue) } _ => Ok(KeyAction::Continue), } } fn handle_up_arrow(&mut self, prompt: &str) -> io::Result<()> { if self.history_pos.is_none() { self.current_line = Some(self.buffer.clone()); } self.history_pos = match self.history_pos { Some(pos) if pos > 0 => Some(pos - 1), None if !self.history.is_empty() => Some(self.history.len() - 1), other => other, }; if let Some(pos) = self.history_pos { if pos < self.history.len() { self.buffer = self.history[pos].clone(); self.cursor_pos = self.buffer.len(); self.refresh_line(prompt)?; } } Ok(()) } fn handle_down_arrow(&mut self, prompt: &str) -> io::Result<()> { if let Some(pos) = self.history_pos { if pos + 1 < self.history.len() { self.history_pos = Some(pos + 1); self.buffer = self.history[pos + 1].clone(); } else { self.history_pos = None; self.buffer = self.current_line.take().unwrap_or_default(); } self.cursor_pos = self.buffer.len(); self.refresh_line(prompt)?; } Ok(()) } fn handle_right_arrow(&mut self) -> io::Result<()> { if let Some(ch) = self.buffer[self.cursor_pos..].chars().next() { let next = self.cursor_pos + ch.len_utf8(); let columns = self.buffer[self.cursor_pos..next].width(); self.cursor_pos = next; write!(self.stdout, "{}", Cursor::right(columns))?; self.stdout.flush()?; } Ok(()) } fn handle_left_arrow(&mut self) -> io::Result<()> { if let Some((previous, _)) = self.buffer[..self.cursor_pos].char_indices().next_back() { let columns = self.buffer[previous..self.cursor_pos].width(); self.cursor_pos = previous; write!(self.stdout, "{}", Cursor::left(columns))?; self.stdout.flush()?; } Ok(()) } } impl Drop for Readline { fn drop(&mut self) { unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &self.previous); } } }