use std::cell::{OnceCell, RefCell};
use std::path::Path;
use std::rc::Rc;
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use crossterm::style::Color;
use crate::diff::{self, Mark};
use crate::document::Document;
use crate::folds::{Blocks, Folds};
use crate::highlight::{self, Highlights, LineState};
use crate::history::{Change, History};
use crate::lsp::{Client, CompletionItem, Diagnostic, Encoding, Location, Reply, Severity};
use crate::screen::{fit, overlay, Decoration, Row, Span, Style};
use crate::search;
use crate::snippets::Language;
#[cfg(test)]
mod tests;
const TAB: &str = " ";
const MENU_ROWS: usize = 8;
const MENU_WIDTH: usize = 50;
#[derive(Clone, Copy, Debug, PartialEq)]
enum PromptKind {
Find,
SaveAs,
}
impl PromptKind {
fn label(self) -> &'static str {
match self {
Self::Find => "Find: ",
Self::SaveAs => "Save as: ",
}
}
}
struct Prompt {
kind: PromptKind,
text: String,
}
struct Completion {
items: Vec<CompletionItem>,
shown: Vec<usize>,
selected: usize,
moved: bool,
start: usize,
y: usize,
}
fn is_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
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 renamed: bool,
page_rows: usize,
history: History,
prompt: Option<Prompt>,
find_from: (usize, usize),
last_query: String,
completion: Option<Completion>,
completion_word: Option<(usize, usize)>,
completion_request: Option<u64>,
git_base: Option<Vec<String>>,
marks: OnceCell<Vec<Mark>>,
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,
renamed: false,
page_rows: 0,
history: History::default(),
prompt: None,
find_from: (0, 0),
last_query: String::new(),
completion: None,
completion_word: None,
completion_request: None,
git_base: None,
marks: OnceCell::new(),
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;
self.completion = None;
self.completion_request = None;
}
pub fn set_git_base(&mut self, base: Option<Vec<String>>) {
self.git_base = base;
self.marks = OnceCell::new();
}
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;
}
self.message.clear();
self.info.clear();
if self.prompt.is_some() {
self.prompt_key(key);
return;
}
let command = KeyModifiers::CONTROL | KeyModifiers::ALT;
let typing = matches!(key.code, KeyCode::Char(c) if !key.modifiers.intersects(command) && c != ' ');
self.history.begin((self.cursor_x, self.cursor_y), typing);
self.edit_key(key);
self.clamp_cursor_x();
self.history.commit((self.cursor_x, self.cursor_y));
}
fn edit_key(&mut self, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
let typed = matches!(key.code, KeyCode::Char(_) if !ctrl && !alt);
if let Some(completion) = &self.completion {
match key.code {
KeyCode::Up => return self.move_selection(-1),
KeyCode::Down => return self.move_selection(1),
KeyCode::Esc => return self.completion = None,
KeyCode::Tab if completion.moved || self.snippet_at_cursor().is_none() => {
return self.accept_completion();
}
KeyCode::Backspace => {}
_ if typed => {}
_ => self.completion = None,
}
}
if !typed && key.code != KeyCode::Backspace {
self.completion_word = None;
}
match key.code {
KeyCode::Char('s') if ctrl => self.save_or_ask(),
KeyCode::Char('z') if ctrl => self.undo(),
KeyCode::Char('y') if ctrl => self.redo(),
KeyCode::Char('f') if ctrl || alt => self.open_prompt(PromptKind::Find),
KeyCode::Char('n') if alt => self.find_again(),
KeyCode::F(3) => self.find_again(),
KeyCode::Char(' ') if ctrl => self.ask_completion(true),
KeyCode::Char('/') if alt => self.ask_completion(true),
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);
self.after_typing(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();
if self.completion.as_ref().is_some_and(|completion| self.cursor_x <= completion.start) {
self.completion = None;
}
self.refilter();
}
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::PageUp => self.wheel(-(self.page_rows.max(1) as isize)),
KeyCode::PageDown => self.wheel(self.page_rows.max(1) as isize),
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 if ctrl => (self.cursor_x, self.cursor_y) = (0, 0),
KeyCode::End if ctrl => {
self.cursor_y = self.folds.header_of(self.document.len().saturating_sub(1));
self.cursor_x = self.document.line_len(self.cursor_y);
}
KeyCode::Home => self.cursor_x = 0,
KeyCode::End => self.cursor_x = self.document.line_len(self.cursor_y),
_ => {}
}
}
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.history.record(Change::Insert { x: self.cursor_x, y: self.cursor_y, c });
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.history.record(Change::Insert { x: self.cursor_x, y: self.cursor_y, c: '\n' });
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 let Some(c) = self.document.lines.get(y).and_then(|line| line.chars().nth(x)) {
let end = self.lsp_position(x + 1, y);
self.history.record(Change::Delete { x, y, c });
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.history.record(Change::Delete { x, y, c: '\n' });
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();
self.marks = 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();
self.completion = None;
if let Some(prompt) = &mut self.prompt {
prompt.text.extend(text.chars().filter(|c| !c.is_control()));
self.prompt_changed();
return;
}
self.history.begin((self.cursor_x, self.cursor_y), false);
self.insert_text(text);
self.history.commit((self.cursor_x, self.cursor_y));
}
fn insert_text(&mut self, text: &str) {
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 undo(&mut self) {
let Some(step) = self.history.undo() else {
self.message = "Nothing to undo".into();
return;
};
for change in step.changes.iter().rev() {
match *change {
Change::Insert { x, y, .. } => self.remove_at(x, y),
Change::Delete { x, y, c } => self.put_at(x, y, c),
}
}
(self.cursor_x, self.cursor_y) = step.before;
self.document.dirty = !self.history.is_saved();
}
fn redo(&mut self) {
let Some(step) = self.history.redo() else {
self.message = "Nothing to redo".into();
return;
};
for change in &step.changes {
match *change {
Change::Insert { x, y, c } => self.put_at(x, y, c),
Change::Delete { x, y, .. } => self.remove_at(x, y),
}
}
(self.cursor_x, self.cursor_y) = step.after;
self.document.dirty = !self.history.is_saved();
}
fn put_at(&mut self, x: usize, y: usize, c: char) {
self.folds.reveal(y);
(self.cursor_x, self.cursor_y) = (x, y);
match c {
'\n' => self.insert_newline(),
c => self.insert_char(c),
}
}
fn remove_at(&mut self, x: usize, y: usize) {
self.folds.reveal(y);
(self.cursor_x, self.cursor_y) = (x, y);
self.delete_at_cursor();
}
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 word_before_cursor(&self) -> String {
let before = self.text_before_cursor();
let start = self.word_start();
before.chars().skip(start).collect()
}
fn word_start(&self) -> usize {
let before = self.text_before_cursor();
let word = before.chars().rev().take_while(|c| is_word_char(*c)).count();
before.chars().count() - word
}
fn snippet_at_cursor(&self) -> Option<&'static str> {
let word = self.word_before_cursor();
self.language.and_then(|language| language.snippet(&word))
}
fn tab(&mut self) {
match self.snippet_at_cursor() {
Some(body) => {
let word = self.word_before_cursor();
self.expand_snippet(word.chars().count(), 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_or_ask(&mut self) {
if self.document.path.is_none() {
self.open_prompt(PromptKind::SaveAs);
} else {
self.save();
}
}
fn save(&mut self) -> bool {
let result = self.document.save();
self.message = match &result {
Ok(()) => {
self.just_saved = true;
self.history.mark_saved();
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}"),
};
result.is_ok()
}
fn save_as(&mut self, name: &str) {
let name = name.trim();
if name.is_empty() {
self.message = "Not saved: no file name given".into();
return;
}
if Path::new(name).exists() {
self.message = format!("Not saved: {name} already exists");
return;
}
self.document.path = Some(name.to_string());
if !self.save() {
self.document.path = None;
return;
}
self.abs_path = std::fs::canonicalize(name)
.or_else(|_| std::path::absolute(name))
.ok()
.map(|path| path.to_string_lossy().into_owned());
self.language = Language::from_path(name);
self.line_states = match self.language {
Some(language) => highlight::line_states(&self.document.lines, language),
None => Vec::new(),
};
self.blocks = OnceCell::new();
self.renamed = true;
}
fn open_prompt(&mut self, kind: PromptKind) {
self.completion = None;
self.find_from = (self.cursor_x, self.cursor_y);
self.prompt = Some(Prompt {
kind,
text: String::new(),
});
}
fn prompt_key(&mut self, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
let Some(prompt) = &mut self.prompt else {
return;
};
let finding = prompt.kind == PromptKind::Find;
match key.code {
KeyCode::Esc => self.prompt = None,
KeyCode::Char('f') if (ctrl || alt) && finding => self.find_step(true),
KeyCode::Char(c) if !ctrl && !alt => {
prompt.text.push(c);
self.prompt_changed();
}
KeyCode::Backspace => {
prompt.text.pop();
self.prompt_changed();
}
KeyCode::Enter | KeyCode::Down if finding => self.find_step(true),
KeyCode::Up if finding => self.find_step(false),
KeyCode::Enter => {
let name = std::mem::take(&mut prompt.text);
self.prompt = None;
self.save_as(&name);
}
_ => {}
}
}
fn prompt_changed(&mut self) {
let Some(Prompt { kind: PromptKind::Find, text }) = &self.prompt else {
return;
};
let query = text.clone();
(self.cursor_x, self.cursor_y) = self.find_from;
self.jump_to_match(&query, true, true);
self.last_query = query;
}
fn find_step(&mut self, forward: bool) {
let query = match &self.prompt {
Some(prompt) if !prompt.text.is_empty() => prompt.text.clone(),
_ => self.last_query.clone(),
};
self.jump_to_match(&query, forward, false);
}
fn find_again(&mut self) {
if self.last_query.is_empty() {
self.message = "Nothing searched for yet: Ctrl+F or Alt+F starts a search".into();
} else {
let query = self.last_query.clone();
self.jump_to_match(&query, true, false);
}
}
fn jump_to_match(&mut self, query: &str, forward: bool, inclusive: bool) {
if query.is_empty() {
return;
}
let from = (self.cursor_x, self.cursor_y);
match search::find(&self.document.lines, query, from, forward, inclusive) {
Some((x, y)) => {
self.folds.reveal(y);
(self.cursor_x, self.cursor_y) = (x, y);
}
None => self.message = format!("No match for {query}"),
}
}
fn after_typing(&mut self, c: char) {
if self.completion.is_some() && is_word_char(c) {
self.refilter();
return;
}
self.completion = None;
if is_word_char(c) || c == '.' || self.text_before_cursor().ends_with("::") {
self.ask_completion(false);
}
}
fn ask_completion(&mut self, manual: bool) {
let word = (self.word_start(), self.cursor_y);
if !manual && self.completion_word == Some(word) {
return;
}
let (line, units) = self.lsp_position(self.cursor_x, self.cursor_y);
self.sync_lsp();
let request = match (&self.lsp, &self.abs_path) {
(Some(lsp), Some(path)) if lsp.borrow().is_ready() => {
lsp.borrow_mut().completion(path, line, units)
}
_ => None,
};
match request {
Some(_) => {
self.completion_word = Some(word);
self.completion_request = request;
}
None if manual => self.message = "No language server to suggest anything".into(),
None => {}
}
}
fn refilter(&mut self) {
let Some(mut completion) = self.completion.take() else {
return;
};
if self.cursor_y != completion.y || self.cursor_x < completion.start {
return;
}
let typed: String = self
.text_before_cursor()
.chars()
.skip(completion.start)
.collect::<String>()
.to_lowercase();
let names: Vec<String> = completion
.items
.iter()
.map(|item| item.filter.to_lowercase())
.collect();
let starts_with = |index: &usize| names[*index].starts_with(&typed);
let only_contains = |index: &usize| !starts_with(index) && names[*index].contains(&typed);
completion.shown = (0..names.len())
.filter(starts_with)
.chain((0..names.len()).filter(only_contains))
.collect();
completion.selected = 0;
completion.moved = false;
if !completion.shown.is_empty() {
self.completion = Some(completion);
}
}
fn move_selection(&mut self, step: isize) {
if let Some(completion) = &mut self.completion {
let count = completion.shown.len() as isize;
completion.selected = (completion.selected as isize + step).rem_euclid(count) as usize;
completion.moved = true;
}
}
fn accept_completion(&mut self) {
let Some(completion) = self.completion.take() else {
return;
};
let item = &completion.items[completion.shown[completion.selected]];
while self.cursor_x > completion.start {
self.backspace();
}
self.insert_text(&item.insert);
}
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::Completion(id, items) => {
let word = (self.word_start(), self.cursor_y);
if self.completion_request != Some(id)
|| self.completion_word != Some(word)
|| self.prompt.is_some()
{
return;
}
match items {
Some(items) => {
self.completion = Some(Completion {
items,
shown: Vec::new(),
selected: 0,
moved: false,
start: word.0,
y: word.1,
});
self.refilter();
}
None => {
self.completion_word = None;
self.ask_completion(false);
}
}
}
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
+ self.git_base.is_some() as usize
}
}
pub fn scroll(&mut self, width: usize, height: usize) {
self.page_rows = height;
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 let Some(prompt) = &self.prompt {
let note = match self.message.as_str() {
"" => String::new(),
message => format!(" ({message})"),
};
format!("{}{}{note}", prompt.kind.label(), prompt.text)
} else 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 mark_on(&self, y: usize) -> Mark {
let Some(base) = &self.git_base else {
return Mark::Same;
};
let marks = self
.marks
.get_or_init(|| diff::marks(base, &self.document.lines));
marks.get(y).copied().unwrap_or_default()
}
fn render_line(&self, y: usize, gutter: usize, text_width: usize) -> Row {
let mut row = Row::new();
let mut number_width = gutter - 1 - self.git_base.is_some() as usize;
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),
));
if self.git_base.is_some() {
row.push(match self.mark_on(y) {
Mark::Added => Span::new(Style::Colored(Color::Green), "▎"),
Mark::Modified => Span::new(Style::Colored(Color::Yellow), "▎"),
Mark::RemovedBelow => Span::new(Style::Colored(Color::Red), "▁"),
Mark::RemovedAbove => Span::new(Style::Colored(Color::Red), "▔"),
Mark::Same => Span::new(Style::Plain, " "),
});
}
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;
}
}
if let Some(Prompt { kind: PromptKind::Find, text }) = &self.prompt {
let width = text.chars().count();
for start in search::matches(line, text) {
for decoration in &mut decorations[start..(start + width).min(len)] {
decoration.marked = true;
}
}
}
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, "~")]);
}
}
self.render_completion(&mut rows, width, text_rows);
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 render_completion(&self, rows: &mut [Row], width: usize, text_rows: usize) {
let Some(completion) = &self.completion else {
return;
};
let cursor_row = self.folds.rows_between(self.row_offset, self.cursor_y);
let below = text_rows.saturating_sub(cursor_row + 1);
let wanted = completion.shown.len().min(MENU_ROWS);
let (top, count) = if below >= wanted || below >= cursor_row {
(cursor_row + 1, wanted.min(below))
} else {
let count = wanted.min(cursor_row);
(cursor_row - count, count)
};
let first = (completion.selected + 1).saturating_sub(count);
let lines: Vec<String> = completion.shown[first..first + count]
.iter()
.map(|index| {
let item = &completion.items[*index];
format!(" {} {}", item.label, item.detail).trim_end().to_string() + " "
})
.collect();
let widest = lines.iter().map(|line| line.chars().count()).max().unwrap_or(0);
let menu_width = widest.min(MENU_WIDTH).min(width);
let x = (self.gutter_width() + completion.start)
.saturating_sub(self.col_offset + 1)
.min(width - menu_width);
for (offset, line) in lines.iter().enumerate() {
let style = if first + offset == completion.selected {
Style::Reverse
} else {
Style::Menu
};
overlay(&mut rows[top + offset], x, &Span::new(style, fit(line, menu_width)));
}
}
pub fn cursor_on_screen(&self) -> (usize, usize) {
if let Some(prompt) = &self.prompt {
let typed = prompt.kind.label().len() + prompt.text.chars().count();
return (typed, self.page_rows);
}
(
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();
self.completion = None;
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) {
self.completion = None;
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)
}
}