diff --git a/Cargo.lock b/Cargo.lock index fc751a7..0bd9980 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -32,6 +32,15 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "anyhow" version = "1.0.103" @@ -74,6 +83,12 @@ version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + [[package]] name = "by_address" version = "1.2.1" @@ -89,12 +104,33 @@ dependencies = [ "rustversion", ] +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + [[package]] name = "color-eyre" version = "0.6.5" @@ -145,6 +181,12 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "crossterm" version = "0.29.0" @@ -192,7 +234,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn", + "syn 2.0.118", ] [[package]] @@ -203,7 +245,7 @@ checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" dependencies = [ "darling_core", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -231,7 +273,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn", + "syn 2.0.118", ] [[package]] @@ -308,12 +350,42 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + [[package]] name = "foldhash" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -370,6 +442,30 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -401,7 +497,7 @@ dependencies = [ "indoc", "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -419,6 +515,17 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "kasuari" version = "0.4.12" @@ -619,7 +726,7 @@ dependencies = [ "by_address", "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -891,7 +998,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -912,6 +1019,12 @@ dependencies = [ "dirs", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "signal-hook" version = "0.3.18" @@ -948,6 +1061,7 @@ name = "six" version = "0.1.0" dependencies = [ "anyhow", + "chrono", "color-eyre", "crossterm", "dirs", @@ -965,6 +1079,12 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" version = "1.15.2" @@ -1007,7 +1127,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -1021,6 +1141,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -1051,7 +1182,7 @@ checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -1103,7 +1234,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.118", ] [[package]] @@ -1198,6 +1329,50 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + [[package]] name = "winapi" version = "0.3.9" @@ -1220,12 +1395,65 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-sys" version = "0.61.2" diff --git a/Cargo.toml b/Cargo.toml index 3c1fe5b..a9fc79b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" [dependencies] anyhow = "1.0.102" +chrono = { version = "0.4", default-features = false, features = ["clock"] } color-eyre = { version = "0.6.5", optional = true } crossterm = "0.29.0" nom = "8.0.0" diff --git a/src/cmd/operator.rs b/src/cmd/operator.rs index d435ed4..d28f97f 100644 --- a/src/cmd/operator.rs +++ b/src/cmd/operator.rs @@ -53,6 +53,7 @@ pub enum ImmediateOp { DeleteEol, RepeatLast, Replace(char), + Undo, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/src/components.rs b/src/components.rs index 8de6d12..49a746b 100644 --- a/src/components.rs +++ b/src/components.rs @@ -8,6 +8,7 @@ mod marks; mod registers; mod repeat; mod session; +mod undo; mod yank; use std::collections::HashMap; @@ -22,6 +23,7 @@ pub use marks::{Change, Marks}; pub use registers::{Register, RegisterData, Registers}; pub use repeat::RepeatBuffer; pub use session::{BufferName, BufferView, Coords, ExSession, ExState, Mode, Session, Viewport}; +pub use undo::{UndoScope, UndoSummary}; pub use yank::YankData; pub type SessionId = usize; diff --git a/src/components/buffer.rs b/src/components/buffer.rs index 0f6db42..a547a39 100644 --- a/src/components/buffer.rs +++ b/src/components/buffer.rs @@ -2,7 +2,8 @@ use std::ops::Range; use ropey::Rope; -use crate::components::{Change, Marks}; +use super::undo::UndoStack; +use crate::components::{Change, Marks, UndoSummary, undo::Action}; // Mutable view of a buffer pub trait MutBuffer { @@ -12,10 +13,12 @@ pub trait MutBuffer { fn insert_rope(&mut self, char_idx: usize, rope: &Rope); fn insert_iter(&mut self, char_idx: usize, iter: impl IntoIterator); fn remove(&mut self, char_range: Range); + fn undo(&mut self) -> Option; } pub struct Buffer { marks: Marks, + undo_stack: UndoStack, dirty: bool, rope: Rope, } @@ -24,6 +27,7 @@ impl Buffer { pub fn new(rope: Rope) -> Self { Self { marks: Marks::new(), + undo_stack: UndoStack::new(), dirty: false, rope, } @@ -32,6 +36,7 @@ impl Buffer { pub fn empty() -> Self { Self { marks: Marks::new(), + undo_stack: UndoStack::new(), dirty: false, rope: Rope::new(), } @@ -60,6 +65,10 @@ impl Buffer { pub fn edit(&mut self) -> impl MutBuffer { SessionMutableBuffer { buffer: self } } + + pub fn commit_undo_txn(&mut self) { + self.undo_stack.commit(); + } } // Define how to mutate a Buffer @@ -74,6 +83,9 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { fn insert_char(&mut self, char_idx: usize, ch: char) { self.buffer.rope.insert_char(char_idx, ch); + self.buffer + .undo_stack + .insert_char(self.buffer.dirty, char_idx, ch); self.buffer.marks.adjust(Change::insert(char_idx, 1)); self.buffer.dirty = true; } @@ -84,6 +96,10 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { } self.buffer.rope.insert(char_idx, text); + self.buffer + .undo_stack + .insert_str(self.buffer.dirty, char_idx, text); + self.buffer .marks .adjust(Change::insert(char_idx, text.chars().count())); @@ -92,18 +108,15 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { fn insert_iter(&mut self, char_idx: usize, iter: impl IntoIterator) { let mut len = 0; - for (i, c) in iter.into_iter().enumerate() { self.buffer.rope.insert_char(char_idx + i, c); + self.buffer + .undo_stack + .insert_char(self.buffer.dirty, char_idx + i, c); len += 1; } self.buffer.marks.adjust(Change::insert(char_idx, len)); - } - - fn remove(&mut self, char_range: Range) { - self.buffer.rope.remove(char_range.clone()); - self.buffer.marks.adjust(Change::delete(char_range)); self.buffer.dirty = true; } @@ -115,9 +128,84 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { let tail = self.buffer.rope.split_off(char_idx); self.buffer.rope.append(rope.clone()); self.buffer.rope.append(tail); + + self.buffer + .undo_stack + .insert_rope(self.buffer.dirty, char_idx, rope); + self.buffer .marks .adjust(Change::insert(char_idx, rope.len_chars())); self.buffer.dirty = true; } + + fn remove(&mut self, char_range: Range) { + if char_range.len() == 1 { + let c = self.buffer.rope.char(char_range.start); + self.buffer + .undo_stack + .remove_char(self.buffer.dirty, char_range.clone(), c); + } else { + let text = self.buffer.rope.slice(char_range.clone()).to_string(); + self.buffer + .undo_stack + .remove(self.buffer.dirty, char_range.clone(), &text); + } + + self.buffer.rope.remove(char_range.clone()); + self.buffer.marks.adjust(Change::delete(char_range)); + self.buffer.dirty = true; + } + + fn undo(&mut self) -> Option { + let buffer = &mut self.buffer; + + if let Some(txn) = buffer.undo_stack.pop() { + buffer.dirty = txn.dirty; + + let mut summary = UndoSummary::default(); + for chunk in txn.data.into_iter().rev() { + let s = mk_summary( + &buffer.rope, + txn.timestamp_ms, + txn.change_id, + chunk.char_idx, + chunk.num_lines, + ); + summary.merge(s); + + match chunk.action { + Action::Insert => { + let end_idx = chunk.char_idx + chunk.len_chars; + buffer.rope.remove(chunk.char_idx..end_idx); + buffer.marks.adjust(Change::delete(chunk.char_idx..end_idx)); + } + Action::Delete => { + buffer.rope.insert(chunk.char_idx, &chunk.text); + buffer + .marks + .adjust(Change::insert(chunk.char_idx, chunk.len_chars)); + } + } + } + return Some(summary); + } + + None + } +} + +fn mk_summary( + rope: &Rope, + timestamp_ms: u64, + change_id: u64, + char_idx: usize, + num_lines: usize, +) -> UndoSummary { + let line_idx = rope.char_to_line(char_idx); + if num_lines > 1 { + UndoSummary::destroy_from(timestamp_ms, change_id, char_idx, line_idx) + } else { + UndoSummary::single_line(timestamp_ms, change_id, char_idx, line_idx) + } } diff --git a/src/components/session.rs b/src/components/session.rs index 59863e0..b308ff0 100644 --- a/src/components/session.rs +++ b/src/components/session.rs @@ -4,7 +4,7 @@ use ratatui::layout::{Position, Rect}; use ropey::Rope; use crate::{ - components::{BufferId, DisplayBuffer, InsertLog, MutBuffer}, + components::{BufferId, DisplayBuffer, InsertLog, MutBuffer, undo::UndoSummary}, misc, }; @@ -203,10 +203,6 @@ impl MutBuffer for ExMutableBuffer<'_> { } } - fn remove(&mut self, char_range: Range) { - self.rope.remove(char_range); - } - fn insert_rope(&mut self, char_idx: usize, rope: &Rope) { if rope.len_chars() == 0 { return; @@ -216,4 +212,12 @@ impl MutBuffer for ExMutableBuffer<'_> { self.rope.append(rope.clone()); self.rope.append(tail); } + + fn remove(&mut self, char_range: Range) { + self.rope.remove(char_range); + } + + fn undo(&mut self) -> Option { + None + } } diff --git a/src/components/undo.rs b/src/components/undo.rs new file mode 100644 index 0000000..bce9cc5 --- /dev/null +++ b/src/components/undo.rs @@ -0,0 +1,443 @@ +use std::{collections::VecDeque, fmt, ops::Range}; + +use ropey::Rope; + +use crate::misc; + +// --- Undo Chunk --- + +pub enum Action { + Insert, + Delete, +} + +// An undo chunk us a basic unit of text editing work. It can be either +// a series of contiguous insertions or deletions. +pub struct UndoChunk { + pub action: Action, + pub char_idx: usize, + pub text: String, + pub len_chars: usize, + pub num_lines: usize, +} + +impl fmt::Debug for UndoChunk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let action = match self.action { + Action::Insert => "Insert", + Action::Delete => "Delete", + }; + + f.debug_struct(action) + .field("char_idx", &self.char_idx) + .field("text", &self.text) + .finish() + } +} + +impl fmt::Display for UndoChunk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(self, f) + } +} + +// --- Undo Summary --- + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UndoScope { + None, + PatchRange { start_line: usize, end_line: usize }, + DestroyFrom { start_line: usize }, +} + +#[derive(Debug, Clone, Copy)] +pub struct UndoSummary { + pub timestamp_ms: u64, + pub change_id: u64, + pub changes: u64, + pub start_idx: usize, + pub scope: UndoScope, +} + +impl UndoSummary { + pub fn single_line(timestamp_ms: u64, change_id: u64, start_idx: usize, line: usize) -> Self { + Self { + timestamp_ms, + change_id, + changes: 1, + start_idx, + scope: UndoScope::PatchRange { + start_line: line, + end_line: line, + }, + } + } + + pub fn destroy_from(timestamp_ms: u64, change_id: u64, start_idx: usize, line: usize) -> Self { + Self { + timestamp_ms, + change_id, + changes: 1, + start_idx, + scope: UndoScope::DestroyFrom { start_line: line }, + } + } + + pub fn is_empty(&self) -> bool { + self.scope == UndoScope::None + } + + pub fn merge(&mut self, other: UndoSummary) { + self.timestamp_ms = self.timestamp_ms.min(other.timestamp_ms); + self.change_id = self.change_id.min(other.change_id); + self.changes = self.changes.saturating_add(other.changes); + self.start_idx = self.start_idx.min(other.start_idx); + + self.scope = match (self.scope, other.scope) { + (UndoScope::None, _) => other.scope, + (_, UndoScope::None) => self.scope, + ( + UndoScope::PatchRange { + start_line: s1, + end_line: e1, + }, + UndoScope::PatchRange { + start_line: s2, + end_line: e2, + }, + ) => UndoScope::PatchRange { + start_line: s1.min(s2), + end_line: e1.max(e2), + }, + ( + UndoScope::DestroyFrom { start_line: s1 }, + UndoScope::PatchRange { start_line: s2, .. }, + ) => UndoScope::DestroyFrom { + start_line: s1.min(s2), + }, + ( + UndoScope::PatchRange { start_line: s1, .. }, + UndoScope::DestroyFrom { start_line: s2 }, + ) => UndoScope::DestroyFrom { + start_line: s1.min(s2), + }, + ( + UndoScope::DestroyFrom { start_line: s1 }, + UndoScope::DestroyFrom { start_line: s2 }, + ) => UndoScope::DestroyFrom { + start_line: s1.min(s2), + }, + } + } +} + +impl Default for UndoSummary { + fn default() -> Self { + Self { + timestamp_ms: u64::MAX, + change_id: u64::MAX, + changes: 0, + start_idx: usize::MAX, + scope: UndoScope::None, + } + } +} + +// --- Undo Transaction --- + +// Undo transactions are a logical grouping of one or more undo chunks. +// The lifespan of a transaction is managed by systems by calling the +// `begin_txn` and `commit` functions in the UndoTxnAgg struct. +pub struct UndoTxn { + pub data: Vec, + pub timestamp_ms: u64, + pub change_id: u64, + pub dirty: bool, +} + +impl UndoTxn { + pub fn new(data: Vec, timestamp_ms: u64, change_id: u64, dirty: bool) -> Self { + Self { + data, + timestamp_ms, + change_id, + dirty, + } + } +} + +impl fmt::Debug for UndoTxn { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("UndoTxn") + .field("timestamp_ms", &self.timestamp_ms) + .field("dirty", &self.dirty) + .field("chunk_count", &self.data.len()) + .field("data", &self.data) + .finish() + } +} + +impl fmt::Display for UndoTxn { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(self, f) + } +} + +// --- Undo Stack --- + +// Stack of undo transactions. The chunk and transactions managing is +// taken care of by the UndoTxnAgg struct. +pub struct UndoStack { + agg: UndoTxnAgg, + txns: VecDeque, +} + +impl UndoStack { + const MAX_TXNS: usize = 256; + + pub fn new() -> Self { + Self { + agg: UndoTxnAgg::new(), + txns: VecDeque::with_capacity(Self::MAX_TXNS), + } + } + + pub fn pop(&mut self) -> Option { + self.txns.pop_back() + } + + pub fn commit(&mut self) { + if let Some(txn) = self.agg.commit() { + if self.txns.len() >= Self::MAX_TXNS { + self.txns.pop_front(); + } + self.txns.push_back(txn); + } + } + + pub fn insert_char(&mut self, dirty: bool, char_idx: usize, c: char) { + self.agg.insert_char(dirty, char_idx, c); + } + + pub fn insert_str(&mut self, dirty: bool, char_idx: usize, s: &str) { + self.agg.insert_str(dirty, char_idx, s); + } + + pub fn insert_rope(&mut self, dirty: bool, char_idx: usize, rope: &Rope) { + self.agg.insert_rope(dirty, char_idx, rope); + } + + pub fn remove_char(&mut self, dirty: bool, char_range: Range, c: char) { + self.agg.remove_char(dirty, char_range, c); + } + + pub fn remove(&mut self, dirty: bool, char_range: Range, text: &str) { + self.agg.remove(dirty, char_range, text); + } +} + +impl fmt::Debug for UndoStack { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("UndoStack") + .field("txn_count", &self.txns.len()) + .field("txns", &self.txns) + .finish() + } +} + +impl fmt::Display for UndoStack { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(self, f) + } +} + +// --- Undo aggregator --- + +#[derive(Debug)] +enum AggMode { + None, + Insert, + Delete, +} + +struct UndoTxnAgg { + in_txn: bool, + change_counter: u64, + creation_ts: u64, + dirty: bool, + mode: AggMode, + start_idx: usize, + end_idx: usize, + buffer: Rope, + chunks: Vec, +} + +impl UndoTxnAgg { + fn new() -> Self { + Self { + in_txn: false, + change_counter: 0, + creation_ts: 0, + dirty: false, + mode: AggMode::None, + start_idx: 0, + end_idx: 0, + buffer: Rope::new(), + chunks: Vec::with_capacity(8), + } + } + + fn begin_txn(&mut self, dirty: bool) { + if self.in_txn { + return; + } + + self.in_txn = true; + self.creation_ts = misc::time::now(); + self.dirty = dirty; + self.mode = AggMode::None; + self.start_idx = 0; + self.end_idx = 0; + self.buffer.remove(0..self.buffer.len_chars()); + self.chunks.clear(); + } + + fn commit(&mut self) -> Option { + if !self.in_txn { + return None; + } + + self.in_txn = false; + self.flush(); + + if self.chunks.is_empty() { + None + } else { + self.change_counter += 1; + let data = std::mem::take(&mut self.chunks); + let txn = UndoTxn::new(data, self.creation_ts, self.change_counter, self.dirty); + #[cfg(feature = "dev")] + { + tracing::debug!("UndoTxnAgg::commit: {txn:?}"); + } + Some(txn) + } + } + + fn insert_char(&mut self, dirty: bool, char_idx: usize, c: char) { + self.insert_preamble(dirty, char_idx); + self.buffer.insert_char(self.buffer.len_chars(), c); + self.end_idx += 1; + } + + fn insert_str(&mut self, dirty: bool, char_idx: usize, s: &str) { + self.insert_preamble(dirty, char_idx); + self.buffer.insert(self.buffer.len_chars(), s); + self.end_idx += s.chars().count(); + } + + fn insert_rope(&mut self, dirty: bool, char_idx: usize, rope: &Rope) { + self.insert_preamble(dirty, char_idx); + self.buffer.append(rope.clone()); + self.end_idx += rope.len_chars(); + } + + fn insert_preamble(&mut self, dirty: bool, char_idx: usize) { + if !self.in_txn { + self.begin_txn(dirty); + } + + let needs_flush = match self.mode { + AggMode::None => true, + AggMode::Insert => char_idx != self.end_idx, + AggMode::Delete => true, + }; + + if needs_flush { + self.flush(); + self.start_idx = char_idx; + self.end_idx = char_idx; + } + + self.mode = AggMode::Insert; + } + + fn remove_char(&mut self, dirty: bool, char_range: Range, c: char) { + self.remove_preamble(dirty, &char_range); + + // char_range.end == self.start_idx: contiguous backspace deletes + // char_range.start == self.start_idx: contiguous deletes (via Del key) + + if char_range.end == self.start_idx { + self.start_idx = char_range.start; + self.buffer.insert_char(0, c); + } else if char_range.start == self.start_idx { + let last_idx = self.buffer.len_chars(); + self.end_idx += char_range.len(); + self.buffer.insert_char(last_idx, c); + } + } + + fn remove(&mut self, dirty: bool, char_range: Range, text: &str) { + self.remove_preamble(dirty, &char_range); + + if char_range.end == self.start_idx { + self.start_idx = char_range.start; + self.buffer.insert(0, text); + } else if char_range.start == self.start_idx { + let last_idx = self.buffer.len_chars(); + self.end_idx += char_range.len(); + self.buffer.insert(last_idx, text); + } + } + + fn remove_preamble(&mut self, dirty: bool, char_range: &Range) { + if !self.in_txn { + self.begin_txn(dirty); + } + + let needs_flush = match self.mode { + AggMode::None => true, + AggMode::Insert => true, + AggMode::Delete => { + char_range.start != self.start_idx && char_range.end != self.start_idx + } + }; + + if needs_flush { + self.flush(); + self.start_idx = char_range.start; + self.end_idx = char_range.end; + } + + self.mode = AggMode::Delete; + } + + fn flush(&mut self) { + if self.buffer.len_chars() > 0 { + match self.mode { + AggMode::Insert => { + self.chunks.push(UndoChunk { + action: Action::Insert, + char_idx: self.start_idx, + text: self.buffer.to_string(), + len_chars: self.buffer.len_chars(), + num_lines: self.buffer.len_lines(), + }); + } + AggMode::Delete => { + self.chunks.push(UndoChunk { + action: Action::Delete, + char_idx: self.start_idx, + text: self.buffer.to_string(), + len_chars: self.buffer.len_chars(), + num_lines: self.buffer.len_lines(), + }); + } + AggMode::None => {} + } + + self.buffer.remove(0..self.buffer.len_chars()); + } + } +} diff --git a/src/misc.rs b/src/misc.rs index db09e47..3ac80bc 100644 --- a/src/misc.rs +++ b/src/misc.rs @@ -1,2 +1,3 @@ pub mod io; pub mod path; +pub mod time; diff --git a/src/misc/time.rs b/src/misc/time.rs new file mode 100644 index 0000000..707393f --- /dev/null +++ b/src/misc/time.rs @@ -0,0 +1,41 @@ +use anyhow::{Context, Result}; +use chrono::{Datelike, Local, TimeZone, Timelike}; +use std::{fmt::Write, write}; + +pub fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as u64 +} + +pub fn ppr_timestamp_ms(mut w: impl Write, timestamp_ms: u64) -> Result<()> { + let now = now(); + let t_diff_secs = (now - timestamp_ms) / 1000; + + if t_diff_secs <= 1 { + w.write_str("1 second")?; + } else if t_diff_secs < 100 { + write!(w, "{} seconds ago", t_diff_secs)?; + } else { + let local_time = Local + .timestamp_millis_opt(i64::try_from(timestamp_ms)?) + .single() + .context("timestamp is outside the supported date range")?; + if local_time.date_naive() != Local::now().date_naive() { + write!( + w, + "{:04}/{:02}/{:02} ", + local_time.year(), + local_time.month(), + local_time.day() + )?; + } + let hours = local_time.hour(); + let mins = local_time.minute(); + let secs = local_time.second(); + write!(w, "{hours:02}:{mins:02}:{secs:02}")?; + } + + Ok(()) +} diff --git a/src/systems/event.rs b/src/systems/event.rs index 4a2d08a..32aefe4 100644 --- a/src/systems/event.rs +++ b/src/systems/event.rs @@ -1,11 +1,13 @@ -use std::format; +use std::{fmt::Write, format}; use ropey::{Rope, RopeSlice}; use crate::{ cmd::MotionMode, components::{BufferName, Level, Status, YankData}, + misc::time, rope, + systems::immediate, }; pub fn on_buffer_loaded(status: &mut Status, name: &BufferName, rope: &Rope) { @@ -63,3 +65,26 @@ pub fn on_delete(status: &mut Status, num_lines: usize, is_empty: bool) { status.clear_msg(); } } + +pub fn on_empty_undo_stack(status: &mut Status) { + status.set_msg(Level::Info, "Already at oldest change"); +} + +pub fn on_undo( + status: &mut Status, + timestamp_ms: u64, + change_id: u64, + buf_report: immediate::BufReport, +) { + let (count, singular, plural) = match buf_report { + immediate::BufReport::Changed(changes) => (changes, "change", "changes"), + immediate::BufReport::Added(lines) => (lines, "line added", "lines added"), + immediate::BufReport::Removed(lines) => (lines, "line deleted", "lines deleted"), + }; + let change = if count == 1 { singular } else { plural }; + + status.set_msg(Level::Info, ""); + write!(status.msg, "{count} {change}; before #{change_id} ") + .expect("writing to a String cannot fail"); + time::ppr_timestamp_ms(&mut status.msg, timestamp_ms).expect("writing to a String cannot fail"); +} diff --git a/src/systems/immediate.rs b/src/systems/immediate.rs index 2736aa6..1ce514f 100644 --- a/src/systems/immediate.rs +++ b/src/systems/immediate.rs @@ -1,9 +1,9 @@ use crate::{ - active_session, + active_session, active_session_and_buffer, cmd::{Arg, Cmd, ImmediateOp, Motion, Operator}, components::{EditorCtx, Register}, systems::{ - immediate::{delete::delete, replace::replace}, + immediate::{delete::delete, replace::replace, undo::undo}, input::dispatch_cmd, insert::{Damage, DamageEvent, broadcast_damage}, interactive::{InteractiveArgs, handle_interactive}, @@ -16,11 +16,13 @@ mod delete_char; mod join; mod paste; mod replace; +mod undo; mod yank; use delete_char::{backspace, delete_char}; use join::join; use paste::{PasteMode, paste}; +pub use undo::BufReport; use yank::yank; #[derive(Clone, Copy)] @@ -92,8 +94,14 @@ pub fn handle_immediate(ctx: &mut EditorCtx, args: ImmediateArgs) { Damage::Intact } ImmediateOp::Replace(c) => replace(ctx, c, args.cmd.reps.unwrap_or(1)), + ImmediateOp::Undo => undo(ctx, args.cmd), }; + if args.cmd.op != Operator::Immediate(ImmediateOp::Undo) { + let (_, _, buffer) = active_session_and_buffer!(mut ctx); + buffer.commit_undo_txn(); + } + let (session, _) = active_session!(ctx); let damage_evt = DamageEvent::new(session.buf_id, damage); broadcast_damage(ctx, damage_evt); @@ -119,7 +127,9 @@ fn is_readonly(reg: Option) -> bool { fn is_repeatable(op: ImmediateOp) -> bool { match op { - ImmediateOp::Yank | ImmediateOp::YankLine | ImmediateOp::RepeatLast => false, + ImmediateOp::Yank | ImmediateOp::YankLine | ImmediateOp::RepeatLast | ImmediateOp::Undo => { + false + } _ => true, } } @@ -130,7 +140,8 @@ fn updates_registers(op: ImmediateOp) -> bool { | ImmediateOp::Paste | ImmediateOp::PasteBefore | ImmediateOp::RepeatLast - | ImmediateOp::Replace(_) => false, + | ImmediateOp::Replace(_) + | ImmediateOp::Undo => false, _ => true, } } diff --git a/src/systems/immediate/undo.rs b/src/systems/immediate/undo.rs new file mode 100644 index 0000000..4ed83c5 --- /dev/null +++ b/src/systems/immediate/undo.rs @@ -0,0 +1,91 @@ +use ropey::Rope; + +use crate::{ + active_session_and_buffer, + cmd::Cmd, + components::{EditorCtx, MutBuffer, Status, UndoScope, UndoSummary}, + systems::{ + commons::char_idx_to_coords, event, insert::Damage, nav::utils::ensure_cursor_inside_line, + }, +}; + +pub enum BufReport { + Changed(usize), + Added(usize), + Removed(usize), +} + +pub fn undo(ctx: &mut EditorCtx, cmd: Cmd) -> Damage { + let (_, buf_view, buffer) = active_session_and_buffer!(mut ctx); + let orig_len = buffer.rope().len_lines(); + + let mut cursor_idx = 0; + let mut merged_summary = UndoSummary::default(); + + for _ in 0..cmd.reps.unwrap_or(1) { + if let Some(undo_summary) = buffer.edit().undo() { + cursor_idx = undo_summary.start_idx; + merged_summary.merge(undo_summary); + } else { + break; + } + } + + if merged_summary.is_empty() { + event::on_empty_undo_stack(&mut ctx.status); + return Damage::Intact; + } + + let new_len = buffer.rope().len_lines(); + let damage = undo_summary_to_damage(merged_summary, buffer.rope()); + + match damage { + Damage::Intact => {} + Damage::Line(line) => { + buf_view + .display_buf + .patch_range(&ctx.config, buffer.rope(), line..line + 1) + } + Damage::Range(start_line, end_line) => { + buf_view + .display_buf + .patch_range(&ctx.config, buffer.rope(), start_line..end_line + 1) + } + Damage::From(line) => buf_view.display_buf.destroy_from(line), + } + + let cursor_idx = cursor_idx.min(buffer.rope().len_chars().saturating_sub(1)); + buf_view.cursor = char_idx_to_coords(&ctx.config, buffer.rope(), buf_view, cursor_idx); + ensure_cursor_inside_line(ctx); + + report_undo(&mut ctx.status, merged_summary, orig_len, new_len); + damage +} + +fn undo_summary_to_damage(summary: UndoSummary, rope: &Rope) -> Damage { + match summary.scope { + UndoScope::None => Damage::Intact, + UndoScope::PatchRange { + start_line, + end_line, + } => { + if start_line == end_line { + Damage::Line(start_line) + } else { + Damage::Range(start_line, end_line) + } + } + UndoScope::DestroyFrom { start_line } => Damage::From(start_line), + } +} + +fn report_undo(status: &mut Status, summary: UndoSummary, orig_len: usize, new_len: usize) { + let buf_report = if orig_len == new_len { + BufReport::Changed(summary.changes as usize) + } else if orig_len < new_len { + BufReport::Added(new_len - orig_len) + } else { + BufReport::Removed(orig_len - new_len) + }; + event::on_undo(status, summary.timestamp_ms, summary.change_id, buf_report); +} diff --git a/src/systems/input/parsers.rs b/src/systems/input/parsers.rs index a67edd4..9a9e5d4 100644 --- a/src/systems/input/parsers.rs +++ b/src/systems/input/parsers.rs @@ -118,6 +118,7 @@ static OP_TRIE: LazyLock>> = LazyLock::new(|| &[char('r')], wants_arg(|evt| char_or_tab(evt).map(|c| op(ImmediateOp::Replace(c)))), ); + t.insert(&[char('u')], ok_op(ImmediateOp::Undo)); t }); diff --git a/src/systems/insert/post_insert.rs b/src/systems/insert/post_insert.rs index c53d60f..069f1a8 100644 --- a/src/systems/insert/post_insert.rs +++ b/src/systems/insert/post_insert.rs @@ -14,6 +14,7 @@ pub fn post_insert(ctx: &mut EditorCtx) { if repetable { post_insert_repeat(ctx); } + commit_undo_txn(ctx); restore_cursor(ctx); } @@ -35,6 +36,11 @@ fn post_insert_repeat(ctx: &mut EditorCtx) { } } +fn commit_undo_txn(ctx: &mut EditorCtx) { + let (_, _, buffer) = active_session_and_buffer!(mut ctx); + buffer.commit_undo_txn(); +} + fn restore_cursor(ctx: &mut EditorCtx) { let (session, buf_view, buffer) = active_session_and_buffer!(mut ctx); let cursor = buf_view.cursor; diff --git a/src/systems/interactive.rs b/src/systems/interactive.rs index d4ebb1b..08c2aaa 100644 --- a/src/systems/interactive.rs +++ b/src/systems/interactive.rs @@ -7,9 +7,8 @@ use crate::{ Operator::{self, Move}, TxnItem, }, - components::{EditorCtx, YankData}, + components::{Coords, EditorCtx, YankData}, systems::{ - commons::{display_width, next_col_or_display_width}, immediate::delete::delete, input::dispatch_txn, insert::{DamageEvent, apply_insert_log, broadcast_damage}, @@ -70,9 +69,14 @@ impl InteractiveArgs { // Run the command's setup, remember it for repetition, then either enter insert // mode or replay the saved insert as a batch. pub fn handle_interactive(ctx: &mut EditorCtx, args: InteractiveArgs) { + let cursor = { + let (_, buf_view) = active_session!(ctx); + buf_view.cursor + }; + prelude(ctx, &args); ctx.repbuf.save_last_cmd(args.cmd); - let insert_point = insert_point(ctx, args.op); + let insert_point = insert_point(ctx, args.op, cursor); match args.exec_mode { ExecMode::Interactive => enter_insert(ctx, insert_point), @@ -133,16 +137,13 @@ pub fn finish_interactive(ctx: &mut EditorCtx, op: InteractiveOp, reps: usize) { } // Choose where insertion begins for operations that reuse the current cursor. -fn insert_point(ctx: &mut EditorCtx, op: InteractiveOp) -> InsertPoint { +fn insert_point(ctx: &mut EditorCtx, op: InteractiveOp, orig_cursor: Coords) -> InsertPoint { match op { InteractiveOp::EnterInsert(insert_point) => insert_point, InteractiveOp::Change => { - let (_, buf_view, buffer) = active_session_and_buffer!(mut ctx); - let rope = buffer.rope(); + let (_, buf_view) = active_session!(mut ctx); let cursor = buf_view.cursor; - - let dw = display_width(&ctx.config, rope, buf_view, cursor); - if next_col_or_display_width(&ctx.config, buffer.rope(), buf_view, cursor) == dw { + if cursor.col < orig_cursor.col { InsertPoint::Last } else { InsertPoint::Curr @@ -214,7 +215,7 @@ fn apply_change_insert(ctx: &mut EditorCtx, from_batch: bool) { ctx, &[ Cmd::new(Operator::Move(Motion::GotoLine(cursor.row + 1))).into(), - Cmd::new(Operator::Move(Motion::GotoCol(cursor.col))).into(), + Cmd::new(Operator::Move(Motion::GotoCol(cursor.col + 1))).into(), ], ); } diff --git a/src/systems/mode.rs b/src/systems/mode.rs index 8fd185d..44aa33f 100644 --- a/src/systems/mode.rs +++ b/src/systems/mode.rs @@ -1,7 +1,7 @@ use ropey::Rope; use crate::{ - active_session, active_session_and_buffer, + active_session_and_buffer, cmd::{ExMode, InsertPoint}, components::{BufferView, Config, EditorCtx, Focus, Level, Mode, TextStyle}, systems::{ @@ -37,7 +37,7 @@ pub fn enter_normal(ctx: &mut EditorCtx) { ctx.status.clear_msg(); ctx.status.clear_cmd(); - let (session, _) = active_session!(mut ctx); + let (session, _, buffer) = active_session_and_buffer!(mut ctx); let old_mode = session.mode; session.mode = Mode::Normal; diff --git a/src/systems/nav/argint.rs b/src/systems/nav/argint.rs index c4eeb8e..86ff0fa 100644 --- a/src/systems/nav/argint.rs +++ b/src/systems/nav/argint.rs @@ -139,7 +139,7 @@ fn fix_c( if cursor_on_whitespace(config, buf_view, rope) { m } else { - Motion::EndBigWord + Motion::EndSubWord } } _ => m, diff --git a/src/systems/nav/session.rs b/src/systems/nav/session.rs index 5588295..14582cf 100644 --- a/src/systems/nav/session.rs +++ b/src/systems/nav/session.rs @@ -53,6 +53,7 @@ fn handle_session_nav(ctx: &mut EditorCtx, args: NavArgs) { match session.mode { Mode::Insert => { session.insert_log.poison(); + buffer.commit_undo_txn(); session_nav::( config, buffer, diff --git a/test-docs/argint.txt b/test-docs/argint.txt index 8ede896..b5157c0 100644 --- a/test-docs/argint.txt +++ b/test-docs/argint.txt @@ -5,7 +5,6 @@ ddd eee aaaa aaaa bbbb bbbb - aaa aaa bbb bbb ccc ccc