diff --git a/src/document.rs b/src/document.rs index 1a2d1b1..cd73874 100644 --- a/src/document.rs +++ b/src/document.rs @@ -3,4 +3,20 @@ use crate::Row; #[derive(Default)] pub struct Document { rows: Vec, +} + +impl Document { + pub fn open() -> Self { + let mut rows = Vec::new(); + rows.push(Row::from("Hello, World!")); + Self { rows } + } + + pub fn row(&self, index: usize) -> Option<&Row> { + self.rows.get(index) + } + + pub fn is_empty(&self) -> bool { + self.rows.is_empty() + } } \ No newline at end of file diff --git a/src/editor.rs b/src/editor.rs index 0240284..0c78ae8 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -1,4 +1,5 @@ use crate::Document; +use crate::Row; use crate::Terminal; use termion::event::Key; @@ -36,7 +37,7 @@ impl Editor { Self { should_quit: false, terminal: Terminal::default().expect("Failed to initialize terminal"), - document: Document::default(), + document: Document::open(), cursor_position: Position::default(), } } @@ -112,13 +113,22 @@ impl Editor { println!("{}\r", welcome_message); } + pub fn draw_row(&self, row: &Row) { + let start = 0; + let end = self.terminal.size().width as usize; + let row = row.render(start, end); + println!("{}\r", row); + } + fn draw_rows(&self) { let height = self.terminal.size().height; - for row in 0..height - 1 { + for terminal_row in 0..height - 1 { Terminal::clear_current_line(); - if row == height / 3 { + if let Some(row) = self.document.row(terminal_row as usize) { + self.draw_row(row); + } else if self.document.is_empty() && terminal_row == height / 3 { self.draw_welcome_message(); } else { println!("~\r"); diff --git a/src/row.rs b/src/row.rs index 5a74fc3..6d30a4d 100644 --- a/src/row.rs +++ b/src/row.rs @@ -1,3 +1,21 @@ +use std::cmp; + pub struct Row { string: String, +} + +impl From<&str> for Row { + fn from(slice: &str) -> Self { + Self { + string: String::from(slice), + } + } +} + +impl Row { + pub fn render(&self, start: usize, end: usize) -> String { + let end = cmp::min(end, self.string.len()); + let start = cmp::min(start, end); + self.string.get(start..end).unwrap_or_default().to_string() + } } \ No newline at end of file