Basic file save

This commit is contained in:
Timothy Warren 2021-03-10 14:51:11 -05:00
parent 2697d41264
commit 31e5fd6633
3 changed files with 26 additions and 1 deletions

View File

@ -1,6 +1,7 @@
use crate::Position; use crate::Position;
use crate::Row; use crate::Row;
use std::fs; use std::fs;
use std::io::{Error, Write};
#[derive(Default)] #[derive(Default)]
pub struct Document { 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) { fn insert_newline(&mut self, at: &Position) {
if at.y > self.len() { if at.y > self.len() {
return; return;

View File

@ -57,7 +57,7 @@ impl Editor {
pub fn default() -> Self { pub fn default() -> Self {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = 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 document = if args.len() > 1 {
let file_name = &args[1]; let file_name = &args[1];
let doc = Document::open(&file_name); let doc = Document::open(&file_name);
@ -145,6 +145,13 @@ impl Editor {
let pressed_key = Terminal::read_key()?; let pressed_key = Terminal::read_key()?;
match pressed_key { match pressed_key {
Key::Ctrl('q') => self.should_quit = true, 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) => { Key::Char(c) => {
self.document.insert(&self.cursor_position, c); self.document.insert(&self.cursor_position, c);
self.move_cursor(Key::Right); self.move_cursor(Key::Right);

View File

@ -98,4 +98,8 @@ impl Row {
Self::from(&remainder[..]) Self::from(&remainder[..])
} }
pub fn as_bytes(&self) -> &[u8] {
self.string.as_bytes()
}
} }