diff --git a/src/document.rs b/src/document.rs index 773c474..ec9efc1 100644 --- a/src/document.rs +++ b/src/document.rs @@ -1,6 +1,7 @@ use crate::Position; use crate::Row; use std::fs; +use std::io::{Error, Write}; #[derive(Default)] pub struct Document { @@ -68,6 +69,19 @@ impl Document { } } + pub fn save(&self) -> Result<(), Error> { + if let Some(file_name) = &self.file_name { + let mut file = fs::File::create(file_name)?; + + for row in &self.rows { + file.write_all(row.as_bytes())?; + file.write_all(b"\n")?; + } + } + + Ok(()) + } + fn insert_newline(&mut self, at: &Position) { if at.y > self.len() { return; diff --git a/src/editor.rs b/src/editor.rs index 4918507..0e0bf5c 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -57,7 +57,7 @@ impl Editor { pub fn default() -> Self { let args: Vec = env::args().collect(); - let mut initial_status = String::from("HELP: Ctrl-Q = quit"); + let mut initial_status = String::from("HELP: Ctrl-S = save | Ctrl-Q = quit"); let document = if args.len() > 1 { let file_name = &args[1]; let doc = Document::open(&file_name); @@ -145,6 +145,13 @@ impl Editor { let pressed_key = Terminal::read_key()?; match pressed_key { Key::Ctrl('q') => self.should_quit = true, + Key::Ctrl('s') => { + if self.document.save().is_ok() { + self.status_message = StatusMessage::from("File saved successfully.".to_string()); + } else { + self.status_message = StatusMessage::from("Error writing file!".to_string()); + } + } Key::Char(c) => { self.document.insert(&self.cursor_position, c); self.move_cursor(Key::Right); diff --git a/src/row.rs b/src/row.rs index b13166e..ec980db 100644 --- a/src/row.rs +++ b/src/row.rs @@ -98,4 +98,8 @@ impl Row { Self::from(&remainder[..]) } + + pub fn as_bytes(&self) -> &[u8] { + self.string.as_bytes() + } } \ No newline at end of file