From afaf3ab0fefe718468cbd7b4ac88ae8ee75ee948 Mon Sep 17 00:00:00 2001 From: mars Date: Wed, 12 Apr 2023 17:39:46 -0400 Subject: [PATCH] Add line command --- src/buffer.rs | 8 +++++++- src/main.rs | 18 ++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/buffer.rs b/src/buffer.rs index 73975d5..2b8b67c 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -33,7 +33,7 @@ use crate::{Cursor, Direction}; #[derive(Clone, Debug)] pub struct Buffer { styles: Arc>, - pub text: Rope, + text: Rope, syntax_set: Arc, parser: ParseState, style_dirty: bool, @@ -41,6 +41,12 @@ pub struct Buffer { styled: Vec)>>, } +impl AsRef for Buffer { + fn as_ref(&self) -> &Rope { + &self.text + } +} + impl Buffer { pub fn from_str(styles: Arc>, text: &str) -> Self { let syntax_set = SyntaxSet::load_defaults_nonewlines(); diff --git a/src/main.rs b/src/main.rs index 5b64678..4bc85a4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -325,7 +325,7 @@ impl State { } fn write_buffer(&mut self, file: OsString) -> Result<()> { - let out = self.buffer.text.bytes().collect::>(); + let out = self.buffer.as_ref().bytes().collect::>(); let mut handle = OpenOptions::new().write(true).open(file)?; handle.write_all(out.as_slice())?; @@ -364,9 +364,16 @@ impl State { self.write_command(command, args)?; self.quit = true; } - command => { - return Err(format!("{}: Unrecognized command.", command)); - } + command => match command.parse::() { + Err(_) => return Err(format!("{}: Unrecognized command.", command)), + Ok(line) if line >= self.buffer.as_ref().len_lines() => { + return Err(format!("Line {} is out-of-bounds", line)) + } + Ok(line) => { + self.cursor.line = line; + self.scroll_to_cursor(); + } + }, } Ok(()) @@ -374,7 +381,10 @@ impl State { fn move_cursor(&mut self, direction: Direction) { self.buffer.move_cursor(&mut self.cursor, direction, true); + self.scroll_to_cursor(); + } + fn scroll_to_cursor(&mut self) { if self.cursor.column < self.scroll.column + 3 { self.scroll.column = self.cursor.column.saturating_sub(3); } else if self.cursor.column + 6 >= self.scroll.column + self.size.0 {