feat: implement rudimentary save functionality

This commit is contained in:
Harsh Shandilya 2022-08-11 01:21:28 +05:30
parent 311c59a1e2
commit f46a628ccc
No known key found for this signature in database
GPG Key ID: 366D7BBAD1031E80
3 changed files with 25 additions and 1 deletions

View File

@ -1,6 +1,7 @@
use crate::Position;
use crate::Row;
use std::fs;
use std::io::{Error, Write};
#[derive(Default)]
pub struct Document {
@ -74,4 +75,15 @@ impl Document {
file_name: Some(filename.to_string()),
})
}
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(())
}
}

View File

@ -42,7 +42,7 @@ impl StatusMessage {
impl Default for Editor {
fn default() -> Self {
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-Q = quit, Ctrl-S = save");
let document = if args.len() > 1 {
let file_name = &args[1];
let doc = Document::open(file_name);
@ -85,6 +85,14 @@ 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);

View File

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