|
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 |
+ |
|
|
10 |
+ |
use libc; |
|
11 |
+ |
use std::io; |
|
12 |
+ |
use std::io::{Read, Stdin, Stdout, Write}; |
|
13 |
+ |
|
|
14 |
+ |
mod cursor; |
|
15 |
+ |
use cursor::Cursor; |
|
16 |
+ |
|
|
17 |
+ |
|
|
18 |
+ |
const CTRL_A: u8 = 1; |
|
19 |
+ |
const CTRL_C: u8 = 3; |
|
20 |
+ |
const CTRL_D: u8 = 4; |
|
21 |
+ |
const CTRL_E: u8 = 5; |
|
22 |
+ |
const ENTER: u8 = 13; |
|
23 |
+ |
const NEWLINE: u8 = 10; |
|
24 |
+ |
const BACKSPACE: u8 = 127; |
|
25 |
+ |
const DELETE: u8 = 8; |
|
26 |
+ |
const ESC: u8 = 27; |
|
27 |
+ |
|
|
28 |
+ |
|
|
29 |
+ |
const CLEAR_LINE: &str = "\r\x1b[0K"; |
|
30 |
+ |
const CLEAR_SCREEN_FROM_CURSOR: &str = "\x1b[J"; |
|
31 |
+ |
|
|
32 |
+ |
/// Maintains editing state and terminal configuration. |
|
33 |
+ |
pub struct Readline { |
|
34 |
+ |
/// Original terminal settings to restore on drop. |
|
35 |
+ |
previous: libc::termios, |
|
36 |
+ |
/// Saved current line when navigating history. |
|
37 |
+ |
current_line: Option<String>, |
|
38 |
+ |
/// Cached stdout handle. |
|
39 |
+ |
stdout: Stdout, |
|
40 |
+ |
/// Cached stdin handle. |
|
41 |
+ |
stdin: Stdin, |
|
42 |
+ |
/// Current input buffer. |
|
43 |
+ |
buffer: String, |
|
44 |
+ |
/// History of previously entered lines. |
|
45 |
+ |
history: Vec<String>, |
|
46 |
+ |
/// Current position in history when navigating. |
|
47 |
+ |
history_pos: Option<usize>, |
|
48 |
+ |
/// Current cursor position in the buffer. |
|
49 |
+ |
cursor_pos: usize, |
|
50 |
+ |
} |
|
51 |
+ |
|
|
52 |
+ |
impl Readline { |
|
53 |
+ |
/// Creates a new [`Readline`] instance. |
|
54 |
+ |
/// |
|
55 |
+ |
/// Initializes terminal settings and internal buffers. |
|
56 |
+ |
/// Returns error if terminal settings cannot be retrieved. |
|
57 |
+ |
pub fn new() -> io::Result<Self> { |
|
58 |
+ |
let mut previous = unsafe { std::mem::zeroed() }; |
|
59 |
+ |
if unsafe { libc::tcgetattr(libc::STDIN_FILENO, &mut previous) } != 0 { |
|
60 |
+ |
return Err(io::Error::last_os_error()); |
|
61 |
+ |
} |
|
62 |
+ |
|
|
63 |
+ |
let mut raw = previous; |
|
64 |
+ |
raw.c_lflag &= !(libc::ECHO | libc::ICANON | libc::IEXTEN | libc::ISIG); |
|
65 |
+ |
raw.c_iflag &= !(libc::IXON | libc::ICRNL); |
|
66 |
+ |
raw.c_oflag &= !(libc::OPOST); |
|
67 |
+ |
raw.c_cc[libc::VMIN] = 1; |
|
68 |
+ |
raw.c_cc[libc::VTIME] = 0; |
|
69 |
+ |
|
|
70 |
+ |
|
|
71 |
+ |
if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &raw) } != 0 { |
|
72 |
+ |
return Err(io::Error::last_os_error()); |
|
73 |
+ |
} |
|
74 |
+ |
|
|
75 |
+ |
Ok(Readline { |
|
76 |
+ |
buffer: String::with_capacity(1024), |
|
77 |
+ |
previous, |
|
78 |
+ |
history: Vec::new(), |
|
79 |
+ |
history_pos: None, |
|
80 |
+ |
current_line: None, |
|
81 |
+ |
stdout: io::stdout(), |
|
82 |
+ |
stdin: io::stdin(), |
|
83 |
+ |
cursor_pos: 0, |
|
84 |
+ |
}) |
|
85 |
+ |
} |
|
86 |
+ |
|
|
87 |
+ |
/// Adds a line to the history. |
|
88 |
+ |
/// |
|
89 |
+ |
/// Only non-empty lines are added. Duplicate consecutive entries are ignored. |
|
90 |
+ |
pub fn add_history(&mut self, line: String) { |
|
91 |
+ |
if line.trim().is_empty() { |
|
92 |
+ |
return; |
|
93 |
+ |
} |
|
94 |
+ |
if let Some(last) = self.history.last() { |
|
95 |
+ |
if last == &line { |
|
96 |
+ |
return; |
|
97 |
+ |
} |
|
98 |
+ |
} |
|
99 |
+ |
self.history.push(line); |
|
100 |
+ |
} |
|
101 |
+ |
|
|
102 |
+ |
/// Reads a line of input from the user. |
|
103 |
+ |
/// |
|
104 |
+ |
/// Displays the given prompt and handles user input until submission. |
|
105 |
+ |
/// Returns None if `Ctrl-C` or `Ctrl-D` is pressed. |
|
106 |
+ |
pub fn readline(&mut self, prompt: &str) -> io::Result<Option<&str>> { |
|
107 |
+ |
|
|
108 |
+ |
write!(self.stdout, "{}{}", CLEAR_LINE, prompt)?; |
|
109 |
+ |
|
|
110 |
+ |
self.stdout.flush()?; |
|
111 |
+ |
self.buffer.clear(); |
|
112 |
+ |
|
|
113 |
+ |
let mut buf = [0u8; 4]; |
|
114 |
+ |
self.cursor_pos = 0; |
|
115 |
+ |
self.history_pos = None; |
|
116 |
+ |
self.current_line = None; |
|
117 |
+ |
|
|
118 |
+ |
loop { |
|
119 |
+ |
match self.stdin.read(&mut buf[..1]) { |
|
120 |
+ |
Ok(0) => { |
|
121 |
+ |
if self.buffer.is_empty() { |
|
122 |
+ |
return Ok(None); |
|
123 |
+ |
} |
|
124 |
+ |
break; |
|
125 |
+ |
} |
|
126 |
+ |
Ok(_) => {} |
|
127 |
+ |
Err(e) => return Err(e), |
|
128 |
+ |
} |
|
129 |
+ |
match self.handle_keypress(&mut buf, prompt)? { |
|
130 |
+ |
KeyAction::Exit => return Ok(None), |
|
131 |
+ |
KeyAction::Submit => break, |
|
132 |
+ |
KeyAction::Continue => continue, |
|
133 |
+ |
} |
|
134 |
+ |
} |
|
135 |
+ |
self.add_history(self.buffer.clone()); |
|
136 |
+ |
|
|
137 |
+ |
Ok(Some(&self.buffer)) |
|
138 |
+ |
} |
|
139 |
+ |
} |
|
140 |
+ |
|
|
141 |
+ |
|
|
142 |
+ |
enum KeyAction { |
|
143 |
+ |
Exit, |
|
144 |
+ |
Submit, |
|
145 |
+ |
Continue, |
|
146 |
+ |
} |
|
147 |
+ |
|
|
148 |
+ |
impl Readline { |
|
149 |
+ |
/// Move to start of line and clear everything after cursor. |
|
150 |
+ |
/// Then, move cursor back to position if needed. |
|
151 |
+ |
fn refresh_line(&mut self, prompt: &str) -> io::Result<()> { |
|
152 |
+ |
write!(self.stdout, "{}{}{}", CLEAR_LINE, prompt, self.buffer)?; |
|
153 |
+ |
if self.cursor_pos < self.buffer.len() { |
|
154 |
+ |
write!( |
|
155 |
+ |
self.stdout, |
|
156 |
+ |
"{}", |
|
157 |
+ |
Cursor::left(self.buffer.len() - self.cursor_pos) |
|
158 |
+ |
)?; |
|
159 |
+ |
} |
|
160 |
+ |
self.stdout.flush() |
|
161 |
+ |
} |
|
162 |
+ |
|
|
163 |
+ |
fn handle_keypress(&mut self, buf: &mut [u8; 4], prompt: &str) -> io::Result<KeyAction> { |
|
164 |
+ |
match buf[0] { |
|
165 |
+ |
ESC => { |
|
166 |
+ |
|
|
167 |
+ |
self.stdin.read_exact(&mut buf[1..3])?; |
|
168 |
+ |
match &buf[..3] { |
|
169 |
+ |
[ESC, b'[', 51] => { |
|
170 |
+ |
|
|
171 |
+ |
self.stdin.read_exact(&mut buf[3..4])?; |
|
172 |
+ |
if self.cursor_pos < self.buffer.len() { |
|
173 |
+ |
self.buffer.remove(self.cursor_pos); |
|
174 |
+ |
self.refresh_line(prompt)?; |
|
175 |
+ |
} |
|
176 |
+ |
} |
|
177 |
+ |
[ESC, b'[', 65] => self.handle_up_arrow(prompt)?, |
|
178 |
+ |
[ESC, b'[', 66] => self.handle_down_arrow(prompt)?, |
|
179 |
+ |
[ESC, b'[', 67] => self.handle_right_arrow()?, |
|
180 |
+ |
[ESC, b'[', 68] => self.handle_left_arrow()?, |
|
181 |
+ |
_ => {} |
|
182 |
+ |
} |
|
183 |
+ |
Ok(KeyAction::Continue) |
|
184 |
+ |
} |
|
185 |
+ |
CTRL_A => { |
|
186 |
+ |
if self.cursor_pos > 0 { |
|
187 |
+ |
write!(self.stdout, "{}", Cursor::left(self.cursor_pos))?; |
|
188 |
+ |
self.stdout.flush()?; |
|
189 |
+ |
self.cursor_pos = 0; |
|
190 |
+ |
} |
|
191 |
+ |
Ok(KeyAction::Continue) |
|
192 |
+ |
} |
|
193 |
+ |
CTRL_E => { |
|
194 |
+ |
let remaining = self.buffer.len() - self.cursor_pos; |
|
195 |
+ |
if remaining > 0 { |
|
196 |
+ |
write!(self.stdout, "{}", Cursor::right(remaining))?; |
|
197 |
+ |
self.stdout.flush()?; |
|
198 |
+ |
self.cursor_pos = self.buffer.len(); |
|
199 |
+ |
} |
|
200 |
+ |
Ok(KeyAction::Continue) |
|
201 |
+ |
} |
|
202 |
+ |
CTRL_C | CTRL_D => { |
|
203 |
+ |
write!( |
|
204 |
+ |
self.stdout, |
|
205 |
+ |
"{}\r\n{}", |
|
206 |
+ |
CLEAR_SCREEN_FROM_CURSOR, CLEAR_LINE |
|
207 |
+ |
)?; |
|
208 |
+ |
self.stdout.flush()?; |
|
209 |
+ |
Ok(KeyAction::Exit) |
|
210 |
+ |
} |
|
211 |
+ |
ENTER | NEWLINE => { |
|
212 |
+ |
write!(self.stdout, "\r\n")?; |
|
213 |
+ |
self.stdout.flush()?; |
|
214 |
+ |
Ok(KeyAction::Submit) |
|
215 |
+ |
} |
|
216 |
+ |
BACKSPACE | DELETE => { |
|
217 |
+ |
if self.cursor_pos > 0 { |
|
218 |
+ |
self.buffer.remove(self.cursor_pos - 1); |
|
219 |
+ |
self.cursor_pos -= 1; |
|
220 |
+ |
self.refresh_line(prompt)?; |
|
221 |
+ |
} |
|
222 |
+ |
Ok(KeyAction::Continue) |
|
223 |
+ |
} |
|
224 |
+ |
c if c.is_ascii() && !c.is_ascii_control() => { |
|
225 |
+ |
self.buffer.insert(self.cursor_pos, c as char); |
|
226 |
+ |
self.cursor_pos += 1; |
|
227 |
+ |
self.refresh_line(prompt)?; |
|
228 |
+ |
Ok(KeyAction::Continue) |
|
229 |
+ |
} |
|
230 |
+ |
_ => Ok(KeyAction::Continue), |
|
231 |
+ |
} |
|
232 |
+ |
} |
|
233 |
+ |
|
|
234 |
+ |
fn handle_up_arrow(&mut self, prompt: &str) -> io::Result<()> { |
|
235 |
+ |
if self.history_pos.is_none() { |
|
236 |
+ |
self.current_line = Some(self.buffer.clone()); |
|
237 |
+ |
} |
|
238 |
+ |
self.history_pos = match self.history_pos { |
|
239 |
+ |
Some(pos) if pos > 0 => Some(pos - 1), |
|
240 |
+ |
None if !self.history.is_empty() => Some(self.history.len() - 1), |
|
241 |
+ |
other => other, |
|
242 |
+ |
}; |
|
243 |
+ |
|
|
244 |
+ |
if let Some(pos) = self.history_pos { |
|
245 |
+ |
if pos < self.history.len() { |
|
246 |
+ |
self.buffer = self.history[pos].clone(); |
|
247 |
+ |
self.cursor_pos = self.buffer.len(); |
|
248 |
+ |
self.refresh_line(prompt)?; |
|
249 |
+ |
} |
|
250 |
+ |
} |
|
251 |
+ |
Ok(()) |
|
252 |
+ |
} |
|
253 |
+ |
|
|
254 |
+ |
fn handle_down_arrow(&mut self, prompt: &str) -> io::Result<()> { |
|
255 |
+ |
if let Some(pos) = self.history_pos { |
|
256 |
+ |
if pos + 1 < self.history.len() { |
|
257 |
+ |
self.history_pos = Some(pos + 1); |
|
258 |
+ |
self.buffer = self.history[pos + 1].clone(); |
|
259 |
+ |
} else { |
|
260 |
+ |
self.history_pos = None; |
|
261 |
+ |
self.buffer = self.current_line.take().unwrap_or_default(); |
|
262 |
+ |
} |
|
263 |
+ |
self.cursor_pos = self.buffer.len(); |
|
264 |
+ |
self.refresh_line(prompt)?; |
|
265 |
+ |
} |
|
266 |
+ |
Ok(()) |
|
267 |
+ |
} |
|
268 |
+ |
|
|
269 |
+ |
fn handle_right_arrow(&mut self) -> io::Result<()> { |
|
270 |
+ |
if self.cursor_pos < self.buffer.len() { |
|
271 |
+ |
self.cursor_pos += 1; |
|
272 |
+ |
write!(self.stdout, "{}", Cursor::right(1))?; |
|
273 |
+ |
self.stdout.flush()?; |
|
274 |
+ |
} |
|
275 |
+ |
Ok(()) |
|
276 |
+ |
} |
|
277 |
+ |
|
|
278 |
+ |
fn handle_left_arrow(&mut self) -> io::Result<()> { |
|
279 |
+ |
if self.cursor_pos > 0 { |
|
280 |
+ |
self.cursor_pos -= 1; |
|
281 |
+ |
write!(self.stdout, "{}", Cursor::left(1))?; |
|
282 |
+ |
self.stdout.flush()?; |
|
283 |
+ |
} |
|
284 |
+ |
Ok(()) |
|
285 |
+ |
} |
|
286 |
+ |
} |
|
287 |
+ |
|
|
288 |
+ |
impl Drop for Readline { |
|
289 |
+ |
fn drop(&mut self) { |
|
290 |
+ |
unsafe { |
|
291 |
+ |
libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &self.previous); |
|
292 |
+ |
} |
|
293 |
+ |
} |
|
294 |
+ |
} |