diff --git a/src/event.rs b/src/event.rs index f887b15..a17abb7 100644 --- a/src/event.rs +++ b/src/event.rs @@ -67,22 +67,47 @@ impl Events { } } + fn first_byte(&mut self) -> u8 { + let byte = self.buffer[0]; + self.buffer = self.buffer[1..].to_vec(); + byte + } + + fn parse(&mut self) -> Event { + let byte = self.first_byte(); + match byte { + ESC => self.parse_esc(), + BS => Event::Key(Key::Backspace, Mod::None), + DEL => Event::Key(Key::Delete, Mod::None), + LF | CR => Event::Key(Key::Enter, Mod::None), + TAB => Event::Key(Key::Tab, Mod::None), + x @ 1..=26 => Event::Key(Key::Char((x + 96).into()), Mod::Ctrl), // ctrl + letter + x @ b' '..=b'~' => Event::Key(Key::Char(x.into()), Mod::None), // regular ascii charaters + x => Event::Unsupported(vec![x]), + } + } + fn parse_esc(&mut self) -> Event { if self.buffer.is_empty() { return Event::Key(Key::Escape, Mod::None); } - let byte = self.buffer[0]; - self.buffer = self.buffer[1..].to_vec(); + let byte = self.first_byte(); match byte { - ESC => Event::Key(Key::Escape, Mod::None), + ESC => { + // Two ESC chars in a row probably means that the first one was an escape key press + // and the second one was for something else, possibly because input is coming all at once from a file. + // Therefore reinsert the second ESC byte so it can be processed next iteration. + self.buffer.insert(0, ESC); + Event::Key(Key::Escape, Mod::None) + } BS => Event::Key(Key::Backspace, Mod::Alt), DEL => Event::Key(Key::Delete, Mod::Alt), LF | CR => Event::Key(Key::Enter, Mod::Alt), TAB => Event::Key(Key::Tab, Mod::Alt), - c @ 1..=26 => Event::Key(Key::Char((c + 96).into()), Mod::CtrlAlt), // ctrl + letter - c @ b' '..=b'~' => Event::Key(Key::Char(c.into()), Mod::Alt), // regular ascii charaters - _ => Event::Unsupported(vec![ESC, byte]), + x @ 1..=26 => Event::Key(Key::Char((x + 96).into()), Mod::CtrlAlt), // ctrl + letter + x @ b' '..=b'~' => Event::Key(Key::Char(x.into()), Mod::Alt), // regular ascii charaters + x => Event::Unsupported(vec![ESC, x]), } } } @@ -96,17 +121,6 @@ impl Iterator for Events { return None; } - let byte = self.buffer[0]; - self.buffer = self.buffer[1..].to_vec(); - Some(match byte { - ESC => self.parse_esc(), - BS => Event::Key(Key::Backspace, Mod::None), - DEL => Event::Key(Key::Delete, Mod::None), - LF | CR => Event::Key(Key::Enter, Mod::None), - TAB => Event::Key(Key::Tab, Mod::None), - c @ 1..=26 => Event::Key(Key::Char((c + 96).into()), Mod::Ctrl), // ctrl + letter - c @ b' '..=b'~' => Event::Key(Key::Char(c.into()), Mod::None), // regular ascii charaters - _ => Event::Unsupported(vec![byte]), - }) + Some(self.parse()) } }