Dirty checking

This commit is contained in:
Timothy Warren 2021-03-10 15:26:12 -05:00
parent 49ec4084c2
commit 72e723ffa5
2 changed files with 32 additions and 7 deletions

View File

@ -7,6 +7,7 @@ use std::io::{Error, Write};
pub struct Document {
rows: Vec<Row>,
pub file_name: Option<String>,
dirty: bool,
}
impl Document {
@ -22,6 +23,7 @@ impl Document {
Ok(Self {
rows,
file_name: Some(filename.to_string()),
dirty: false,
})
}
@ -38,6 +40,13 @@ impl Document {
}
pub fn insert(&mut self, at: &Position, c: char) {
if at.y > self.len() {
return;
}
// File has been modified
self.dirty = true;
if c == '\n' {
self.insert_newline(at);
return;
@ -47,7 +56,7 @@ impl Document {
let mut row = Row::default();
row.insert(0, c);
self.rows.push(row);
} else if at.y < self.len() {
} else {
let row = self.rows.get_mut(at.y).unwrap();
row.insert(at.x, c);
}
@ -59,6 +68,9 @@ impl Document {
return
}
// File has been modified
self.dirty = true;
if at.x == self.rows.get_mut(at.y).unwrap().len() && at.y < len - 1 {
let next_row = self.rows.remove(at.y + 1);
let row = self.rows.get_mut(at.y).unwrap();
@ -69,7 +81,7 @@ impl Document {
}
}
pub fn save(&self) -> Result<(), Error> {
pub fn save(&mut self) -> Result<(), Error> {
if let Some(file_name) = &self.file_name {
let mut file = fs::File::create(file_name)?;
@ -77,16 +89,19 @@ impl Document {
file.write_all(row.as_bytes())?;
file.write_all(b"\n")?;
}
// File has been cleaned! (Saved)
self.dirty = false;
}
Ok(())
}
fn insert_newline(&mut self, at: &Position) {
if at.y > self.len() {
return;
}
pub fn is_dirty(&self) -> bool {
self.dirty
}
fn insert_newline(&mut self, at: &Position) {
if at.y == self.len() {
self.rows.push(Row::default());
return;

View File

@ -107,6 +107,11 @@ impl Editor {
fn draw_status_bar(&self) {
let mut status;
let width = self.terminal.size().width as usize;
let modified_indicator = if self.document.is_dirty() {
" (modified)"
} else {
""
};
let mut file_name = "[No Name]".to_string();
if let Some(name) = &self.document.file_name {
@ -114,7 +119,12 @@ impl Editor {
file_name.truncate(20);
}
status = format!("{} - {} lines", file_name, self.document.len());
status = format!(
"{} - {} lines{}",
file_name,
self.document.len(),
modified_indicator
);
let line_indicator = format!(
"{}/{}",