Skip to content

Commit

Permalink
scroll only in valid positions
Browse files Browse the repository at this point in the history
  • Loading branch information
Rosnaky committed Jul 15, 2024
1 parent 3350b2c commit c099f6c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 22 deletions.
2 changes: 0 additions & 2 deletions src/editor/editorcommand.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};

use super::terminal::Size;


pub enum Direction {
Up,
Down,
Expand Down
50 changes: 30 additions & 20 deletions src/editor/view.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::cmp::min;

use super::{
editorcommand::{Direction, EditorCommand}, terminal::{Position, Size, Terminal}
};
Expand Down Expand Up @@ -99,32 +101,40 @@ impl View {
fn move_text_location(&mut self, direction: &Direction) {
let Location {mut x, mut y} = self.location;
let Size {height, width} = Terminal::size().unwrap_or_default();

match direction {
Direction::Up => {
y = y.saturating_sub(1);
}
Direction::Down => {
y = y.saturating_add(1);
}
Direction::Up => y = y.saturating_sub(1),

Direction::Down => y = y.saturating_add(1),

Direction::Left => {
x = x.saturating_sub(1);
if x > 0 {
x = x.saturating_sub(1);
}
else if y > 0 {
y = y.saturating_sub(1);
x = self.buffer.lines.get(y).map_or(0, |line| line.len().saturating_sub(1));
}
}
Direction::Right => {
x = x.saturating_add(1);
}
Direction::PageUp => {
y = 0;
}
Direction::PageDown => {
y = height.saturating_sub(1);
}
Direction::Home => {
x = 0;
}
Direction::End => {
x = width.saturating_sub(1);
let line_width = self.buffer.lines.get(y).map_or(0, |line| line.len());
if x.saturating_add(1) < line_width {
x = x.saturating_add(1);
}
else {
y = y.saturating_add(1);
x = 0;
}
}
Direction::PageUp => y = y.saturating_sub(height).saturating_sub(1),

Direction::PageDown => y = y.saturating_add(height).saturating_sub(1),

Direction::Home => x = 0,
Direction::End => x = self.buffer.lines.get(y).map_or(0, |line| line.len()),
}
x = self.buffer.lines.get(y).map_or(0, |line| min(line.len(), x));
y = min(y, self.buffer.lines.len());
self.location = Location {x, y};
self.scroll_location_into_view();
}
Expand Down
4 changes: 4 additions & 0 deletions src/editor/view/line.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@ impl Line {
let end = min(range.end, self.string.len());
self.string.get(start..end).unwrap_or_default().to_string()
}

pub fn len(&self) -> usize {
self.string.len()
}
}

0 comments on commit c099f6c

Please sign in to comment.