use super::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PairAction {
Surround(char),
TypeOver,
InsertPair(char),
Plain,
}
impl Editor {
pub fn word_before_cursor(&self) -> String {
let Some(line) = self.lines.get(self.cursor_row) else {
return String::new();
};
let chars: Vec<char> = line.chars().collect();
let end = self.cursor_col.min(chars.len());
let mut start = end;
while start > 0 && is_word_char(chars[start - 1]) {
start -= 1;
}
chars[start..end].iter().collect()
}
pub fn caret_in_code(&self) -> bool {
let Some(line) = self.lines.get(self.cursor_row) else {
return false;
};
let caret = char_byte(line, self.cursor_col);
self.lang != Some(LangKind::Markdown)
&& self
.earlier_construct_end(self.cursor_row, caret)
.is_some_and(|from| !ends_in_string_or_comment(&line[from..caret], self.lang))
}
pub fn insert_char(&mut self, c: char) {
if self.overwrite_applies() {
self.overwrite_char(c);
return;
}
if self.auto_close_tags && c == '>' && self.insert_closing_tag() {
self.last_typed = Some((c, self.edit_seq));
return;
}
if self.auto_close_pairs && self.insert_char_with_pairs(c) {
self.last_typed = Some((c, self.edit_seq));
return;
}
self.pin_on_edit();
let had_selection = self.selection.map(|s| s.has_area()).unwrap_or(false);
let kind = if had_selection {
EditKind::DeleteSelection
} else {
EditKind::InsertChar
};
self.push_undo(kind);
self.delete_selection_inner();
self.insert_char_raw(c);
self.recompute_highlights();
self.last_typed = Some((c, self.edit_seq));
}
pub(super) fn overwrite_applies(&self) -> bool {
self.overwrite
&& self.carets.is_empty()
&& !self.selection.is_some_and(|s| s.has_area())
&& self
.lines
.get(self.cursor_row)
.is_some_and(|l| self.cursor_col < l.chars().count())
}
pub(super) fn joins_cluster_before_caret(&self, c: char) -> bool {
let Some(line) = self.lines.get(self.cursor_row) else {
return false;
};
let byte = self.byte_index(self.cursor_row, self.cursor_col);
let Some(prev) = line[..byte].graphemes(true).next_back() else {
return false;
};
let mut joined = String::with_capacity(prev.len() + c.len_utf8());
joined.push_str(prev);
joined.push(c);
joined.graphemes(true).nth(1).is_none()
}
pub(super) fn overwrite_char(&mut self, c: char) {
self.undoable_edit(EditKind::InsertChar, |this| {
this.selection = None;
let row = this.cursor_row;
let from = this.byte_index(row, this.cursor_col);
let to = if this.joins_cluster_before_caret(c) {
from
} else {
let next = next_grapheme_col(&this.lines[row], this.cursor_col);
this.byte_index(row, next)
};
let mut buf = [0u8; 4];
this.lines[row].replace_range(from..to, c.encode_utf8(&mut buf));
let col = this.cursor_col + 1;
let line = &this.lines[row];
this.cursor_col = if floor_grapheme_col(line, col) == col {
col
} else {
next_grapheme_col(line, col)
};
});
self.last_typed = Some((c, self.edit_seq));
}
pub(super) fn insert_closing_tag(&mut self) -> bool {
if self.lines.is_empty() {
return false;
}
if self.selection.is_some_and(|s| s.has_area()) {
return false;
}
let byte = self.byte_index(self.cursor_row, self.cursor_col);
if matches!(self.lang, Some(LangKind::Vue | LangKind::Svelte))
&& in_sfc_script_or_style(&self.lines, self.cursor_row, byte)
{
return false;
}
let name = match self.lines.get(self.cursor_row) {
Some(line) => tag_auto_close_name(line, byte, self.lang).map(str::to_owned),
None => None,
};
let Some(name) = name else {
return false;
};
self.undoable_edit(EditKind::InsertChar, |this| {
let row = this.cursor_row;
this.lines[row].insert_str(byte, &format!("></{name}>"));
this.cursor_col += 1;
});
self.ensure_cursor_col_visible();
true
}
pub(super) fn insert_char_with_pairs(&mut self, c: char) -> bool {
if self.lines.is_empty() {
self.lines.push(String::new());
}
match self.pair_action(c) {
PairAction::Plain => false,
PairAction::TypeOver => {
self.cursor_col += 1;
self.ensure_cursor_col_visible();
true
}
PairAction::Surround(close) => {
self.pin_on_edit();
self.push_undo(EditKind::Paste);
self.surround_selection_raw(c, close);
self.recompute_highlights();
true
}
PairAction::InsertPair(close) => {
self.pin_on_edit();
self.push_undo(EditKind::InsertChar);
self.insert_pair_raw(c, close);
self.recompute_highlights();
self.auto_pair_at = Some((self.cursor_row, self.cursor_col, self.edit_seq));
true
}
}
}
pub(super) fn pair_action(&self, c: char) -> PairAction {
let Some(line) = self.lines.get(self.cursor_row) else {
return PairAction::Plain;
};
let close = auto_close_partner(c);
let has_sel = self.selection.map(|s| s.has_area()).unwrap_or(false);
if has_sel {
return match close {
Some(close) if !is_pair_closer(c) => PairAction::Surround(close),
_ => PairAction::Plain,
};
}
let next = line.chars().nth(self.cursor_col);
if (is_pair_closer(c) || is_pair_quote(c)) && next == Some(c) {
return PairAction::TypeOver;
}
let Some(close) = close else {
return PairAction::Plain;
};
if is_pair_closer(c) {
return PairAction::Plain;
}
let next_ok = match is_pair_quote(c) {
true => next.is_none_or(|n| !n.is_alphanumeric() && n != '_' && n != c),
false => next.is_none_or(|n| AUTO_CLOSE_BEFORE.contains(n)),
};
let before = &line[..self.byte_index(self.cursor_row, self.cursor_col)];
let prev_ok = !is_pair_quote(c)
|| before
.chars()
.next_back()
.is_none_or(|p| !p.is_alphanumeric() && p != '_' && p != c)
|| (self.lang == Some(LangKind::Python)
&& is_python_string_prefix(trailing_word(before)));
let lifetime = c == '\'' && self.lang == Some(LangKind::Rust) && rust_lifetime_at(before);
if !next_ok || !prev_ok || lifetime {
return PairAction::Plain;
}
if is_pair_quote(c) {
let Some(from) = self.earlier_construct_end(self.cursor_row, before.len()) else {
return PairAction::Plain;
};
if ends_in_string_or_comment(&before[from..], self.lang) {
return PairAction::Plain;
}
}
PairAction::InsertPair(close)
}
pub(super) fn surround_selection_raw(&mut self, open: char, close: char) {
let Some(sel) = self.selection else {
return;
};
let ((sr, sc), (er, ec)) = sel.normalised();
let close_byte = self.byte_index(er, ec);
self.lines[er].insert(close_byte, close);
let open_byte = self.byte_index(sr, sc);
self.lines[sr].insert(open_byte, open);
let inner_end = if sr == er { ec + 1 } else { ec };
self.selection = Some(EditorSelection {
anchor: (sr, sc + 1),
head: (er, inner_end),
});
self.cursor_row = er;
self.cursor_col = inner_end;
self.mark_buffer_changed();
}
pub(super) fn insert_pair_raw(&mut self, open: char, close: char) {
let row = self.cursor_row;
let byte = self.byte_index(row, self.cursor_col);
self.lines[row].insert(byte, close);
self.lines[row].insert(byte, open);
self.cursor_col += 1;
self.mark_buffer_changed();
}
pub(super) fn earlier_construct_end(&self, row: usize, caret: usize) -> Option<usize> {
if !self.protected_current {
return Some(0);
}
let line_start: usize = self.lines[..row].iter().map(|l| l.len() + 1).sum();
let first = self
.protected_ranges
.partition_point(|&(_, end)| end <= line_start);
match self.protected_ranges.get(first) {
Some(&(start, end)) if start < line_start => {
if end > line_start + caret {
None
} else {
Some(end - line_start)
}
}
_ => Some(0),
}
}
pub fn insert_str(&mut self, s: &str) {
self.insert_str_as(s, crate::provenance::Seat::Me);
}
pub fn paste_str(&mut self, s: &str, reindent: bool) {
let text = normalize_newlines(s);
let (sr, sc) = match self.selection.filter(|sel| sel.has_area()) {
Some(sel) => sel.normalised().0,
None => (self.cursor_row, self.cursor_col),
};
let line = self.lines.get(sr).cloned().unwrap_or_default();
let before: String = line.chars().take(sc).collect();
let protected = self
.earlier_construct_end(sr, before.len())
.is_none_or(|from| ends_in_string_or_comment(&before[from..], self.lang));
self.insert_str(&text);
let code = !matches!(self.lang, None | Some(LangKind::Markdown));
if !reindent || !code || sc == 0 || protected || !text.contains('\n') {
return;
}
let at_indent = before.chars().all(char::is_whitespace);
let base = match at_indent {
true => before,
false => line.chars().take_while(|c| c.is_whitespace()).collect(),
};
let (tab, spaces) = self.indent_preference();
let edits = paste_reindent_edits(&text, sr, sc, &base, at_indent, tab, spaces);
if edits.is_empty() {
return;
}
let last = sr + text.matches('\n').count();
let shift: isize = edits
.iter()
.filter(|e| e.start.0 == last)
.map(|e| e.new_text.chars().count() as isize - (e.end.1 - e.start.1) as isize)
.sum();
self.apply_span_edits(&edits);
self.cursor_row = last;
self.cursor_col = self.cursor_col.saturating_add_signed(shift);
self.clamp_cursor();
}
pub fn insert_str_as(&mut self, s: &str, seat: crate::provenance::Seat) {
self.insert_str_as_in(s, seat, None);
}
pub fn insert_str_as_in(&mut self, s: &str, seat: crate::provenance::Seat, group: Option<u64>) {
self.pin_on_edit();
self.push_undo_step(EditKind::Paste, group);
if let Some(sel) = self.selection {
let ((sr, _), (er, _)) = sel.normalised();
if self.delete_selection_inner() {
self.provenance.splice(sr, er.saturating_sub(sr) + 1, 1);
}
}
let start_line = self.cursor_row;
let before = self.lines.len();
self.bookmark_sync_paused = true;
for c in normalize_newlines(s).chars() {
if c == '\n' {
self.insert_newline_raw();
} else {
self.insert_char_raw(c);
}
}
self.bookmark_sync_paused = false;
self.sync_bookmarks_to_buffer();
let added = self.lines.len().saturating_sub(before);
let end = (start_line + added + 1).min(self.lines.len());
self.provenance
.splice(start_line, 1, end.saturating_sub(start_line));
self.provenance.record(start_line..end, seat);
self.provenance.truncate(self.lines.len());
self.recompute_highlights();
}
pub(super) fn insert_char_raw(&mut self, c: char) {
if self.lines.is_empty() {
self.lines.push(String::new());
}
let row = self.cursor_row;
let col = self.cursor_col;
let byte = self.byte_index(row, col);
self.lines[row].insert(byte, c);
self.cursor_col += 1;
self.mark_buffer_changed();
}
pub fn backspace(&mut self) {
self.backspace_in(None);
}
pub(super) fn backspace_in(&mut self, group: Option<u64>) {
if self.at_symbol_edge(false) {
return;
}
self.pin_on_edit();
self.push_undo_step(EditKind::Backspace, group);
if self.auto_close_pairs
&& !self.selection.map(|s| s.has_area()).unwrap_or(false)
&& self.cursor_col > 0
&& self.auto_pair_at == Some((self.cursor_row, self.cursor_col, self.edit_seq))
{
let line = self.lines.get(self.cursor_row).cloned().unwrap_or_default();
let prev = line.chars().nth(self.cursor_col - 1);
let next = line.chars().nth(self.cursor_col);
if let (Some(p), Some(n)) = (prev, next)
&& auto_close_partner(p) == Some(n)
&& !is_pair_closer(p)
{
let byte = self.byte_index(self.cursor_row, self.cursor_col);
self.lines[self.cursor_row].remove(byte);
}
}
self.backspace_raw();
self.recompute_highlights();
}
pub(super) fn backspace_raw(&mut self) {
if self.delete_selection_inner() || self.at_symbol_edge(false) {
return;
}
if self.cursor_col > 0 {
let row = self.cursor_row;
let col = prev_grapheme_col(&self.lines[row], self.cursor_col);
let from = self.byte_index(row, col);
let to = self.byte_index(row, self.cursor_col);
self.lines[row].replace_range(from..to, "");
self.cursor_col = col;
self.mark_buffer_changed();
} else if self.cursor_row > 0 {
let cur = self.lines.remove(self.cursor_row);
self.cursor_row -= 1;
self.cursor_col = self.line_char_len(self.cursor_row);
self.lines[self.cursor_row].push_str(&cur);
self.mark_buffer_changed();
}
}
pub fn delete_forward(&mut self) {
if self.at_symbol_edge(true) {
return;
}
self.pin_on_edit();
self.push_undo(EditKind::DeleteForward);
self.delete_forward_raw();
self.recompute_highlights();
}
pub(super) fn delete_forward_raw(&mut self) {
if self.delete_selection_inner() || self.at_symbol_edge(true) {
return;
}
let row = self.cursor_row;
let len = self.line_char_len(row);
if self.cursor_col < len {
let from = self.byte_index(row, self.cursor_col);
let next = next_grapheme_col(&self.lines[row], self.cursor_col);
let to = self.byte_index(row, next);
self.lines[row].replace_range(from..to, "");
self.mark_buffer_changed();
} else if row + 1 < self.lines.len() {
let next = self.lines.remove(row + 1);
self.lines[row].push_str(&next);
self.mark_buffer_changed();
}
}
pub fn delete_word_left(&mut self) {
let col = self.cursor_col.min(self.line_char_len(self.cursor_row));
if col == 0 || self.selection.is_some_and(|s| s.has_area()) {
self.backspace();
return;
}
let start = word_start_before(&self.lines[self.cursor_row], col);
self.delete_cols_on_line(EditKind::Backspace, start, col);
}
pub fn delete_word_right(&mut self) {
let len = self.line_char_len(self.cursor_row);
if self.cursor_col >= len || self.selection.is_some_and(|s| s.has_area()) {
self.delete_forward();
return;
}
let end = word_end_after(&self.lines[self.cursor_row], self.cursor_col);
self.delete_cols_on_line(EditKind::DeleteForward, self.cursor_col, end);
}
pub(super) fn delete_cols_on_line(&mut self, kind: EditKind, from: usize, to: usize) {
self.undoable_edit(kind, |this| {
let row = this.cursor_row;
let (a, b) = (this.byte_index(row, from), this.byte_index(row, to));
this.lines[row].replace_range(a..b, "");
this.cursor_col = from;
this.selection = None;
});
}
}
pub(super) const VOID_ELEMENTS: &[&str] = &[
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source",
"track", "wbr",
];
pub(super) fn lang_auto_closes_tags(lang: Option<LangKind>) -> bool {
matches!(
lang,
Some(
LangKind::Html
| LangKind::Xml
| LangKind::Tsx
| LangKind::JavaScript
| LangKind::Vue
| LangKind::Svelte
)
)
}
pub(super) fn in_sfc_script_or_style(lines: &[String], row: usize, byte: usize) -> bool {
let mut inside = false;
for (r, line) in lines.iter().enumerate().take(row + 1) {
let text = if r == row {
line.get(..byte).unwrap_or(line)
} else {
line.as_str()
};
let lower = text.to_ascii_lowercase();
let mut from = 0;
while let Some(off) = lower[from..].find('<') {
let at = from + off;
let tail = &lower[at + 1..];
let (closing, name_part) = match tail.strip_prefix('/') {
Some(t) => (true, t),
None => (false, tail),
};
let named = ["script", "style"].iter().any(|n| {
name_part.strip_prefix(n).is_some_and(|after| {
after.is_empty() || after.starts_with(|c: char| c == '>' || c.is_whitespace())
})
});
if named {
if closing {
inside = false;
} else if tail.contains('>') {
inside = true;
}
}
from = at + 1;
}
}
inside
}
pub(super) fn tag_auto_close_name(line: &str, byte: usize, lang: Option<LangKind>) -> Option<&str> {
if !lang_auto_closes_tags(lang) {
return None;
}
let before = line.get(..byte)?;
let lt = before.rfind('<')?;
let inner = &before[lt + 1..];
if inner.starts_with(['/', '!', '?']) {
return None;
}
if inner.ends_with('/') {
return None;
}
if before[..lt]
.chars()
.next_back()
.is_some_and(|p| p.is_alphanumeric() || p == '_')
{
return None;
}
if matches!(lang, Some(LangKind::Tsx | LangKind::JavaScript))
&& ends_in_script_string_or_comment(&before[..lt])
{
return None;
}
let name_len = inner
.find(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '-' | '.' | ':')))
.unwrap_or(inner.len());
let name = &inner[..name_len];
if !name
.chars()
.next()
.is_some_and(|f| f.is_alphabetic() || f == '_')
{
return None;
}
let rest = &inner[name.len()..];
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
return None;
}
if matches!(lang, Some(LangKind::Tsx | LangKind::JavaScript)) {
let attrs = rest.trim_start();
let first = attrs
.split(|c: char| c.is_whitespace() || c == '=')
.next()
.unwrap_or("");
if attrs.starts_with('=') || first == "extends" {
return None;
}
}
let mut quote: Option<char> = None;
let mut depth = 0usize;
for c in rest.chars() {
match quote {
Some(q) if c == q => quote = None,
Some(_) => {}
None => match c {
'"' | '\'' | '`' => quote = Some(c),
'{' => depth += 1,
'}' => depth = depth.saturating_sub(1),
_ => {}
},
}
}
if quote.is_some() || depth > 0 {
return None;
}
let after = &line[byte..];
if after.trim_start().starts_with('>') || after.contains(&format!("</{name}>")) {
return None;
}
if rest.contains('>') {
return None;
}
if matches!(
lang,
Some(LangKind::Html | LangKind::Vue | LangKind::Svelte)
) && VOID_ELEMENTS.iter().any(|v| v.eq_ignore_ascii_case(name))
{
return None;
}
Some(name)
}
pub(super) fn ends_in_script_string_or_comment(prefix: &str) -> bool {
let mut quote: Option<char> = None;
let mut block_comment = false;
let mut chars = prefix.chars().peekable();
while let Some(c) = chars.next() {
if block_comment {
if c == '*' && chars.peek() == Some(&'/') {
chars.next();
block_comment = false;
}
} else if let Some(q) = quote {
if c == '\\' {
chars.next();
} else if c == q {
quote = None;
}
} else {
match c {
'"' | '\'' | '`' => quote = Some(c),
'/' if chars.peek() == Some(&'/') => return true,
'/' if chars.peek() == Some(&'*') => {
chars.next();
block_comment = true;
}
_ => {}
}
}
}
quote.is_some() || block_comment
}
pub(super) fn ends_in_string_or_comment(prefix: &str, lang: Option<LangKind>) -> bool {
let line_comment = line_comment_token(lang);
let block_comment = block_comment_tokens(lang).filter(|_| lang != Some(LangKind::Python));
let hash_needs_space = matches!(lang, Some(LangKind::Bash | LangKind::Yaml));
let mut quote: Option<(char, bool)> = None; let mut in_block = false;
let mut i = 0;
while let Some(c) = prefix[i..].chars().next() {
let rest = &prefix[i..];
let mut step = c.len_utf8();
if in_block {
if let Some((_, close)) = block_comment
&& rest.starts_with(close)
{
in_block = false;
step = close.len();
}
} else if let Some((q, triple)) = quote {
if c == '\\' && backslash_escapes(q, lang) {
step += rest[step..].chars().next().map_or(0, char::len_utf8);
} else if c == q && (!triple || rest.chars().take(3).eq([q, q, q])) {
quote = None;
if triple {
step = 3;
}
}
} else if let Some((open, _)) = block_comment
&& rest.starts_with(open)
{
in_block = true;
step = open.len();
} else if line_comment.is_some_and(|t| rest.starts_with(t))
&& (!hash_needs_space
|| prefix[..i]
.chars()
.next_back()
.is_none_or(char::is_whitespace))
{
return true;
} else if is_pair_quote(c) && quote_opens_string(&prefix[..i], rest, lang) {
let triple =
lang == Some(LangKind::Python) && c != '`' && rest.chars().take(3).eq([c, c, c]);
quote = Some((c, triple));
if triple {
step = 3;
}
}
i += step;
}
quote.is_some() || in_block
}
pub(super) fn quote_opens_string(before: &str, rest: &str, lang: Option<LangKind>) -> bool {
let mut chars = rest.chars();
let q = chars.next();
if q == Some('"') {
return true;
}
let word = trailing_word(before);
let prefixed = lang == Some(LangKind::Python) && is_python_string_prefix(word);
if !word.is_empty() && !prefixed {
return false;
}
if lang == Some(LangKind::Rust) && q == Some('\'') {
return matches!(
(chars.next(), chars.next()),
(None, _) | (Some('\\'), _) | (Some(_), Some('\''))
);
}
true
}
pub(super) fn rust_lifetime_at(before: &str) -> bool {
let before = before.trim_end();
match before.chars().next_back() {
Some('<') => before[..before.len() - 1]
.chars()
.next_back()
.is_some_and(opens_generics_after),
Some('&' | '+') => true,
Some(',') => inside_angle_brackets(before),
_ => matches!(trailing_word(before), "break" | "continue" | "where"),
}
}
pub(super) fn opens_generics_after(prev: char) -> bool {
prev.is_alphanumeric() || prev == '_' || prev == ':'
}
pub(super) fn inside_angle_brackets(s: &str) -> bool {
let mut depth = 0i32;
let mut prev = ' ';
for c in s.chars() {
match c {
'<' if opens_generics_after(prev) => depth += 1,
'>' if prev != '-' && prev != '=' => depth = (depth - 1).max(0),
_ => {}
}
prev = c;
}
depth > 0
}
pub(super) fn backslash_escapes(q: char, lang: Option<LangKind>) -> bool {
!matches!(
(q, lang),
('\'', Some(LangKind::Bash | LangKind::Yaml | LangKind::Toml)) | ('`', Some(LangKind::Go))
)
}
pub(super) fn is_python_string_prefix(word: &str) -> bool {
matches!(
word.to_ascii_lowercase().as_str(),
"f" | "r" | "b" | "u" | "rb" | "br" | "fr" | "rf"
)
}
pub(super) fn trailing_word(s: &str) -> &str {
let start = s
.char_indices()
.rev()
.take_while(|&(_, c)| is_word_char(c))
.last()
.map_or(s.len(), |(i, _)| i);
&s[start..]
}
pub(super) fn auto_close_partner(c: char) -> Option<char> {
match c {
'(' => Some(')'),
'[' => Some(']'),
'{' => Some('}'),
'"' => Some('"'),
'\'' => Some('\''),
'`' => Some('`'),
_ => None,
}
}
pub(super) const AUTO_CLOSE_BEFORE: &str = ";:.,=}])> \t";
pub(super) fn is_pair_closer(c: char) -> bool {
matches!(c, ')' | ']' | '}')
}
pub(super) fn is_pair_quote(c: char) -> bool {
matches!(c, '"' | '\'' | '`')
}