From cf0c576284727035cc3fa5923bdb7d7be1a99d79 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Wed, 10 Mar 2021 15:33:41 -0500 Subject: [PATCH] Add quit confirmation on unsaved changes --- src/editor.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/editor.rs b/src/editor.rs index 2f45582..f2f3bac 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -10,6 +10,7 @@ use termion::event::Key; const STATUS_FG_COLOR: color::Rgb = color::Rgb(63, 63, 63); const STATUS_BG_COLOR: color::Rgb = color::Rgb(239, 239, 239); const VERSION: &str = env!("CARGO_PKG_VERSION"); +const QUIT_TIMES: u8 = 3; #[derive(Default)] pub struct Position { @@ -42,6 +43,7 @@ pub struct Editor { offset: Position, document: Document, status_message: StatusMessage, + quit_times: u8, } impl Editor { @@ -82,6 +84,7 @@ impl Editor { cursor_position: Position::default(), offset: Position::default(), status_message: StatusMessage::from(initial_status), + quit_times: QUIT_TIMES, } } @@ -176,7 +179,20 @@ impl Editor { fn process_keypress(&mut self) -> Result<(), std::io::Error> { let pressed_key = Terminal::read_key()?; match pressed_key { - Key::Ctrl('q') => self.should_quit = true, + Key::Ctrl('q') => { + if self.quit_times > 0 && self.document.is_dirty() { + self.status_message = StatusMessage::from(format!( + "WARNING! File has unsaved changes. Press Ctrl-Q {} more times to quit.", + self.quit_times + )); + + self.quit_times -= 1; + + return Ok(()); + } + + self.should_quit = true + }, Key::Ctrl('s') => self.save(), Key::Char(c) => { self.document.insert(&self.cursor_position, c); @@ -202,6 +218,12 @@ impl Editor { self.scroll(); + // Reset quit confirmation count if not Ctrl-Q input + if self.quit_times < QUIT_TIMES { + self.quit_times = QUIT_TIMES; + self.status_message = StatusMessage::default(); + } + Ok(()) }