Open file from filesystem

This commit is contained in:
Timothy Warren 2021-03-08 13:34:25 -05:00
parent 7e8493410f
commit 1c237c9cb9
2 changed files with 22 additions and 4 deletions

View File

@ -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<Self, std::io::Error> {
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> {

View File

@ -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<String> = 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(),
}
}