Add Ctrl-W readline shortcut (delete previous word)
@@ -22,6 +22,24 @@ pub fn handler(key: Key, app: &mut App) {
app.input_idx = 0;
app.input_cursor_position = 0;
}
+ Key::Ctrl('w') => {
+ if app.input_cursor_position == 0 {
+ return;
+ }
+ let word_end = match app.input[..app.input_idx].iter().rposition(|&x| x != ' ') {
+ Some(index) => index + 1,
+ None => 0,
+ };
+ let word_start = match app.input[..word_end].iter().rposition(|&x| x == ' ') {
+ Some(index) => index + 1,
+ None => 0,
+ };
+ let deleted: String = app.input[word_start..app.input_idx].iter().collect();
+ let deleted_len: u16 = UnicodeWidthStr::width(deleted.as_str()).try_into().unwrap();
+ app.input.drain(word_start..app.input_idx);
+ app.input_idx = word_start;
+ app.input_cursor_position -= deleted_len;
+ }
Key::Ctrl('e') => {
app.input_idx = app.input.len();
let input_string: String = app.input.iter().collect();
@@ -170,6 +188,45 @@ mod tests {
assert_eq!(app.input, str_to_vec_char("My"));
}
+ #[test]
+ fn test_input_handler_ctrl_w() {
+ let mut app = App::default();
+
+ app.input = str_to_vec_char("My text");
+
+ handler(Key::Ctrl('w'), &mut app);
+ assert_eq!(app.input, str_to_vec_char("My text"));
+
+ app.input_cursor_position = 3;
+ app.input_idx = 3;
+ handler(Key::Ctrl('w'), &mut app);
+ assert_eq!(app.input, str_to_vec_char("text"));
+ assert_eq!(app.input_cursor_position, 0);
+ assert_eq!(app.input_idx, 0);
+
+ app.input = str_to_vec_char(" ");
+ app.input_cursor_position = 3;
+ app.input_idx = 3;
+ handler(Key::Ctrl('w'), &mut app);
+ assert_eq!(app.input, str_to_vec_char(" "));
+ assert_eq!(app.input_cursor_position, 0);
+ assert_eq!(app.input_idx, 0);
+ app.input_cursor_position = 1;
+ app.input_idx = 1;
+ handler(Key::Ctrl('w'), &mut app);
+ assert_eq!(app.input, str_to_vec_char(""));
+ assert_eq!(app.input_cursor_position, 0);
+ assert_eq!(app.input_idx, 0);
+
+ app.input = str_to_vec_char("Hello there ");
+ app.input_cursor_position = 13;
+ app.input_idx = 13;
+ handler(Key::Ctrl('w'), &mut app);
+ assert_eq!(app.input, str_to_vec_char("Hello "));
+ assert_eq!(app.input_cursor_position, 6);
+ assert_eq!(app.input_idx, 6);
+ }
+
#[test]
fn test_input_handler_esc_back_to_playlist() {
let mut app = App::default();
