summaryrefslogtreecommitdiffstats
path: root/src/line.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/line.rs')
-rw-r--r--src/line.rs415
1 files changed, 415 insertions, 0 deletions
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 @@
1use std::io::{self, IsTerminal, Write};
2use std::path::PathBuf;
3
4use crossterm::cursor::{MoveToColumn, MoveUp};
5use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
6use crossterm::event::{DisableBracketedPaste, EnableBracketedPaste};
7use crossterm::terminal::{self, Clear, ClearType};
8use crossterm::execute;
9
10const HISTORY_LIMIT: usize = 200;
11
12pub struct Editor {
13 interactive: bool,
14 history: Vec<String>,
15 history_index: usize,
16 draft: Vec<char>,
17}
18
19impl Editor {
20 pub fn new() -> Self {
21 Self {
22 interactive: std::io::stdin().is_terminal() && std::io::stdout().is_terminal(),
23 history: load_history(),
24 history_index: 0,
25 draft: Vec::new(),
26 }
27 }
28
29 pub fn is_interactive(&self) -> bool {
30 self.interactive
31 }
32
33 /// Reads one prompt. `None` means end of input (Ctrl-D or EOF).
34 ///
35 /// Raw mode is enabled only for the duration of this call, so Ctrl-C during
36 /// a turn is still a signal handled by `signal`, not a keystroke.
37 pub fn read(&mut self, prompt: &str) -> io::Result<Option<String>> {
38 if !self.interactive {
39 return read_plain();
40 }
41
42 let guard = RawGuard::enable()?;
43 let mut buffer: Vec<char> = Vec::new();
44 let mut cursor = 0usize;
45 let mut rows = 1usize;
46
47 self.history_index = self.history.len();
48 self.draft.clear();
49
50 let width = terminal_width();
51 draw(prompt, &buffer, cursor, width, &mut rows)?;
52
53 loop {
54 let event = event::read()?;
55 match event {
56 Event::Paste(text) => {
57 insert(&mut buffer, &mut cursor, &text);
58 draw(prompt, &buffer, cursor, width, &mut rows)?;
59 }
60 Event::Key(key) if key.kind == KeyEventKind::Press => {
61 match handle_key(key, &mut buffer, &mut cursor, self) {
62 Action::Continue => {}
63 Action::Submit => {
64 // Redraw with the caret at the end so the submitted
65 // line looks complete before we move on.
66 draw(prompt, &buffer, buffer.len(), width, &mut rows)?;
67 drop(guard);
68 let line: String = buffer.iter().collect();
69 self.remember(&line);
70 println!();
71 return Ok(Some(line));
72 }
73 Action::Eof => {
74 drop(guard);
75 println!();
76 return Ok(None);
77 }
78 Action::Cancel => {
79 drop(guard);
80 println!("^C");
81 return Ok(Some(String::new()));
82 }
83 }
84 draw(prompt, &buffer, cursor, width, &mut rows)?;
85 }
86 _ => {}
87 }
88 }
89 }
90
91 fn remember(&mut self, line: &str) {
92 if line.trim().is_empty() {
93 return;
94 }
95 // Prompt-mode commands are not worth recalling.
96 if matches!(line.trim(), "/exit" | "/quit" | "/help" | "/paste") {
97 return;
98 }
99 if self.history.last().map(|last| last.as_str()) == Some(line) {
100 return;
101 }
102 self.history.push(line.to_string());
103 if self.history.len() > HISTORY_LIMIT {
104 self.history.remove(0);
105 }
106 append_history(line);
107 }
108}
109
110/// Plain line reading for pipes, scripts and tests. Identical contract.
111fn read_plain() -> io::Result<Option<String>> {
112 let mut line = String::new();
113 if io::stdin().read_line(&mut line)? == 0 {
114 return Ok(None);
115 }
116 Ok(Some(line.trim_end_matches(['\n', '\r']).to_string()))
117}
118
119enum Action {
120 Continue,
121 Submit,
122 Eof,
123 Cancel,
124}
125
126fn handle_key(
127 key: KeyEvent,
128 buffer: &mut Vec<char>,
129 cursor: &mut usize,
130 editor: &mut Editor,
131) -> Action {
132 let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
133
134 match key.code {
135 KeyCode::Enter => return Action::Submit,
136 // Ctrl-J is what a pipe or a test harness sends for a newline; terminals
137 // send CR for Enter, so both have to submit.
138 KeyCode::Char('j') if ctrl => return Action::Submit,
139 KeyCode::Char('d') if ctrl => {
140 if buffer.is_empty() {
141 return Action::Eof;
142 }
143 if *cursor < buffer.len() {
144 buffer.remove(*cursor);
145 }
146 }
147 KeyCode::Char('c') if ctrl => return Action::Cancel,
148 KeyCode::Char('a') if ctrl => *cursor = 0,
149 KeyCode::Char('e') if ctrl => *cursor = buffer.len(),
150 KeyCode::Char('u') if ctrl => {
151 buffer.clear();
152 *cursor = 0;
153 }
154 KeyCode::Char('k') if ctrl => buffer.truncate(*cursor),
155 KeyCode::Char('w') if ctrl => {
156 let mut end = *cursor;
157 while end > 0 && buffer[end - 1].is_whitespace() {
158 end -= 1;
159 }
160 while end > 0 && !buffer[end - 1].is_whitespace() {
161 end -= 1;
162 }
163 buffer.drain(end..*cursor);
164 *cursor = end;
165 }
166 KeyCode::Char(ch) if !ctrl => {
167 buffer.insert(*cursor, ch);
168 *cursor += 1;
169 }
170 KeyCode::Tab => {
171 for _ in 0..4 {
172 buffer.insert(*cursor, ' ');
173 *cursor += 1;
174 }
175 }
176 KeyCode::Backspace => {
177 if *cursor > 0 {
178 buffer.remove(*cursor - 1);
179 *cursor -= 1;
180 }
181 }
182 KeyCode::Delete => {
183 if *cursor < buffer.len() {
184 buffer.remove(*cursor);
185 }
186 }
187 KeyCode::Left => *cursor = cursor.saturating_sub(1),
188 KeyCode::Right => *cursor = (*cursor + 1).min(buffer.len()),
189 KeyCode::Home => *cursor = 0,
190 KeyCode::End => *cursor = buffer.len(),
191 KeyCode::Up => editor.history_up(buffer, cursor),
192 KeyCode::Down => editor.history_down(buffer, cursor),
193 _ => {}
194 }
195 Action::Continue
196}
197
198impl Editor {
199 fn history_up(&mut self, buffer: &mut Vec<char>, cursor: &mut usize) {
200 if self.history.is_empty() || self.history_index == 0 {
201 return;
202 }
203 if self.history_index == self.history.len() {
204 self.draft = buffer.clone();
205 }
206 self.history_index -= 1;
207 *buffer = self.history[self.history_index].chars().collect();
208 *cursor = buffer.len();
209 }
210
211 fn history_down(&mut self, buffer: &mut Vec<char>, cursor: &mut usize) {
212 if self.history_index >= self.history.len() {
213 return;
214 }
215 self.history_index += 1;
216 if self.history_index == self.history.len() {
217 *buffer = self.draft.clone();
218 } else {
219 *buffer = self.history[self.history_index].chars().collect();
220 }
221 *cursor = buffer.len();
222 }
223}
224
225fn insert(buffer: &mut Vec<char>, cursor: &mut usize, text: &str) {
226 let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
227 for (offset, ch) in normalized.chars().enumerate() {
228 buffer.insert(*cursor + offset, ch);
229 }
230 *cursor += normalized.chars().count();
231}
232
233fn terminal_width() -> usize {
234 match terminal::size() {
235 // A pty with no size reported reports 0 columns; treating that as 1
236 // would make every character wrap onto its own line.
237 Ok((cols, _)) if cols > 0 => cols as usize,
238 _ => 80,
239 }
240}
241
242/// Position of the cursor after consuming `prompt` plus `buffer[..upto]`.
243/// Approximates every character as one column; good enough for a prompt line.
244fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, usize) {
245 let mut row = 0usize;
246 let mut col = 0usize;
247 for ch in prompt.chars().chain(buffer[..upto.min(buffer.len())].iter().copied()) {
248 advance(ch, &mut row, &mut col, width);
249 }
250 (row, col)
251}
252
253fn advance(ch: char, row: &mut usize, col: &mut usize, width: usize) {
254 if ch == '\n' {
255 *row += 1;
256 *col = 0;
257 return;
258 }
259 *col += 1;
260 if *col >= width {
261 *col = 0;
262 *row += 1;
263 }
264}
265
266fn draw(
267 prompt: &str,
268 buffer: &[char],
269 cursor: usize,
270 width: usize,
271 rows: &mut usize,
272) -> io::Result<()> {
273 let mut out = io::stdout();
274
275 let total = layout(prompt, buffer, buffer.len(), width).0 + 1;
276 let (cursor_row, cursor_col) = layout(prompt, buffer, cursor, width);
277
278 if *rows > 1 {
279 execute!(out, MoveUp((*rows - 1) as u16))?;
280 }
281 execute!(out, MoveToColumn(0), Clear(ClearType::FromCursorDown))?;
282
283 let mut text = String::with_capacity(prompt.len() + buffer.len());
284 text.push_str(prompt);
285 for ch in buffer {
286 if *ch == '\n' {
287 text.push_str("\r\n");
288 } else {
289 text.push(*ch);
290 }
291 }
292 out.write_all(text.as_bytes())?;
293
294 let end_row = total - 1;
295 if end_row > cursor_row {
296 execute!(out, MoveUp((end_row - cursor_row) as u16))?;
297 }
298 execute!(out, MoveToColumn(cursor_col as u16))?;
299 out.flush()?;
300
301 *rows = total;
302 Ok(())
303}
304
305struct RawGuard;
306
307impl RawGuard {
308 fn enable() -> io::Result<Self> {
309 terminal::enable_raw_mode()?;
310 execute!(io::stdout(), EnableBracketedPaste)?;
311 Ok(RawGuard)
312 }
313}
314
315impl Drop for RawGuard {
316 fn drop(&mut self) {
317 let _ = execute!(io::stdout(), DisableBracketedPaste);
318 let _ = terminal::disable_raw_mode();
319 }
320}
321
322fn history_path() -> PathBuf {
323 crate::session::data_root().join("history")
324}
325
326fn load_history() -> Vec<String> {
327 let text = std::fs::read_to_string(history_path()).unwrap_or_default();
328 let mut lines: Vec<String> = text
329 .split('\n')
330 .filter(|line| !line.trim().is_empty() && !line.starts_with('\u{0}'))
331 .map(|line| line.replace('\u{0}', "\n"))
332 .collect();
333 if lines.len() > HISTORY_LIMIT {
334 lines.drain(..lines.len() - HISTORY_LIMIT);
335 }
336 lines
337}
338
339fn append_history(line: &str) {
340 let path = history_path();
341 if let Some(parent) = path.parent() {
342 let _ = std::fs::create_dir_all(parent);
343 }
344 if let Ok(mut file) = std::fs::OpenOptions::new()
345 .create(true)
346 .append(true)
347 .open(&path)
348 {
349 // One record per line, so newlines inside a prompt are escaped.
350 let _ = writeln!(file, "{}", line.replace('\n', "\u{0}"));
351 }
352}
353
354#[cfg(test)]
355mod tests {
356 use super::*;
357
358 #[test]
359 fn layout_accounts_for_newlines() {
360 let buffer: Vec<char> = "ab\ncd".chars().collect();
361 assert_eq!(layout("> ", &buffer, 0, 80), (0, 2));
362 assert_eq!(layout("> ", &buffer, 2, 80), (0, 4));
363 assert_eq!(layout("> ", &buffer, 3, 80), (1, 0));
364 assert_eq!(layout("> ", &buffer, 5, 80), (1, 2));
365 }
366
367 #[test]
368 fn layout_wraps_at_the_terminal_width() {
369 let buffer: Vec<char> = "abcdef".chars().collect();
370 // Prompt takes 2 columns, so the 6 chars fill exactly 8.
371 assert_eq!(layout("> ", &buffer, 6, 8), (1, 0));
372 assert_eq!(layout("> ", &buffer, 3, 8), (0, 5));
373 }
374
375 #[test]
376 fn width_falls_back_when_the_terminal_reports_none() {
377 // Cannot control the real terminal here, but the fallback path must not
378 // produce a one-column layout.
379 assert!(terminal_width() >= 1);
380 }
381
382 #[test]
383 fn insert_normalises_line_endings() {
384 let mut buffer = vec!['a'];
385 let mut cursor = 1;
386 insert(&mut buffer, &mut cursor, "b\r\nc");
387 assert_eq!(buffer, vec!['a', 'b', '\n', 'c']);
388 assert_eq!(cursor, 4);
389 }
390
391 #[test]
392 fn history_walks_both_ways() {
393 let mut editor = Editor {
394 interactive: false,
395 history: vec!["one".into(), "two".into()],
396 history_index: 0,
397 draft: Vec::new(),
398 };
399 editor.history_index = editor.history.len();
400
401 let mut buffer = vec!['x'];
402 let mut cursor = 1;
403 editor.history_up(&mut buffer, &mut cursor);
404 assert_eq!(buffer.iter().collect::<String>(), "two");
405 editor.history_up(&mut buffer, &mut cursor);
406 assert_eq!(buffer.iter().collect::<String>(), "one");
407 editor.history_up(&mut buffer, &mut cursor);
408 assert_eq!(buffer.iter().collect::<String>(), "one");
409
410 editor.history_down(&mut buffer, &mut cursor);
411 assert_eq!(buffer.iter().collect::<String>(), "two");
412 editor.history_down(&mut buffer, &mut cursor);
413 assert_eq!(buffer.iter().collect::<String>(), "x");
414 }
415}