use super::*;
impl Editor {
pub(super) fn insert_char(&mut self, c: char) {
if self.is_only_to_look_at() {
return;
}
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(), c);
self.cursor_x += 1;
}
pub(super) fn insert_newline(&mut self) {
if self.is_only_to_look_at() {
return;
}
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", '\n');
self.lines_shifted(self.cursor_y, 1);
self.cursor_y += 1;
self.cursor_x = 0;
}
pub(super) 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();
}
}
pub(super) fn delete(&mut self) {
self.folds.unfold(self.cursor_y);
self.delete_at_cursor();
}
pub(super) fn is_only_to_look_at(&mut self) -> bool {
if self.view.is_some() {
self.message = "This shows changes and cannot be edited: Enter goes to the line in its file".into();
}
self.view.is_some()
}
pub(super) fn delete_at_cursor(&mut self) {
if self.is_only_to_look_at() {
return;
}
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, "", c);
} 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), "", '\n');
self.lines_shifted(y, -1);
}
}
pub(super) fn rescan(&mut self, y: usize, added: isize) {
if self.language.is_none() {
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 = y + added.max(0) as usize;
self.stale = Some(match self.stale {
None => (y, last),
Some((from, to)) => {
let to = if y <= to { (to as isize + added).max(y as isize) as usize } else { to };
(from.min(y), to.max(last))
}
});
}
pub(super) fn recolour(&mut self) {
if let (Some((from, to)), Some(language)) = (self.stale.take(), self.language) {
self.line_states.resize(self.document.len(), LineState::Code);
highlight::rescan(&mut self.line_states, &self.document.lines, language, from, to);
}
}
pub(super) 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))
}
pub(super) fn encoding(&self) -> Encoding {
self.lsp
.as_ref()
.map_or(Encoding::Utf32, |lsp| lsp.borrow().encoding())
}
pub(super) fn text_changed(&mut self, start: (usize, usize), end: (usize, usize), text: &str, touched: char) {
let by_indent = self.language.is_some_and(Language::blocks_by_indent);
if by_indent || matches!(touched, '{' | '}' | '\n') {
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);
}
}
pub(super) 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;
}
}
}
}
pub(super) fn type_char(&mut self, c: char) {
if c == '}' && self.cursor_x > 0 && self.text_before_cursor().chars().all(|c| c == ' ') {
for _ in 0..self.indent().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.delete_selection();
self.insert_text(text);
self.history.commit((self.cursor_x, self.cursor_y));
self.recolour();
}
pub(super) fn selection(&self) -> Option<((usize, usize), (usize, usize))> {
let anchor = self.anchor?;
let cursor = (self.cursor_x, self.cursor_y);
match (anchor.1, anchor.0).cmp(&(cursor.1, cursor.0)) {
std::cmp::Ordering::Less => Some((anchor, cursor)),
std::cmp::Ordering::Greater => Some((cursor, anchor)),
std::cmp::Ordering::Equal => None,
}
}
pub(super) fn line_range(&self) -> Option<((usize, usize), (usize, usize))> {
let y = self.cursor_y;
if y + 1 < self.document.len() {
Some(((0, y), (0, y + 1)))
} else if self.document.line_len(y) > 0 {
Some(((0, y), (self.document.line_len(y), y)))
} else {
None
}
}
pub(super) fn text_between(&self, start: (usize, usize), end: (usize, usize)) -> String {
let mut text = String::new();
let lines = self.document.lines.iter().enumerate();
for (y, line) in lines.take(end.1 + 1).skip(start.1) {
let from = if y == start.1 { start.0 } else { 0 };
let line = line.chars().skip(from);
if y == end.1 {
text.extend(line.take(end.0 - from));
} else {
text.extend(line);
text.push('\n');
}
}
text
}
pub(super) fn select_all(&mut self) {
let Some(last) = self.document.len().checked_sub(1) else {
return;
};
self.anchor = Some((0, 0));
(self.cursor_x, self.cursor_y) = (self.document.line_len(last), last);
}
pub(super) fn copy(&mut self) -> Option<((usize, usize), (usize, usize))> {
let (start, end) = self.selection().or_else(|| self.line_range())?;
let text = self.text_between(start, end);
self.message = match end.1 - start.1 {
0 => format!("Copied {} characters", text.chars().count()),
lines => format!("Copied {} lines", lines + (end.0 > 0) as usize),
};
self.copied = Some(text);
Some((start, end))
}
pub(super) fn cut(&mut self) {
if let Some((start, end)) = self.copy() {
self.anchor = Some(start);
(self.cursor_x, self.cursor_y) = end;
self.delete_selection();
self.message = self.message.replacen("Copied", "Cut", 1);
}
}
pub(super) fn delete_selection(&mut self) -> bool {
let Some((start, end)) = self.selection() else {
return false;
};
self.anchor = None;
(self.cursor_x, self.cursor_y) = end;
while (self.cursor_y, self.cursor_x) > (start.1, start.0) {
self.backspace();
}
true
}
pub(super) fn selected_lines(&self) -> (usize, usize) {
match self.selection() {
Some((start, end)) if end.0 == 0 => (start.1, end.1 - 1),
Some((start, end)) => (start.1, end.1),
None => (self.cursor_y, self.cursor_y),
}
}
pub(super) fn after_line_edit(&mut self, first: usize, last: usize, x: usize, y: usize) {
if self.anchor.is_some() {
self.anchor = Some((0, first));
(self.cursor_x, self.cursor_y) = (self.document.line_len(last), last);
self.keep_selection = true;
} else {
(self.cursor_x, self.cursor_y) = (x, y);
}
}
pub(super) fn shift_lines(&mut self, inwards: bool) {
let (first, last) = self.selected_lines();
let (mut x, y) = (self.cursor_x, self.cursor_y);
let unit = self.indent();
for line in first..=last.min(self.document.len().saturating_sub(1)) {
(self.cursor_x, self.cursor_y) = (0, line);
if inwards {
if self.document.line_len(line) > 0 {
unit.chars().for_each(|c| self.insert_char(c));
}
} else {
let spaces = self.document.lines.get(line).map_or(0, |text| {
text.chars().take(unit.len()).take_while(|c| *c == ' ').count()
});
for _ in 0..spaces {
self.delete();
}
if line == y {
x = x.saturating_sub(spaces);
}
}
}
self.after_line_edit(first, last, x, y);
}
pub(super) fn toggle_comment(&mut self) {
let Some(token) = self.language.map(highlight::line_comment) else {
self.message = "No comment style known for this kind of file".into();
return;
};
let (first, last) = self.selected_lines();
let (x, y) = (self.cursor_x, self.cursor_y);
let indent_of = |line: &String| line.chars().take_while(|c| *c == ' ').count();
let lines: Vec<(usize, usize)> = (first..=last)
.filter_map(|line| Some((line, self.document.lines.get(line)?)))
.filter(|(_, text)| !text.trim().is_empty())
.map(|(line, text)| (line, indent_of(text)))
.collect();
let commented = lines.iter().all(|(line, indent)| {
self.document.lines[*line].chars().skip(*indent).collect::<String>().starts_with(token)
});
let column = lines.iter().map(|(_, indent)| *indent).min().unwrap_or(0);
for (line, indent) in lines {
if commented {
(self.cursor_x, self.cursor_y) = (indent, line);
for _ in 0..token.chars().count() {
self.delete();
}
if self.document.lines[line].chars().nth(indent) == Some(' ') {
self.delete();
}
} else {
(self.cursor_x, self.cursor_y) = (column, line);
self.insert_text(&format!("{token} "));
}
}
self.after_line_edit(first, last, x, y);
}
pub(super) fn move_line(&mut self, down: bool) {
let (x, y) = (self.cursor_x, self.cursor_y);
let lower = y + down as usize;
if lower == 0 || lower >= self.document.len() {
return;
}
self.folds.reveal(lower - 1);
self.folds.reveal(lower);
let text = self.document.lines[lower].clone();
(self.cursor_x, self.cursor_y) = (0, lower);
for _ in 0..text.chars().count() {
self.delete();
}
self.backspace();
(self.cursor_x, self.cursor_y) = (0, lower - 1);
text.chars().for_each(|c| self.insert_char(c));
self.insert_newline();
(self.cursor_x, self.cursor_y) = (x, if down { y + 1 } else { y - 1 });
}
pub(super) fn duplicate_line(&mut self) {
let Some(text) = self.document.lines.get(self.cursor_y).cloned() else {
return;
};
let x = self.cursor_x;
self.cursor_x = self.document.line_len(self.cursor_y);
self.insert_newline();
text.chars().for_each(|c| self.insert_char(c));
self.cursor_x = x;
}
pub fn select_word(&mut self) {
let Some(line) = self.document.lines.get(self.cursor_y) else {
return;
};
let chars: Vec<char> = line.chars().collect();
let mut start = self.cursor_x.min(chars.len());
let mut end = start;
while start > 0 && is_word_char(chars[start - 1]) {
start -= 1;
}
while end < chars.len() && is_word_char(chars[end]) {
end += 1;
}
if start < end {
self.anchor = Some((start, self.cursor_y));
self.cursor_x = end;
}
}
pub fn jump_to(&mut self, x: usize, y: usize) {
self.anchor = None;
self.completion = None;
self.cursor_y = y.min(self.document.len().saturating_sub(1));
self.folds.reveal(self.cursor_y);
self.cursor_x = x.min(self.document.line_len(self.cursor_y));
}
pub fn reload(&mut self, lines: &[String]) {
let cursor = (self.cursor_x, self.cursor_y);
self.anchor = None;
self.completion = None;
self.prompt = None;
self.history.begin(cursor, false);
self.select_all();
self.delete_selection();
for (y, line) in lines.iter().enumerate() {
if y > 0 {
self.insert_newline();
}
line.chars().for_each(|c| self.insert_char(c));
}
self.jump_to(cursor.0, cursor.1);
self.history.commit((self.cursor_x, self.cursor_y));
self.history.mark_saved();
self.document.dirty = false;
self.recolour();
self.message = "Reloaded: the file changed on disk".into();
}
pub(super) fn insert_text(&mut self, text: &str) {
for c in text.chars() {
match c {
'\n' => self.insert_newline(),
'\r' => {}
'\t' => self.indent().chars().for_each(|c| self.insert_char(c)),
c => self.insert_char(c),
}
}
}
pub(super) 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();
}
pub(super) 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();
}
pub(super) 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),
}
}
pub(super) 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();
}
pub(super) 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(),
}
}
pub(super) fn indent(&self) -> &'static str {
Language::indent(self.language)
}
pub(super) 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.is_some_and(Language::blocks_by_indent),
_ => false,
};
if opens_block {
indent.push_str(self.indent());
}
indent
}
pub(super) fn word_before_cursor(&self) -> String {
let before = self.text_before_cursor();
let start = self.word_start();
before.chars().skip(start).collect()
}
pub(super) 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
}
pub(super) fn snippet_at_cursor(&self) -> Option<&'static str> {
let word = self.word_before_cursor();
self.language.and_then(|language| language.snippet(&word))
}
pub(super) 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 => self.indent().chars().for_each(|c| self.insert_char(c)),
}
}
pub(super) 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;
}
}
pub(super) fn save_or_ask(&mut self) {
if self.is_only_to_look_at() {
return;
}
if self.document.path.is_none() {
self.open_prompt(PromptKind::SaveAs);
} else {
self.save();
}
}
pub(super) 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()
}
pub(super) 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;
}
}