feat(editor): allow opening files passed through argv

This commit is contained in:
Harsh Shandilya 2022-08-07 23:28:18 +05:30
parent ad46738140
commit efde3d3440
No known key found for this signature in database
GPG Key ID: 366D7BBAD1031E80
2 changed files with 19 additions and 2 deletions

View File

@ -1,4 +1,5 @@
use crate::Row;
use std::fs;
#[derive(Default)]
pub struct Document {
@ -13,4 +14,13 @@ impl Document {
pub fn is_empty(&self) -> bool {
self.rows.is_empty()
}
pub fn open(filename: &str) -> Result<Self, std::io::Error> {
let contents = fs::read_to_string(filename)?;
let mut rows = vec![];
for line in contents.lines() {
rows.push(Row::from(line));
}
Ok(Self { rows })
}
}

View File

@ -1,5 +1,5 @@
use crate::{Document, Row, Terminal};
use std::io;
use std::{io, env};
use std::result::Result;
use termion::event::Key;
@ -21,10 +21,17 @@ pub struct Position {
impl Default for Editor {
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::default(),
document,
cursor_position: Position::default(),
}
}