use std::cell::OnceCell;
use std::io::{stdout, BufWriter, Write};
use std::path::Path;
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
use std::time::Duration;
use crossterm::{
cursor::{Hide, MoveTo, Show},
event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
queue,
style::{Attribute, Color, Print, ResetColor, SetAttribute, SetForegroundColor},
terminal::{Clear, ClearType},
};
use serde_json::Value;
use crate::document::Document;
use crate::folds::{Blocks, Folds};
use crate::highlight::{Highlights, TokenKind};
use crate::lsp::{Client, Diagnostic, Encoding, Location, Reply, ServerSpec, Severity};
use crate::snippets::Language;
use crate::terminal::Terminal;
#[cfg(test)]
mod tests;
const TAB: &str = " ";
const LSP_DEBOUNCE: Duration = Duration::from_millis(100);
pub enum AppEvent {
Input(Event),
Lsp(Option<Value>),
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Style {
Plain,
Dim,
Reverse,
Error,
Warning,
Code(Decoration),
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Decoration {
kind: Option<TokenKind>,
underlined: bool,
faded: bool,
struck: bool,
}
fn color_of(kind: TokenKind) -> Color {
match kind {
TokenKind::Keyword => Color::Magenta,
TokenKind::Function => Color::Blue,
TokenKind::Type => Color::Cyan,
TokenKind::String => Color::Green,
TokenKind::Constant => Color::DarkYellow,
TokenKind::Comment => Color::DarkGrey,
TokenKind::Macro => Color::DarkCyan,
TokenKind::Namespace => Color::DarkGreen,
}
}
#[derive(Clone, Debug, PartialEq)]
struct Span {
style: Style,
text: String,
}
impl Span {
fn new(style: Style, text: impl Into<String>) -> Self {
Self {
style,
text: text.into(),
}
}
}
type Row = Vec<Span>;
pub struct Editor {
document: Document,
language: Option<Language>,
folds: Folds,
blocks: OnceCell<Blocks>,
should_quit: bool,
cursor_x: usize,
cursor_y: usize,
row_offset: usize,
col_offset: usize,
message: String,
info: Vec<String>,
quit_pending: bool,
lsp: Option<Client>,
diagnostics: Vec<Diagnostic>,
highlights: Highlights,
show_diagnostics: bool,
last_frame: Vec<Row>,
last_size: (usize, usize),
}
impl Editor {
pub fn new(document: Document) -> Self {
Self {
language: document.path.as_deref().and_then(Language::from_path),
document,
folds: Folds::default(),
blocks: OnceCell::new(),
should_quit: false,
cursor_x: 0,
cursor_y: 0,
row_offset: 0,
col_offset: 0,
message: String::new(),
info: Vec::new(),
quit_pending: false,
lsp: None,
diagnostics: Vec::new(),
highlights: Highlights::default(),
show_diagnostics: false,
last_frame: Vec::new(),
last_size: (0, 0),
}
}
pub fn start_lsp(&mut self, events: Sender<AppEvent>) {
let Some(path) = self.document.path.clone() else {
return;
};
let custom = std::env::var("CURD_LSP").ok();
let Some(spec) = ServerSpec::for_file(self.language, &path, custom.as_deref()) else {
return;
};
let forward = move |message| {
let _ = events.send(AppEvent::Lsp(message));
};
match Client::start(&spec, &path, forward) {
Ok(client) => {
self.message = format!("Starting {}...", client.name);
self.lsp = Some(client);
self.show_diagnostics = true;
}
Err(_) => self.message = format!("No language server: {} not found", spec.command),
}
}
pub fn run(&mut self, events: &Receiver<AppEvent>) -> std::io::Result<()> {
while !self.should_quit {
let (width, height) = Terminal::size()?;
self.scroll(
width.saturating_sub(self.gutter_width()),
height.saturating_sub(1),
);
self.draw(width, height)?;
let waiting_to_sync = self.lsp.as_ref().is_some_and(Client::has_pending_changes);
let event = if waiting_to_sync {
match events.recv_timeout(LSP_DEBOUNCE) {
Ok(event) => Some(event),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => break,
}
} else {
match events.recv() {
Ok(event) => Some(event),
Err(_) => break,
}
};
match event {
Some(event) => {
self.handle_event(event);
while let Ok(event) = events.try_recv() {
self.handle_event(event);
}
}
None => self.sync_lsp(),
}
}
Ok(())
}
fn handle_event(&mut self, event: AppEvent) {
match event {
AppEvent::Input(Event::Key(key)) => self.handle_key(key),
AppEvent::Input(Event::Paste(text)) => self.paste(&text),
AppEvent::Input(_) => {}
AppEvent::Lsp(Some(message)) => {
if let Some(lsp) = &mut self.lsp {
let lines = &self.document.lines;
let reply = lsp.handle(&message, &|| lines.join("\n"));
self.apply_reply(reply);
}
}
AppEvent::Lsp(None) => {
if let Some(lsp) = self.lsp.take() {
self.message = format!("Language server {} stopped", lsp.name);
self.diagnostics.clear();
self.highlights = Highlights::default();
self.show_diagnostics = false;
}
}
}
}
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();
self.info.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('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.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.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.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.text_changed(start, (y + 1, 0), "");
self.lines_shifted(y, -1);
}
}
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, Client::encoding)
}
fn text_changed(&mut self, start: (usize, usize), end: (usize, usize), text: &str) {
self.blocks = OnceCell::new();
if let Some(lsp) = &mut self.lsp {
lsp.change(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);
}
fn paste(&mut self, text: &str) {
self.quit_pending = false;
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.sync_lsp();
if let Some(lsp) = &mut self.lsp {
lsp.did_save();
}
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"),
};
}
fn sync_lsp(&mut self) {
if let Some(lsp) = &mut self.lsp {
let lines = &self.document.lines;
lsp.flush(&|| lines.join("\n"));
}
}
fn ask_lsp(&mut self, question: fn(&mut Client, usize, usize)) {
let (line, units) = self.lsp_position(self.cursor_x, self.cursor_y);
self.sync_lsp();
match &mut self.lsp {
Some(lsp) if lsp.is_ready() => question(lsp, line, units),
Some(lsp) => self.message = format!("{} is still starting", lsp.name),
None => self.message = "No language server for this file".into(),
}
}
fn apply_reply(&mut self, reply: Reply) {
match reply {
Reply::Ready => {
if let Some(lsp) = &self.lsp {
self.message = format!("{} ready", lsp.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 = match (&self.lsp, &self.document.path) {
(Some(lsp), _) => lsp.path() == location.path,
(None, Some(path)) => *path == location.path,
(None, None) => false,
};
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,
})
}
fn gutter_width(&self) -> usize {
if self.document.is_empty() {
0
} else {
self.show_diagnostics as usize + self.document.len().to_string().len() + 1
}
}
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
.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 { "" };
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];
for token in self.highlights.on(y) {
for decoration in &mut decorations[token.start.min(len)..token.end.min(len)] {
decoration.kind = Some(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
}
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
}
fn draw(&mut self, width: usize, height: usize) -> std::io::Result<()> {
let frame = self.render(width, height);
let mut out = BufWriter::new(stdout().lock());
queue!(out, Hide)?;
if self.last_size != (width, height) {
queue!(out, Clear(ClearType::All))?;
self.last_frame.clear();
self.last_size = (width, height);
}
for (y, row) in frame.iter().enumerate() {
if self.last_frame.get(y) == Some(row) {
continue;
}
queue!(out, MoveTo(0, y as u16), Clear(ClearType::UntilNewLine))?;
for span in row {
match span.style {
Style::Plain => {}
Style::Dim => queue!(out, SetAttribute(Attribute::Dim))?,
Style::Reverse => queue!(out, SetAttribute(Attribute::Reverse))?,
Style::Error => queue!(out, SetForegroundColor(Color::Red))?,
Style::Warning => queue!(out, SetForegroundColor(Color::Yellow))?,
Style::Code(decoration) => {
if let Some(kind) = decoration.kind {
queue!(out, SetForegroundColor(color_of(kind)))?;
}
if decoration.underlined {
queue!(out, SetAttribute(Attribute::Underlined))?;
}
if decoration.faded {
queue!(out, SetAttribute(Attribute::Dim))?;
}
if decoration.struck {
queue!(out, SetAttribute(Attribute::CrossedOut))?;
}
}
}
queue!(out, Print(&span.text))?;
if span.style != Style::Plain {
queue!(out, SetAttribute(Attribute::Reset), ResetColor)?;
}
}
}
self.last_frame = frame;
let screen_x = (self.gutter_width() + self.cursor_x - self.col_offset) as u16;
let screen_y = self.folds.rows_between(self.row_offset, self.cursor_y) as u16;
queue!(out, MoveTo(screen_x, screen_y), Show)?;
out.flush()
}
}
fn code_span((decoration, text): (Decoration, String)) -> Span {
if decoration == Decoration::default() {
Span::new(Style::Plain, text)
} else {
Span::new(Style::Code(decoration), text)
}
}
fn fit(text: &str, width: usize) -> String {
let mut fitted: String = text.chars().take(width).collect();
let padding = width - fitted.chars().count();
fitted.push_str(&" ".repeat(padding));
fitted
}