From 9f5512442177b1242e40c25c14b0ae5d8e6f5359 Mon Sep 17 00:00:00 2001 From: Rory Dudley Date: Mon, 30 Sep 2024 21:55:34 -0600 Subject: Slight refactor of getchar() and more handling for getline() The getchar() function was changed so that it is able to detect some ANSI escape sequences. To better handle this, getchar() now returns a value from the Key enum, indicating whether or not an escape sequence was found. Currently, the only escape sequences the function deals with are arrow keys. Handling of the left and right arrow keys were added to the getline() function, in order to allow a user to go back and edit their command inplace. Up and down arrow keys are also handled, but they are just ignored for now (i.e. they do not move the cursor around anymore). The local 'pos' variable became an Arc>, since it needs to be reset to 0 if ctrl-c is pressed (the handler for which is outside the scope of getline()). Signed-off-by: Rory Dudley --- src/main.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index d5147ff..527fb8c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,7 +25,12 @@ use termios::{tcsetattr, Termios, ECHO, ICANON, TCSANOW}; /// repl(&mut away, &mut env); /// } /// ``` -fn repl(away: &mut Arc>, buffer: &mut Arc>>, env: &mut Environment) { +fn repl( + away: &mut Arc>, + buffer: &mut Arc>>, + pos: &mut Arc>, + env: &mut Environment, +) { // Setup termios flags let mut termios = Termios::from_fd(STDIN).unwrap(); termios.c_lflag &= !(ICANON | ECHO); @@ -55,7 +60,7 @@ fn repl(away: &mut Arc>, buffer: &mut Arc>>, env: &mut *away.lock().unwrap() = false; // Wait for user input - let bytes = getline(buffer); + let bytes = getline(buffer, pos); // Check if we've reached EOF (i.e. ) if bytes == 0 { @@ -145,11 +150,14 @@ fn main() { // Handle signals let mut away = Arc::new(Mutex::new(true)); let mut buffer: Arc>> = Arc::new(Mutex::new(vec![])); + let mut pos: Arc> = Arc::new(Mutex::new(0)); unsafe { let away = Arc::clone(&away); let buffer = Arc::clone(&buffer); + let pos = Arc::clone(&pos); signal_hook::low_level::register(signal_hook::consts::SIGINT, move || { buffer.lock().unwrap().clear(); + *pos.lock().unwrap() = 0; if *away.lock().unwrap() { println!(); } else { @@ -168,5 +176,5 @@ fn main() { options(&mut env); // Begin evaluating commands - repl(&mut away, &mut buffer, &mut env); + repl(&mut away, &mut buffer, &mut pos, &mut env); } -- cgit v1.2.3