use std::cell::{OnceCell, RefCell};
use std::path::Path;
use std::rc::Rc;
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crate::document::Document;
use crate::folds::{Blocks, Folds};
use crate::highlight::{self, Highlights, LineState};
use crate::lsp::{Client, Diagnostic, Encoding, Location, Reply, Severity};
use crate::screen::{fit, Decoration, Row, Span, Style};
use crate::snippets::Language;
#[cfg(test)]
mod tests;
const TAB: &str = " ";
pub struct Editor {
pub document: Document,
pub abs_path: Option<String>,
pub language: Option<Language>,
folds: Folds,
blocks: OnceCell<Blocks>,
line_states: Vec<LineState>,
cursor_x: usize,
cursor_y: usize,
row_offset: usize,
col_offset: usize,
pub message: String,
info: Vec<String>,
pub just_saved: bool,
pub lsp: Option<Rc<RefCell<Client>>>,
pub diagnostics: Vec<Diagnostic>,
pub highlights: Highlights,
pub show_diagnostics: bool,
}
impl Editor {
pub fn new(document: Document) -> Self {
let language = document.path.as_deref().and_then(Language::from_path);
let abs_path = document
.path
.as_deref()
.and_then(|path| std::path::absolute(path).ok())
.map(|path| path.to_string_lossy().into_owned());
Self {
language,
abs_path,
line_states: match language {
Some(language) => highlight::line_states(&document.lines, language),
None => Vec::new(),
},
document,
folds: Folds::default(),
blocks: OnceCell::new(),
cursor_x: 0,
cursor_y: 0,
row_offset: 0,
col_offset: 0,
message: String::new(),
info: Vec::new(),
just_saved: false,
lsp: None,
diagnostics: Vec::new(),
highlights: Highlights::default(),
show_diagnostics: false,
}
}
pub fn attach_lsp(&mut self, lsp: Rc<RefCell<Client>>) {
self.lsp = Some(lsp);
self.show_diagnostics = true;
}
pub fn detach_lsp(&mut self) {
self.lsp = None;
self.diagnostics.clear();
self.highlights = Highlights::default();
self.show_diagnostics = false;
}
pub fn name(&self) -> &str {
self.document
.path
.as_deref()
.and_then(|path| Path::new(path).file_name())
.and_then(|name| name.to_str())
.unwrap_or("[No Name]")
}
pub 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);
self.message.clear();
self.info.clear();
match key.code {
KeyCode::Char('s') if ctrl => self.save(),
KeyCode::Char('k') if ctrl || alt => self.toggle_fold(),
KeyCode::Char('a') if alt => self.toggle_all_folds(),
KeyCode::Char('h') if alt => self.ask_lsp(Client::hover),
KeyCode::F(2) => self.ask_lsp(Client::hover),
KeyCode::Char('g') if alt => self.ask_lsp(Client::definition),
KeyCode::F(12) => self.ask_lsp(Client::definition),
KeyCode::Char(c) if !ctrl && !alt => self.type_char(c),
KeyCode::Tab => self.tab(),
KeyCode::Enter => {
let indent = self.indent_for_new_line();
self.insert_newline();
indent.chars().for_each(|c| self.insert_char(c));
}
KeyCode::Backspace => self.backspace(),
KeyCode::Delete => self.delete(),
KeyCode::Up => {
if let Some(y) = self.folds.prev_visible(self.cursor_y) {
self.cursor_y = y;
}
}
KeyCode::Down => {
if let Some(y) = self.folds.next_visible(self.cursor_y, self.document.len()) {
self.cursor_y = y;
}
}
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),
_ => {}
}
self.clamp_cursor_x();
}
fn clamp_cursor_x(&mut self) {
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.folds.unfold(self.cursor_y);
let at = self.lsp_position(self.cursor_x, self.cursor_y);
self.document.insert_char(self.cursor_x, self.cursor_y, c);
self.highlights.inserted(self.cursor_x, self.cursor_y);
self.rescan(self.cursor_y, 0);
self.text_changed(at, at, &c.to_string());
self.cursor_x += 1;
}
fn insert_newline(&mut self) {
self.folds.unfold(self.cursor_y);
let at = self.lsp_position(self.cursor_x, self.cursor_y);
self.document.insert_newline(self.cursor_x, self.cursor_y);
self.highlights.split(self.cursor_x, self.cursor_y);
self.rescan(self.cursor_y, 1);
self.text_changed(at, at, "\n");
self.lines_shifted(self.cursor_y, 1);
self.cursor_y += 1;
self.cursor_x = 0;
}
fn backspace(&mut self) {
self.folds.unfold(self.cursor_y);
if self.cursor_x > 0 {
self.cursor_x -= 1;
self.delete_at_cursor();
} else if self.cursor_y > 0 {
self.folds.reveal(self.cursor_y - 1);
self.cursor_y -= 1;
self.cursor_x = self.document.line_len(self.cursor_y);
self.delete_at_cursor();
}
}
fn delete(&mut self) {
self.folds.unfold(self.cursor_y);
self.delete_at_cursor();
}
fn delete_at_cursor(&mut self) {
let (x, y) = (self.cursor_x, self.cursor_y);
let start = self.lsp_position(x, y);
if x < self.document.line_len(y) {
let end = self.lsp_position(x + 1, y);
self.document.delete_char(x, y);
self.highlights.deleted(x, y);
self.rescan(y, 0);
self.text_changed(start, end, "");
} else if y + 1 < self.document.len() {
self.folds.unfold(y + 1);
self.document.delete_char(x, y);
self.highlights.joined(y, x);
self.rescan(y, -1);
self.text_changed(start, (y + 1, 0), "");
self.lines_shifted(y, -1);
}
}
fn rescan(&mut self, y: usize, added: isize) {
let Some(language) = self.language else {
return;
};
match added {
1 => self.line_states.insert(y + 1, LineState::Code),
-1 => drop(self.line_states.remove(y + 1)),
_ => {}
}
self.line_states.resize(self.document.len(), LineState::Code);
let last_changed = y + added.max(0) as usize;
highlight::rescan(&mut self.line_states, &self.document.lines, language, y, last_changed);
}
fn lsp_position(&self, x: usize, y: usize) -> (usize, usize) {
let line = self.document.lines.get(y).map_or("", String::as_str);
(y, self.encoding().to_units(line, x))
}
fn encoding(&self) -> Encoding {
self.lsp
.as_ref()
.map_or(Encoding::Utf32, |lsp| lsp.borrow().encoding())
}
fn text_changed(&mut self, start: (usize, usize), end: (usize, usize), text: &str) {
self.blocks = OnceCell::new();
if let (Some(lsp), Some(path)) = (&self.lsp, &self.abs_path) {
lsp.borrow_mut().change(path, start, end, text);
}
}
fn lines_shifted(&mut self, y: usize, delta: isize) {
self.folds.shift_after(y, delta);
for diagnostic in &mut self.diagnostics {
for line in [&mut diagnostic.line, &mut diagnostic.end_line] {
if *line > y {
*line = (*line as isize + delta) as usize;
}
}
}
}
fn type_char(&mut self, c: char) {
if c == '}' && self.cursor_x > 0 && self.text_before_cursor().chars().all(|c| c == ' ') {
for _ in 0..TAB.len().min(self.cursor_x) {
self.backspace();
}
}
self.insert_char(c);
}
pub fn paste(&mut self, text: &str) {
self.message.clear();
self.info.clear();
for c in text.chars() {
match c {
'\n' => self.insert_newline(),
'\r' => {}
'\t' => TAB.chars().for_each(|c| self.insert_char(c)),
c => self.insert_char(c),
}
}
}
fn text_before_cursor(&self) -> String {
match self.document.lines.get(self.cursor_y) {
Some(line) => line.chars().take(self.cursor_x).collect(),
None => String::new(),
}
}
fn indent_for_new_line(&self) -> String {
let before = self.text_before_cursor();
let mut indent: String = before.chars().take_while(|c| *c == ' ').collect();
let opens_block = match before.trim_end().chars().last() {
Some('{' | '(' | '[') => true,
Some(':') => self.language == Some(Language::Python),
_ => false,
};
if opens_block {
indent.push_str(TAB);
}
indent
}
fn tab(&mut self) {
let before = self.text_before_cursor();
let word_len = before
.chars()
.rev()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.count();
let word: String = before.chars().skip(before.chars().count() - word_len).collect();
match self.language.and_then(|language| language.snippet(&word)) {
Some(body) => {
self.expand_snippet(word_len, body);
self.message = format!("Expanded snippet: {word}");
}
None => TAB.chars().for_each(|c| self.insert_char(c)),
}
}
fn expand_snippet(&mut self, trigger_len: usize, body: &str) {
for _ in 0..trigger_len {
self.backspace();
}
let indent: String = self
.text_before_cursor()
.chars()
.take_while(|c| *c == ' ')
.collect();
let mut cursor_target = None;
let mut chars = body.chars().peekable();
while let Some(c) = chars.next() {
match c {
'$' if chars.peek() == Some(&'0') => {
chars.next();
cursor_target = Some((self.cursor_x, self.cursor_y));
}
'\n' => {
self.insert_newline();
indent.chars().for_each(|c| self.insert_char(c));
}
c => self.insert_char(c),
}
}
if let Some((x, y)) = cursor_target {
self.cursor_x = x;
self.cursor_y = y;
}
}
fn save(&mut self) {
self.message = match self.document.save() {
Ok(()) => {
self.just_saved = true;
self.sync_lsp();
if let (Some(lsp), Some(path)) = (&self.lsp, &self.abs_path) {
lsp.borrow_mut().did_save(path);
}
format!("Saved {} lines", self.document.len())
}
Err(error) => format!("Could not save: {error}"),
};
}
fn blocks(&self) -> &Blocks {
self.blocks.get_or_init(|| {
if self.language == Some(Language::Python) {
Blocks::by_indent(&self.document.lines)
} else {
Blocks::by_braces(&self.document.lines)
}
})
}
fn toggle_fold(&mut self) {
if self.folds.unfold(self.cursor_y) {
self.message = "Unfolded".into();
return;
}
let blocks = self.blocks();
let block = blocks
.end(self.cursor_y)
.map(|end| (self.cursor_y, end))
.or_else(|| blocks.enclosing(self.cursor_y));
match block {
Some((start, end)) => {
self.folds.fold(start, end);
self.cursor_y = start;
self.message = format!("Folded {} lines", end - start);
}
None => self.message = "No block to fold here".into(),
}
}
fn toggle_all_folds(&mut self) {
if !self.folds.is_empty() {
self.folds.clear();
self.message = "Unfolded all".into();
return;
}
let blocks = self.blocks().top_level();
for (start, end) in &blocks {
self.folds.fold(*start, *end);
}
self.cursor_y = self.folds.header_of(self.cursor_y);
self.message = match blocks.len() {
0 => "No blocks to fold".into(),
count => format!("Folded {count} blocks"),
};
}
pub fn sync_lsp(&mut self) {
if let (Some(lsp), Some(path)) = (&self.lsp, &self.abs_path) {
let lines = &self.document.lines;
lsp.borrow_mut().flush(path, &|| lines.join("\n"));
}
}
fn ask_lsp(&mut self, question: fn(&mut Client, &str, usize, usize)) {
let (line, units) = self.lsp_position(self.cursor_x, self.cursor_y);
self.sync_lsp();
match (&self.lsp, &self.abs_path) {
(Some(lsp), Some(path)) => {
let mut lsp = lsp.borrow_mut();
if lsp.is_ready() {
question(&mut lsp, path, line, units);
} else {
self.message = format!("{} is still starting", lsp.name);
}
}
_ => self.message = "No language server for this file".into(),
}
}
pub fn apply_reply(&mut self, reply: Reply) {
match reply {
Reply::Ready => {
if let Some(lsp) = &self.lsp {
self.message = format!("{} ready", lsp.borrow().name);
}
}
Reply::Diagnostics(diagnostics) => self.diagnostics = diagnostics,
Reply::Hover(lines) if lines.is_empty() => {
self.message = "Nothing to show here".into();
}
Reply::Hover(lines) => self.info = lines,
Reply::Definition(None) => self.message = "No definition found".into(),
Reply::Definition(Some(location)) => self.go_to(location),
Reply::Tokens(tokens) => {
self.highlights = Highlights::new(&tokens, &self.document.lines, self.encoding());
}
Reply::Nothing => {}
}
}
fn go_to(&mut self, location: Location) {
let in_this_file = [&self.abs_path, &self.document.path]
.iter()
.any(|path| path.as_deref() == Some(location.path.as_str()));
if !in_this_file || location.line >= self.document.len() {
let name = Path::new(&location.path)
.file_name()
.and_then(|name| name.to_str())
.unwrap_or(&location.path);
self.message = format!("Defined in {name}, line {}", location.line + 1);
return;
}
self.folds.reveal(location.line);
self.cursor_y = location.line;
self.cursor_x = self
.encoding()
.to_chars(&self.document.lines[location.line], location.units);
self.message = format!("Jumped to line {}", location.line + 1);
}
fn diagnostic_on(&self, y: usize) -> Option<&Diagnostic> {
self.diagnostics
.iter()
.filter(|diagnostic| diagnostic.line == y)
.min_by_key(|diagnostic| match diagnostic.severity {
Severity::Error => 0,
Severity::Warning => 1,
Severity::Info => 2,
})
}
pub fn gutter_width(&self) -> usize {
if self.document.is_empty() {
0
} else {
self.show_diagnostics as usize + self.document.len().to_string().len() + 1
}
}
pub fn scroll(&mut self, width: usize, height: usize) {
self.row_offset = self.folds.header_of(self.row_offset.min(self.cursor_y));
while height > 0 && self.folds.rows_between(self.row_offset, self.cursor_y) >= height {
match self.folds.next_visible(self.row_offset, self.document.len()) {
Some(next) => self.row_offset = next,
None => break,
}
}
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 display_line(&self, y: usize) -> String {
let line = &self.document.lines[y];
match self.folds.end_of(y) {
Some(_) if self.language == Some(Language::Python) => format!("{line} ..."),
Some(end) => format!("{line} ... {}", self.document.lines[end].trim()),
None => line.clone(),
}
}
fn status_line(&self, width: usize) -> String {
let left = if !self.message.is_empty() {
self.message.clone()
} else if let Some(diagnostic) = self.diagnostic_on(self.cursor_y) {
let kind = match diagnostic.severity {
Severity::Error => "error",
Severity::Warning => "warning",
Severity::Info => "info",
};
format!("{kind}: {}", diagnostic.message)
} else {
let name = self.name();
let modified = if self.document.dirty { " [modified]" } else { "" };
let count = |severity| {
self.diagnostics
.iter()
.filter(|diagnostic| diagnostic.severity == severity)
.count()
};
let problems = match (count(Severity::Error), count(Severity::Warning)) {
(0, 0) => String::new(),
(errors, warnings) => format!(" E:{errors} W:{warnings}"),
};
format!("{name}{modified}{problems}")
};
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
};
fit(&line, width)
}
fn render_line(&self, y: usize, gutter: usize, text_width: usize) -> Row {
let mut row = Row::new();
let mut number_width = gutter - 1;
if self.show_diagnostics {
number_width -= 1;
row.push(match self.diagnostic_on(y).map(|d| d.severity) {
Some(Severity::Error) => Span::new(Style::Error, "E"),
Some(Severity::Warning) => Span::new(Style::Warning, "W"),
Some(Severity::Info) => Span::new(Style::Dim, "i"),
None => Span::new(Style::Plain, " "),
});
}
let marker = if self.folds.end_of(y).is_some() {
'+'
} else if self.blocks().end(y).is_some() {
'-'
} else {
' '
};
row.push(Span::new(
Style::Dim,
format!("{:>number_width$}{marker}", y + 1),
));
let decorations = self.decorations(y);
let visible = self.display_line(y);
let visible = visible.chars().enumerate().skip(self.col_offset).take(text_width);
let mut current: Option<(Decoration, String)> = None;
for (x, c) in visible {
let decoration = decorations.get(x).copied().unwrap_or_default();
match &mut current {
Some((same, text)) if *same == decoration => text.push(c),
_ => {
row.extend(current.take().map(code_span));
current = Some((decoration, c.to_string()));
}
}
}
row.extend(current.map(code_span));
row
}
fn decorations(&self, y: usize) -> Vec<Decoration> {
let line = &self.document.lines[y];
let len = line.chars().count();
let mut decorations = vec![Decoration::default(); len];
let mut scanned = Vec::new();
if let Some(language) = self.language {
let state = self.line_states.get(y).copied().unwrap_or_default();
highlight::lex_line(line, language, state, &mut scanned);
}
for token in scanned.iter().chain(self.highlights.on(y)) {
for decoration in &mut decorations[token.start.min(len)..token.end.min(len)] {
decoration.kind = token.kind;
}
}
let encoding = self.encoding();
for diagnostic in &self.diagnostics {
if diagnostic.line > y {
break;
}
if diagnostic.end_line < y {
continue;
}
let start = if diagnostic.line == y {
encoding.to_chars(line, diagnostic.start)
} else {
0
};
let mut end = if diagnostic.end_line == y {
encoding.to_chars(line, diagnostic.end)
} else {
len
};
if diagnostic.line == diagnostic.end_line {
end = end.max(start + 1).min(len);
}
let underlined = matches!(diagnostic.severity, Severity::Error | Severity::Warning);
for decoration in decorations.iter_mut().take(end).skip(start) {
decoration.underlined |= underlined;
decoration.faded |= diagnostic.unnecessary;
decoration.struck |= diagnostic.deprecated;
}
}
decorations
}
pub fn render(&self, width: usize, height: usize) -> Vec<Row> {
let text_rows = height.saturating_sub(1);
let gutter = self.gutter_width();
let text_width = width.saturating_sub(gutter);
let mut rows = Vec::with_capacity(height);
let mut next_line = Some(self.row_offset).filter(|y| *y < self.document.len());
for row in 0..text_rows {
if let Some(y) = next_line {
rows.push(self.render_line(y, gutter, text_width));
next_line = self.folds.next_visible(y, self.document.len());
} 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;
let text = format!("~{}{}", " ".repeat(padding), msg);
rows.push(vec![Span::new(Style::Plain, text)]);
} else {
rows.push(vec![Span::new(Style::Plain, "~")]);
}
}
let panel = self.info.len().min(text_rows / 2);
if panel > 0 {
let cursor_row = self.folds.rows_between(self.row_offset, self.cursor_y);
let top = if cursor_row >= text_rows - panel { 0 } else { text_rows - panel };
for (offset, line) in self.info.iter().take(panel).enumerate() {
let text = fit(&format!(" {line}"), width);
rows[top + offset] = vec![Span::new(Style::Reverse, text)];
}
}
if height > 0 {
rows.push(vec![Span::new(Style::Reverse, self.status_line(width))]);
}
rows
}
pub fn cursor_on_screen(&self) -> (usize, usize) {
(
self.gutter_width() + self.cursor_x - self.col_offset,
self.folds.rows_between(self.row_offset, self.cursor_y),
)
}
pub fn click(&mut self, x: usize, y: usize) {
self.message.clear();
self.info.clear();
let mut line = self.row_offset;
for _ in 0..y {
match self.folds.next_visible(line, self.document.len()) {
Some(next) => line = next,
None => break,
}
}
if line < self.document.len() {
self.cursor_y = line;
self.cursor_x = (x.saturating_sub(self.gutter_width()) + self.col_offset)
.min(self.document.line_len(line));
}
}
pub fn wheel(&mut self, lines: isize) {
for _ in 0..lines.unsigned_abs() {
let next = if lines > 0 {
self.folds.next_visible(self.cursor_y, self.document.len())
} else {
self.folds.prev_visible(self.cursor_y)
};
match next {
Some(y) => self.cursor_y = y,
None => break,
}
}
self.clamp_cursor_x();
}
}
fn code_span((decoration, text): (Decoration, String)) -> Span {
if decoration == Decoration::default() {
Span::new(Style::Plain, text)
} else {
Span::new(Style::Code(decoration), text)
}
}