Gracefully handle opening an empty file
This commit is contained in:
parent
93ac2604b2
commit
8825cdb058
@ -1271,21 +1271,32 @@ impl Editor {
|
||||
|
||||
/// Open a file for display
|
||||
pub fn open(&mut self, filename: &str) -> io::Result<()> {
|
||||
self.filename = filename.to_owned();
|
||||
let file = File::open(filename);
|
||||
|
||||
self.select_syntax_highlight();
|
||||
match file {
|
||||
Ok(_) => {
|
||||
let buf_reader = BufReader::new(file.unwrap());
|
||||
|
||||
let file = File::open(&self.filename)?;
|
||||
let buf_reader = BufReader::new(file);
|
||||
let lines = buf_reader.lines().map(|l| clean_unwrap(l));
|
||||
|
||||
let lines = buf_reader.lines().map(|l| clean_unwrap(l));
|
||||
for line in lines {
|
||||
self.insert_row(self.rows.len(), &line);
|
||||
}
|
||||
|
||||
for line in lines {
|
||||
self.insert_row(self.rows.len(), &line);
|
||||
// Make sure the whole file is loaded before
|
||||
// showing the filename and selecting the syntax
|
||||
// for highlighting
|
||||
self.filename = filename.to_owned();
|
||||
self.select_syntax_highlight();
|
||||
|
||||
self.dirty = 0;
|
||||
},
|
||||
// Gracefully handle errors opening a file
|
||||
Err(e) => {
|
||||
self.set_status_message(&e.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
self.dirty = 0;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -1311,7 +1322,7 @@ impl Editor {
|
||||
|
||||
self.set_status_message(&format!("{} bytes written to disk", data.len()));
|
||||
}
|
||||
Err(e) => self.set_status_message(&format!("Failed to save: {:?}", e)),
|
||||
Err(e) => self.set_status_message(&format!("Failed to save: {}", e.to_string())),
|
||||
};
|
||||
|
||||
file.sync_all()?;
|
||||
|
@ -36,10 +36,10 @@ fn main() -> Result<(), Error> {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
if args.len() >= 2 {
|
||||
editor.open(&args[1])?;
|
||||
} else {
|
||||
editor.set_status_message("HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find");
|
||||
}
|
||||
|
||||
editor.set_status_message("HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find");
|
||||
|
||||
// Main input loop. Editor::process_keypress uses an Option Enum as a sentinel.
|
||||
// `None` is returned on a quit action, in other cases, `Some(())` is returned,
|
||||
// continuing the loop
|
||||
|
Loading…
Reference in New Issue
Block a user