use super::*;
pub(super) fn next_undo_step_id() -> u64 {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
impl Snapshot {
pub(super) fn take_peer_splice(&mut self, s: &crate::undo_rebase::Splice) {
let edit = TextSpanEdit {
start: self.lines.position(s.at),
end: self.lines.position(s.at + s.deleted),
new_text: s.inserted.clone(),
utf16: false,
};
let map = |p| map_through_span_edits(p, std::slice::from_ref(&edit));
(self.cursor_row, self.cursor_col) = map((self.cursor_row, self.cursor_col));
for sel in self.selection.iter_mut().chain(self.carets.iter_mut()) {
sel.anchor = map(sel.anchor);
sel.head = map(sel.head);
}
self.lines
.replace_range(s.at..s.at + s.deleted, &s.inserted);
self.bytes = self.lines.heap_bytes();
self.dirty = true;
}
}
pub(super) const UNDO_STACK_LIMIT: usize = 500;
pub(super) const UNDO_BYTES_LIMIT: usize = if cfg!(test) {
1024 * 1024
} else {
256 * 1024 * 1024
};
pub(super) const UNDO_MIN_STEPS: usize = 16;
pub(super) struct ClosedHistory {
path: PathBuf,
text_hash: u64,
undo: Vec<Snapshot>,
redo: Vec<Snapshot>,
save_seq: u64,
bytes: usize,
}
pub(super) const CLOSED_HISTORY_FILES: usize = 30;
pub(super) const CLOSED_HISTORY_BYTES: usize = UNDO_BYTES_LIMIT;
pub(super) fn lines_hash(lines: &[String]) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
lines.hash(&mut h);
h.finish()
}
pub(super) fn closed_history_key(path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
impl Editor {
pub(super) fn stash_history(&mut self) {
let Some(path) = self.path.as_deref() else {
return;
};
if (self.undo_stack.is_empty() && self.redo_stack.is_empty())
|| self.has_non_text_view()
|| self.symbol_view.is_some()
{
return;
}
let undo = std::mem::take(&mut self.undo_stack);
let redo = std::mem::take(&mut self.redo_stack);
let entry = ClosedHistory {
path: closed_history_key(path),
text_hash: lines_hash(&self.lines),
bytes: undo.iter().chain(&redo).map(|s| s.bytes).sum(),
undo,
redo,
save_seq: self.save_seq,
};
let _ = CLOSED_HISTORY.try_with(|kept| {
let mut kept = kept.borrow_mut();
kept.retain(|h| h.path != entry.path);
kept.push(entry);
let mut total: usize = kept.iter().map(|h| h.bytes).sum();
while kept.len() > CLOSED_HISTORY_FILES
|| (total > CLOSED_HISTORY_BYTES && kept.len() > 1)
{
total -= kept.remove(0).bytes;
}
});
}
pub(super) fn restore_history(&mut self) {
let Some(path) = self.path.as_deref() else {
return;
};
if self.has_non_text_view() || self.symbol_view.is_some() {
return;
}
let key = closed_history_key(path);
let Ok(Some(entry)) = CLOSED_HISTORY.try_with(|kept| {
let mut kept = kept.borrow_mut();
let i = kept.iter().position(|h| h.path == key)?;
Some(kept.remove(i))
}) else {
return;
};
if entry.text_hash != lines_hash(&self.lines) {
return;
}
self.undo_stack = entry.undo;
self.redo_stack = entry.redo;
self.save_seq = entry.save_seq;
}
pub(super) fn snapshot(&self) -> Snapshot {
let lines = PackedLines::from(&self.lines[..]);
let bytes = lines.heap_bytes();
Snapshot {
lines,
bytes,
final_newline: self.final_newline,
cursor_row: self.cursor_row,
cursor_col: self.cursor_col,
selection: self.selection,
carets: self.carets.clone(),
dirty: self.dirty,
save_seq: self.save_seq,
provenance: self.provenance.clone(),
lsp_folds: self.lsp_folds.clone(),
lsp_folds_lines: self.lsp_folds_lines,
}
}
pub(super) fn trim_undo_stack(&mut self) {
let mut total: usize = self.undo_stack.iter().map(|s| s.bytes).sum();
let mut drop = 0;
while self.undo_stack.len() - drop > UNDO_MIN_STEPS
&& (self.undo_stack.len() - drop > UNDO_STACK_LIMIT || total > UNDO_BYTES_LIMIT)
{
total -= self.undo_stack[drop].bytes;
drop += 1;
}
self.undo_stack.drain(..drop);
}
pub(super) fn trim_redo_stack(&mut self) {
let held = self.undo_stack.iter().chain(&self.redo_stack);
let mut total: usize = held.map(|s| s.bytes).sum();
let mut drop = 0;
while drop < self.redo_stack.len() && total > UNDO_BYTES_LIMIT {
total -= self.redo_stack[drop].bytes;
drop += 1;
}
self.redo_stack.drain(..drop);
}
pub fn undo_history_size(&self) -> (usize, usize) {
let steps = self.undo_stack.iter().chain(&self.redo_stack);
(
self.undo_stack.len() + self.redo_stack.len(),
steps.map(|s| s.bytes).sum(),
)
}
pub(super) fn push_undo(&mut self, kind: EditKind) {
self.push_undo_step(kind, None);
}
pub(super) fn push_undo_step(&mut self, kind: EditKind, group: Option<u64>) {
self.seed_bookmark_shadow();
self.last_edit_origin = (self.cursor_row, self.cursor_col);
self.merge_edit_row = self.cursor_row;
let in_group = group.is_none()
&& self.undo_group == Some(Some(self.undo_step_id))
&& !self.undo_stack.is_empty();
let typing = matches!(kind, EditKind::InsertChar | EditKind::MultiInsertChar);
let coalesce = in_group
|| (typing && self.last_edit_kind == Some(kind))
|| (group.is_some() && group == self.remote_undo_group && !self.undo_stack.is_empty());
self.remote_undo_group = group;
if !coalesce {
self.undo_stack.push(self.snapshot());
self.trim_undo_stack();
self.undo_step_id = next_undo_step_id();
self.mirrored_step = None;
}
if group.is_none()
&& let Some(step) = self.undo_group.as_mut()
{
*step = Some(self.undo_step_id);
}
self.redo_stack.clear();
self.last_edit_kind = Some(kind);
}
pub fn undo(&mut self) -> bool {
let Some(snap) = self.undo_stack.pop() else {
return false;
};
self.remote_undo_group = None;
self.redo_stack.push(self.snapshot());
self.restore_snapshot(snap);
self.undo_step_id = next_undo_step_id();
true
}
pub fn redo(&mut self) -> bool {
let Some(snap) = self.redo_stack.pop() else {
return false;
};
self.remote_undo_group = None;
self.undo_stack.push(self.snapshot());
self.restore_snapshot(snap);
self.undo_step_id = next_undo_step_id();
true
}
pub(super) fn restore_snapshot(&mut self, snap: Snapshot) {
self.lines = snap.lines.iter().map(String::from).collect();
self.final_newline = snap.final_newline;
self.provenance = snap.provenance;
if self.lines.is_empty() {
self.lines.push(String::new());
}
self.provenance.truncate(self.lines.len());
self.lsp_folds = snap.lsp_folds;
self.lsp_folds_lines = snap.lsp_folds_lines;
self.cursor_row = snap.cursor_row.min(self.lines.len().saturating_sub(1));
self.cursor_col = snap.cursor_col.min(self.line_char_len(self.cursor_row));
self.selection = snap.selection;
self.carets = snap.carets;
self.set_dirty(snap.dirty || self.save_seq != snap.save_seq);
self.linked_ranges.clear();
self.linked_rows.clear();
self.merge_edit_row = self.cursor_row;
self.last_edit_kind = None;
self.edit_seq = self.edit_seq.wrapping_add(1);
self.hscroll_content_cols = None;
self.wrap_total_cache.clear();
self.sync_bookmarks_to_buffer();
self.recompute_highlights();
}
pub fn break_undo_coalescing(&mut self) {
self.last_edit_kind = None;
}
pub fn begin_undo_group(&mut self) {
self.undo_group = Some(None);
self.last_edit_kind = None;
}
pub fn end_undo_group(&mut self) {
self.undo_group = None;
self.last_edit_kind = None;
}
pub fn undo_group_open(&self) -> bool {
self.undo_group.is_some()
}
pub fn adopt_undo_step(&mut self, step: u64, group: u64) {
if self.undo_step_id == step && !self.undo_stack.is_empty() {
self.remote_undo_group = Some(group);
}
}
}