use std::io::{stdout, Write};
use std::path::Path;
use crossterm::{
cursor::{Hide, MoveTo, Show},
event::{read, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
queue,
style::{Attribute, Print, SetAttribute},
terminal::{Clear, ClearType},
};
use crate::document::Document;
use crate::terminal::Terminal;
#[cfg(test)]
mod tests;
const TAB: &str = " ";
pub struct Editor {
document: Document,
should_quit: bool,
cursor_x: usize,
cursor_y: usize,
row_offset: usize,
col_offset: usize,
message: String,
quit_pending: bool,
}
impl Editor {
pub fn new(document: Document) -> Self {
Self {
document,
should_quit: false,
cursor_x: 0,
cursor_y: 0,
row_offset: 0,
col_offset: 0,
message: String::new(),
quit_pending: false,
}
}
pub fn run(&mut self) -> std::io::Result<()> {
while !self.should_quit {
let (width, height) = Terminal::size()?;
let text_rows = height.saturating_sub(1);
self.scroll(width, text_rows);
self.draw(width, text_rows)?;
if let Event::Key(key) = read()? {
self.handle_key(key);
}
}
Ok(())
}
fn handle_key(&mut self, key: KeyEvent) {
if key.kind == KeyEventKind::Release {
return;
}
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
let quit_was_pending = std::mem::take(&mut self.quit_pending);
self.message.clear();
match key.code {
KeyCode::Char('q') if ctrl => {
if self.document.dirty && !quit_was_pending {
self.quit_pending = true;
self.message = "Unsaved changes! Ctrl+Q again to quit".into();
} else {
self.should_quit = true;
}
}
KeyCode::Char('s') if ctrl => self.save(),
KeyCode::Char(c) if !ctrl && !alt => self.insert_char(c),
KeyCode::Tab => TAB.chars().for_each(|c| self.insert_char(c)),
KeyCode::Enter => {
self.document.insert_newline(self.cursor_x, self.cursor_y);
self.cursor_y += 1;
self.cursor_x = 0;
}
KeyCode::Backspace => {
if self.cursor_x > 0 {
self.cursor_x -= 1;
self.document.delete_char(self.cursor_x, self.cursor_y);
} else if self.cursor_y > 0 {
self.cursor_y -= 1;
self.cursor_x = self.document.line_len(self.cursor_y);
self.document.delete_char(self.cursor_x, self.cursor_y);
}
}
KeyCode::Delete => self.document.delete_char(self.cursor_x, self.cursor_y),
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 insert_char(&mut self, c: char) {
self.document.insert_char(self.cursor_x, self.cursor_y, c);
self.cursor_x += 1;
}
fn save(&mut self) {
self.message = match self.document.save() {
Ok(()) => format!("Saved {} lines", self.document.len()),
Err(error) => format!("Could not save: {error}"),
};
}
fn scroll(&mut self, width: usize, height: usize) {
if self.cursor_y < self.row_offset {
self.row_offset = self.cursor_y;
}
if height > 0 && self.cursor_y >= self.row_offset + height {
self.row_offset = self.cursor_y - height + 1;
}
if self.cursor_x < self.col_offset {
self.col_offset = self.cursor_x;
}
if width > 0 && self.cursor_x >= self.col_offset + width {
self.col_offset = self.cursor_x - width + 1;
}
}
fn status_line(&self, width: usize) -> String {
let left = if !self.message.is_empty() {
self.message.clone()
} else {
let name = self
.document
.path
.as_deref()
.and_then(|path| Path::new(path).file_name())
.and_then(|name| name.to_str())
.unwrap_or("[No Name]");
let modified = if self.document.dirty { " [modified]" } else { "" };
format!("{name}{modified}")
};
let right = format!("Ln {}, Col {}", self.cursor_y + 1, self.cursor_x + 1);
let left_len = left.chars().count();
let line = if left_len + 1 + right.len() <= width {
let gap = width - left_len - right.len();
format!("{left}{}{right}", " ".repeat(gap))
} else {
left
};
let mut line: String = line.chars().take(width).collect();
let padding = width - line.chars().count();
line.push_str(&" ".repeat(padding));
line
}
fn draw(&self, width: usize, text_rows: usize) -> std::io::Result<()> {
let mut out = stdout();
queue!(out, Hide, Clear(ClearType::All), MoveTo(0, 0))?;
for row in 0..text_rows {
let file_row = row + self.row_offset;
if let Some(line) = self.document.lines.get(file_row) {
let visible: String = line.chars().skip(self.col_offset).take(width).collect();
queue!(out, Print(visible))?;
} else if self.document.is_empty() && row == text_rows / 3 {
let msg = concat!("curd editor -- v", env!("CARGO_PKG_VERSION"));
let padding = width.saturating_sub(msg.len()) / 2;
queue!(out, Print(format!("~{}{}", " ".repeat(padding), msg)))?;
} else {
queue!(out, Print("~"))?;
}
queue!(out, Print("\r\n"))?;
}
queue!(
out,
SetAttribute(Attribute::Reverse),
Print(self.status_line(width)),
SetAttribute(Attribute::Reset)
)?;
let screen_x = (self.cursor_x - self.col_offset) as u16;
let screen_y = (self.cursor_y - self.row_offset) as u16;
queue!(out, MoveTo(screen_x, screen_y), Show)?;
out.flush()?;
Ok(())
}
}