From 33ee68acadd01598a678d6a2236c9f6ab802f90b Mon Sep 17 00:00:00 2001 From: CrispyPin Date: Tue, 28 Feb 2023 20:56:24 +0100 Subject: [PATCH] open several files when provided as args --- src/editor.rs | 27 +++++++++++++++------------ src/main.rs | 10 +++++----- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/editor.rs b/src/editor.rs index 205a6af..d50d7d3 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -3,6 +3,7 @@ use std::{ io::{stdin, stdout, Write}, ops::Range, process::exit, + vec, }; use termion::{ clear, cursor, @@ -34,29 +35,31 @@ struct Cursor { type Line = Range; impl Editor { - pub fn new(path: Option) -> Self { - let text = path - .as_ref() - .map(|path| { - fs::read_to_string(path).unwrap_or_else(|err| { - println!("Error: {err}"); - exit(1); - }) - }) - .unwrap_or_default(); - + pub fn new(path: String) -> Self { + let text = fs::read_to_string(&path).unwrap_or_default(); let mut this = Editor { text, lines: Vec::new(), scroll: 0, cursor: Cursor { line: 0, column: 0 }, - path, + path: Some(path), active: false, }; this.find_lines(); this } + pub fn new_empty() -> Self { + Editor { + text: String::new(), + lines: vec![0..0], + scroll: 0, + cursor: Cursor { line: 0, column: 0 }, + path: None, + active: false, + } + } + pub fn name(&self) -> &str { self.path.as_ref().map_or("untitled", |s| s) } diff --git a/src/main.rs b/src/main.rs index 2df81d1..f1228e7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,7 +16,7 @@ mod util; use editor::Editor; fn main() { - Navigator::new(env::args().nth(1)).run(); + Navigator::new().run(); } struct Navigator { @@ -27,13 +27,13 @@ struct Navigator { } impl Navigator { - fn new(immediate_file: Option) -> Self { + fn new() -> Self { let term = stdout().into_raw_mode().unwrap(); - let editors = vec![Editor::new(immediate_file)]; + let editors = env::args().skip(1).map(Editor::new).collect(); Self { editors, selected: Some(0), - path: String::new(), // TODO + path: String::new(), _term: term, } } @@ -105,7 +105,7 @@ impl Navigator { fn new_editor(&mut self) { self.selected = Some(self.editors.len()); - self.editors.push(Editor::new(None)); + self.editors.push(Editor::new_empty()); self.open_selected(); }