.cargo/
crates/
scripts/
src/
math/
readline/
editor.rs
7.1 KiB
fmt.rs
2.3 KiB
lib.rs
1.1 KiB
math.rs
150 B
readline.rs
11.7 KiB
rng.rs
14.0 KiB
.gitignore
30 B
.gitsigners
198 B
AGENTS.md
1.9 KiB
CONTRIBUTING
1.7 KiB
Cargo.lock
5.4 KiB
Cargo.toml
1.9 KiB
LICENSE
1.1 KiB
README.md
245 B
STYLE
3.7 KiB
clippy.toml
213 B
src/readline.rs
raw
| 1 | //! A line editing library for handling user input. |
| 2 | //! |
| 3 | //! This module provides a line editor with: |
| 4 | //! * History navigation (up/down arrows) |
| 5 | //! * Cursor movement (left/right arrows) |
| 6 | //! * Basic line editing (backspace, delete) |
| 7 | //! * Raw mode terminal handling |
| 8 | //! * ANSI escape sequence support |
| 9 | #![warn(missing_docs, clippy::unwrap_used)] |
| 10 | #![allow(clippy::collapsible_if)] |
| 11 | use crate::tui::Text as _; |
| 12 | use libc; |
| 13 | use std::io; |
| 14 | use std::io::{Read, Stdin, Stdout, Write}; |
| 15 | |
| 16 | mod cursor; |
| 17 | use cursor::Cursor; |
| 18 | |
| 19 | // Special characters. |
| 20 | const CTRL_A: u8 = 1; |
| 21 | const CTRL_C: u8 = 3; |
| 22 | const CTRL_D: u8 = 4; |
| 23 | const CTRL_E: u8 = 5; |
| 24 | const ENTER: u8 = 13; |
| 25 | const NEWLINE: u8 = 10; |
| 26 | const BACKSPACE: u8 = 127; |
| 27 | const DELETE: u8 = 8; |
| 28 | const ESC: u8 = 27; |
| 29 | |
| 30 | // ANSI escape sequences. |
| 31 | const CLEAR_LINE: &str = "\r\x1b[0K"; |
| 32 | const CLEAR_SCREEN_FROM_CURSOR: &str = "\x1b[J"; |
| 33 | |
| 34 | /// Maximum time to wait for another byte in an escape sequence. |
| 35 | const ESCAPE_TIMEOUT_MS: u32 = 50; |
| 36 | |
| 37 | /// Maintains editing state and terminal configuration. |
| 38 | pub struct Readline { |
| 39 | /// Original terminal settings to restore on drop. |
| 40 | previous: libc::termios, |
| 41 | /// Saved current line when navigating history. |
| 42 | current_line: Option<String>, |
| 43 | /// Cached stdout handle. |
| 44 | stdout: Stdout, |
| 45 | /// Cached stdin handle. |
| 46 | stdin: Stdin, |
| 47 | /// Readiness sources used while parsing escape sequences. |
| 48 | sources: popol::Sources<()>, |
| 49 | /// Reusable buffer for input readiness events. |
| 50 | events: Vec<popol::Event<()>>, |
| 51 | /// Current input buffer. |
| 52 | buffer: String, |
| 53 | /// History of previously entered lines. |
| 54 | history: Vec<String>, |
| 55 | /// Current position in history when navigating. |
| 56 | history_pos: Option<usize>, |
| 57 | /// Current cursor position in the buffer. |
| 58 | cursor_pos: usize, |
| 59 | } |
| 60 | |
| 61 | impl Readline { |
| 62 | /// Creates a new [`Readline`] instance. |
| 63 | /// |
| 64 | /// Initializes terminal settings and internal buffers. |
| 65 | /// Returns error if terminal settings cannot be retrieved. |
| 66 | pub fn new() -> io::Result<Self> { |
| 67 | let mut previous = unsafe { std::mem::zeroed() }; |
| 68 | if unsafe { libc::tcgetattr(libc::STDIN_FILENO, &mut previous) } != 0 { |
| 69 | return Err(io::Error::last_os_error()); |
| 70 | } |
| 71 | // Configure raw mode. |
| 72 | let mut raw = previous; |
| 73 | raw.c_lflag &= !(libc::ECHO | libc::ICANON | libc::IEXTEN | libc::ISIG); |
| 74 | raw.c_iflag &= !(libc::IXON | libc::ICRNL); |
| 75 | raw.c_oflag &= !(libc::OPOST); |
| 76 | raw.c_cc[libc::VMIN] = 1; |
| 77 | raw.c_cc[libc::VTIME] = 0; |
| 78 | |
| 79 | // Apply raw mode settings. |
| 80 | if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &raw) } != 0 { |
| 81 | return Err(io::Error::last_os_error()); |
| 82 | } |
| 83 | |
| 84 | let stdin = io::stdin(); |
| 85 | let mut sources = popol::Sources::with_capacity(1); |
| 86 | sources.register((), &stdin, popol::interest::READ); |
| 87 | |
| 88 | Ok(Readline { |
| 89 | buffer: String::with_capacity(1024), |
| 90 | previous, |
| 91 | history: Vec::new(), |
| 92 | history_pos: None, |
| 93 | current_line: None, |
| 94 | stdout: io::stdout(), |
| 95 | stdin, |
| 96 | sources, |
| 97 | events: Vec::with_capacity(1), |
| 98 | cursor_pos: 0, |
| 99 | }) |
| 100 | } |
| 101 | |
| 102 | /// Adds a line to the history. |
| 103 | /// |
| 104 | /// Only non-empty lines are added. Duplicate consecutive entries are ignored. |
| 105 | pub fn add_history(&mut self, line: String) { |
| 106 | if line.trim().is_empty() { |
| 107 | return; |
| 108 | } |
| 109 | if let Some(last) = self.history.last() { |
| 110 | if last == &line { |
| 111 | return; |
| 112 | } |
| 113 | } |
| 114 | self.history.push(line); |
| 115 | } |
| 116 | |
| 117 | /// Reads a line of input from the user. |
| 118 | /// |
| 119 | /// Displays the given prompt and handles user input until submission. |
| 120 | /// Returns None if `Ctrl-C` or `Ctrl-D` is pressed. |
| 121 | pub fn readline(&mut self, prompt: &str) -> io::Result<Option<&str>> { |
| 122 | // Start at beginning of line and clear. |
| 123 | write!(self.stdout, "{}{}", CLEAR_LINE, prompt)?; |
| 124 | |
| 125 | self.stdout.flush()?; |
| 126 | self.buffer.clear(); |
| 127 | |
| 128 | let mut buf = [0u8; 8]; |
| 129 | self.cursor_pos = 0; |
| 130 | self.history_pos = None; |
| 131 | self.current_line = None; |
| 132 | |
| 133 | loop { |
| 134 | match self.stdin.read(&mut buf[..1]) { |
| 135 | Ok(0) => { |
| 136 | if self.buffer.is_empty() { |
| 137 | return Ok(None); |
| 138 | } |
| 139 | break; |
| 140 | } |
| 141 | Ok(_) => {} |
| 142 | Err(e) => return Err(e), |
| 143 | } |
| 144 | match self.handle_keypress(&mut buf, prompt)? { |
| 145 | KeyAction::Exit => return Ok(None), |
| 146 | KeyAction::Submit => break, |
| 147 | KeyAction::Continue => continue, |
| 148 | } |
| 149 | } |
| 150 | self.add_history(self.buffer.clone()); |
| 151 | |
| 152 | Ok(Some(&self.buffer)) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | #[derive(Debug)] |
| 157 | enum KeyAction { |
| 158 | Exit, |
| 159 | Submit, |
| 160 | Continue, |
| 161 | } |
| 162 | |
| 163 | impl Readline { |
| 164 | /// Move to start of line and clear everything after cursor. |
| 165 | /// Then, move cursor back to position if needed. |
| 166 | fn refresh_line(&mut self, prompt: &str) -> io::Result<()> { |
| 167 | write!(self.stdout, "{}{}{}", CLEAR_LINE, prompt, self.buffer)?; |
| 168 | let remaining = self.buffer[self.cursor_pos..].width(); |
| 169 | if remaining > 0 { |
| 170 | write!(self.stdout, "{}", Cursor::left(remaining))?; |
| 171 | } |
| 172 | self.stdout.flush() |
| 173 | } |
| 174 | |
| 175 | fn read_escape_sequence(&mut self, buf: &mut [u8; 8]) -> io::Result<usize> { |
| 176 | let mut len = 1; |
| 177 | loop { |
| 178 | self.events.clear(); |
| 179 | match self.sources.poll( |
| 180 | &mut self.events, |
| 181 | popol::Timeout::from_millis(ESCAPE_TIMEOUT_MS), |
| 182 | ) { |
| 183 | Ok(_) => {} |
| 184 | Err(error) if error.kind() == io::ErrorKind::TimedOut => return Ok(len), |
| 185 | Err(error) => return Err(error), |
| 186 | } |
| 187 | |
| 188 | let mut byte = [0]; |
| 189 | self.stdin.read_exact(&mut byte)?; |
| 190 | if len < buf.len() { |
| 191 | buf[len] = byte[0]; |
| 192 | len += 1; |
| 193 | } |
| 194 | if len == 2 && byte[0] != b'[' { |
| 195 | return Ok(len); |
| 196 | } |
| 197 | if len > 2 && (0x40..=0x7e).contains(&byte[0]) { |
| 198 | return Ok(len); |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | fn handle_keypress(&mut self, buf: &mut [u8; 8], prompt: &str) -> io::Result<KeyAction> { |
| 204 | match buf[0] { |
| 205 | ESC => { |
| 206 | let len = self.read_escape_sequence(buf)?; |
| 207 | match &buf[..len] { |
| 208 | [ESC, b'[', b'3', b'~'] if self.cursor_pos < self.buffer.len() => { |
| 209 | self.buffer.remove(self.cursor_pos); |
| 210 | self.refresh_line(prompt)?; |
| 211 | } |
| 212 | [ESC, b'[', b'A'] => self.handle_up_arrow(prompt)?, |
| 213 | [ESC, b'[', b'B'] => self.handle_down_arrow(prompt)?, |
| 214 | [ESC, b'[', b'C'] => self.handle_right_arrow()?, |
| 215 | [ESC, b'[', b'D'] => self.handle_left_arrow()?, |
| 216 | _ => {} |
| 217 | } |
| 218 | Ok(KeyAction::Continue) |
| 219 | } |
| 220 | CTRL_A => { |
| 221 | if self.cursor_pos > 0 { |
| 222 | let columns = self.buffer[..self.cursor_pos].width(); |
| 223 | write!(self.stdout, "{}", Cursor::left(columns))?; |
| 224 | self.stdout.flush()?; |
| 225 | self.cursor_pos = 0; |
| 226 | } |
| 227 | Ok(KeyAction::Continue) |
| 228 | } |
| 229 | CTRL_E => { |
| 230 | let columns = self.buffer[self.cursor_pos..].width(); |
| 231 | if columns > 0 { |
| 232 | write!(self.stdout, "{}", Cursor::right(columns))?; |
| 233 | self.stdout.flush()?; |
| 234 | self.cursor_pos = self.buffer.len(); |
| 235 | } |
| 236 | Ok(KeyAction::Continue) |
| 237 | } |
| 238 | CTRL_C | CTRL_D => { |
| 239 | write!( |
| 240 | self.stdout, |
| 241 | "{}\r\n{}", |
| 242 | CLEAR_SCREEN_FROM_CURSOR, CLEAR_LINE |
| 243 | )?; |
| 244 | self.stdout.flush()?; |
| 245 | Ok(KeyAction::Exit) |
| 246 | } |
| 247 | ENTER | NEWLINE => { |
| 248 | write!(self.stdout, "\r\n")?; |
| 249 | self.stdout.flush()?; |
| 250 | Ok(KeyAction::Submit) |
| 251 | } |
| 252 | BACKSPACE | DELETE => { |
| 253 | if self.cursor_pos > 0 { |
| 254 | let previous = self.buffer[..self.cursor_pos] |
| 255 | .char_indices() |
| 256 | .next_back() |
| 257 | .map_or(0, |(index, _)| index); |
| 258 | self.buffer.drain(previous..self.cursor_pos); |
| 259 | self.cursor_pos = previous; |
| 260 | self.refresh_line(prompt)?; |
| 261 | } |
| 262 | Ok(KeyAction::Continue) |
| 263 | } |
| 264 | c if c.is_ascii() && !c.is_ascii_control() => { |
| 265 | self.buffer.insert(self.cursor_pos, c as char); |
| 266 | self.cursor_pos += 1; |
| 267 | self.refresh_line(prompt)?; |
| 268 | Ok(KeyAction::Continue) |
| 269 | } |
| 270 | c if c >= 0xc2 => { |
| 271 | let width = match c { |
| 272 | 0xc2..=0xdf => 2, |
| 273 | 0xe0..=0xef => 3, |
| 274 | 0xf0..=0xf4 => 4, |
| 275 | _ => return Ok(KeyAction::Continue), |
| 276 | }; |
| 277 | self.stdin.read_exact(&mut buf[1..width])?; |
| 278 | if let Ok(value) = std::str::from_utf8(&buf[..width]) { |
| 279 | self.buffer.insert_str(self.cursor_pos, value); |
| 280 | self.cursor_pos += width; |
| 281 | self.refresh_line(prompt)?; |
| 282 | } |
| 283 | Ok(KeyAction::Continue) |
| 284 | } |
| 285 | _ => Ok(KeyAction::Continue), |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | fn handle_up_arrow(&mut self, prompt: &str) -> io::Result<()> { |
| 290 | if self.history_pos.is_none() { |
| 291 | self.current_line = Some(self.buffer.clone()); |
| 292 | } |
| 293 | self.history_pos = match self.history_pos { |
| 294 | Some(pos) if pos > 0 => Some(pos - 1), |
| 295 | None if !self.history.is_empty() => Some(self.history.len() - 1), |
| 296 | other => other, |
| 297 | }; |
| 298 | |
| 299 | if let Some(pos) = self.history_pos { |
| 300 | if pos < self.history.len() { |
| 301 | self.buffer = self.history[pos].clone(); |
| 302 | self.cursor_pos = self.buffer.len(); |
| 303 | self.refresh_line(prompt)?; |
| 304 | } |
| 305 | } |
| 306 | Ok(()) |
| 307 | } |
| 308 | |
| 309 | fn handle_down_arrow(&mut self, prompt: &str) -> io::Result<()> { |
| 310 | if let Some(pos) = self.history_pos { |
| 311 | if pos + 1 < self.history.len() { |
| 312 | self.history_pos = Some(pos + 1); |
| 313 | self.buffer = self.history[pos + 1].clone(); |
| 314 | } else { |
| 315 | self.history_pos = None; |
| 316 | self.buffer = self.current_line.take().unwrap_or_default(); |
| 317 | } |
| 318 | self.cursor_pos = self.buffer.len(); |
| 319 | self.refresh_line(prompt)?; |
| 320 | } |
| 321 | Ok(()) |
| 322 | } |
| 323 | |
| 324 | fn handle_right_arrow(&mut self) -> io::Result<()> { |
| 325 | if let Some(ch) = self.buffer[self.cursor_pos..].chars().next() { |
| 326 | let next = self.cursor_pos + ch.len_utf8(); |
| 327 | let columns = self.buffer[self.cursor_pos..next].width(); |
| 328 | self.cursor_pos = next; |
| 329 | write!(self.stdout, "{}", Cursor::right(columns))?; |
| 330 | self.stdout.flush()?; |
| 331 | } |
| 332 | Ok(()) |
| 333 | } |
| 334 | |
| 335 | fn handle_left_arrow(&mut self) -> io::Result<()> { |
| 336 | if let Some((previous, _)) = self.buffer[..self.cursor_pos].char_indices().next_back() { |
| 337 | let columns = self.buffer[previous..self.cursor_pos].width(); |
| 338 | self.cursor_pos = previous; |
| 339 | write!(self.stdout, "{}", Cursor::left(columns))?; |
| 340 | self.stdout.flush()?; |
| 341 | } |
| 342 | Ok(()) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | impl Drop for Readline { |
| 347 | fn drop(&mut self) { |
| 348 | unsafe { |
| 349 | libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &self.previous); |
| 350 | } |
| 351 | } |
| 352 | } |