From 1c237c9cb9ff68bd132998bd0540fa2c0441ab1b Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Mon, 8 Mar 2021 13:34:25 -0500 Subject: [PATCH] Open file from filesystem --- src/document.rs | 15 ++++++++++++--- src/editor.rs | 11 ++++++++++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/document.rs b/src/document.rs index cd73874..a51ceda 100644 --- a/src/document.rs +++ b/src/document.rs @@ -1,4 +1,5 @@ use crate::Row; +use std::fs; #[derive(Default)] pub struct Document { @@ -6,10 +7,18 @@ pub struct Document { } impl Document { - pub fn open() -> Self { + pub fn open(filename: &str) -> Result { + let contents = fs::read_to_string(filename)?; + let mut rows = Vec::new(); - rows.push(Row::from("Hello, World!")); - Self { rows } + + for value in contents.lines() { + rows.push(Row::from(value)); + } + + Ok(Self { + rows + }) } pub fn row(&self, index: usize) -> Option<&Row> { diff --git a/src/editor.rs b/src/editor.rs index 0c78ae8..b1001ca 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -1,6 +1,7 @@ use crate::Document; use crate::Row; use crate::Terminal; +use std::env; use termion::event::Key; const VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -34,10 +35,18 @@ impl Editor { } pub fn default() -> Self { + let args: Vec = env::args().collect(); + let document = if args.len() > 1 { + let file_name = &args[1]; + Document::open(&file_name).unwrap_or_default() + } else { + Document::default() + }; + Self { should_quit: false, terminal: Terminal::default().expect("Failed to initialize terminal"), - document: Document::open(), + document, cursor_position: Position::default(), } }