From 7ee14621b3850b9eaaf25d808004c75a34f34eb3 Mon Sep 17 00:00:00 2001 From: Garrit Franke Date: Thu, 14 Jan 2021 18:38:19 +0100 Subject: [PATCH] Load file to buffer --- src/main.rs | 47 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/src/main.rs b/src/main.rs index 3de3ba8..046023c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,14 +4,16 @@ use crate::termion::cursor::DetectCursorPos; use std::fmt::Debug; use std::fmt::Display; use std::io::{stdin, stdout, Write}; +use std::path::Path; use termion::event::Key; use termion::input::TermRead; use termion::raw::IntoRawMode; use termion::screen::*; -struct Editor { +struct Editor<'a> { screen: Box, mode: Mode, + file_path: Option<&'a Path>, } #[derive(Eq, PartialEq, Debug)] @@ -20,22 +22,34 @@ enum Mode { Insert, } -impl Editor { - pub fn new() -> Self { - let mut screen = AlternateScreen::from(stdout().into_raw_mode().unwrap()); - - write!( - screen, - "{}{}", - termion::clear::All, - termion::cursor::Goto(1, 1), - ); - - screen.flush().unwrap(); - Self { +impl<'a> Editor<'a> { + pub fn new(path: Option<&'a Path>) -> Self { + let screen = AlternateScreen::from(stdout().into_raw_mode().unwrap()); + let mut s = Self { screen: Box::new(screen), mode: Mode::Normal, + file_path: path, + }; + s.write(&termion::clear::All); + s.write(&termion::cursor::Goto(1, 1)); + + match path { + Some(p) => { + let file_contents = std::fs::read(p).expect("Could not read file"); + for b in file_contents.iter() { + if *b as char == '\n' { + s.write_newline(); + } else { + s.write(&(*b as char)); + } + } + } + None => {} } + + s.flush(); + + s } pub fn write(&mut self, w: &dyn Display) { @@ -82,7 +96,10 @@ impl Editor { fn main() { let stdin = stdin(); - let mut editor = Editor::new(); + let args: Vec = std::env::args().collect(); + + let file_path = Path::new(args.get(1).expect("usage: rim ")); + let mut editor = Editor::new(Some(file_path)); editor.enter_mode(Mode::Normal); for c in stdin.keys() { let key = c.unwrap(); -- 2.45.2