use std::io::{stdout, Write};
use crossterm::{
cursor::MoveTo,
event::{read, Event, KeyCode, KeyEvent, KeyModifiers},
queue,
style::Print,
terminal::{Clear, ClearType},
};
use crate::document::Document;
use crate::terminal::Terminal;
#[cfg(test)]
mod tests;
pub struct Editor {
document: Document,
should_quit: bool,
cursor_x: usize,
cursor_y: usize,
row_offset: usize,
}
impl Editor {
pub fn new(document: Document) -> Self {
Self {
document,
should_quit: false,
cursor_x: 0,
cursor_y: 0,
row_offset: 0,
}
}
pub fn run(&mut self) -> std::io::Result<()> {
while !self.should_quit {
let (_width, height) = Terminal::size()?;
self.scroll(height);
self.draw()?;
if let Event::Key(key) = read()? {
self.handle_key(key);
}
}
Ok(())
}
fn handle_key(&mut self, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
match key.code {
KeyCode::Char('q') if ctrl => self.should_quit = true,
KeyCode::Up => {
if self.cursor_y > 0 {
self.cursor_y -= 1;
}
}
KeyCode::Down => {
if self.cursor_y + 1 < self.document.len() {
self.cursor_y += 1;
}
}
KeyCode::Left => {
if self.cursor_x > 0 {
self.cursor_x -= 1;
}
}
KeyCode::Right => {
if self.cursor_x < self.document.line_len(self.cursor_y) {
self.cursor_x += 1;
}
}
KeyCode::Home => self.cursor_x = 0,
KeyCode::End => self.cursor_x = self.document.line_len(self.cursor_y),
_ => {}
}
let len = self.document.line_len(self.cursor_y);
if self.cursor_x > len {
self.cursor_x = len;
}
}
fn scroll(&mut self, height: usize) {
if self.cursor_y < self.row_offset {
self.row_offset = self.cursor_y;
}
if self.cursor_y >= self.row_offset + height {
self.row_offset = self.cursor_y - height + 1;
}
}
fn draw(&self) -> std::io::Result<()> {
let mut out = stdout();
let (width, height) = Terminal::size()?;
queue!(out, Clear(ClearType::All), MoveTo(0, 0))?;
for row in 0..height {
let file_row = row + self.row_offset;
if let Some(line) = self.document.lines.get(file_row) {
let visible: String = line.chars().take(width).collect();
queue!(out, Print(visible))?;
} else if self.document.is_empty() && row == height / 3 {
let msg = "curd editor -- v0.1";
let padding = width.saturating_sub(msg.len()) / 2;
queue!(out, Print(format!("~{}{}", " ".repeat(padding), msg)))?;
} else {
queue!(out, Print("~"))?;
}
if row < height - 1 {
queue!(out, Print("\r\n"))?;
}
}
let screen_x = self.cursor_x as u16;
let screen_y = (self.cursor_y - self.row_offset) as u16;
queue!(out, MoveTo(screen_x, screen_y))?;
out.flush()?;
Ok(())
}
}