From 815d519972fbf83810994c9ffb2103bafeb3cd27 Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Wed, 4 Nov 2026 09:49:06 +0100 Subject: [PATCH 01/11] Implement undo logic Undo seems to work for changes done in insert mode. Next: incorporate extra commands. For that I need to add further undo txn demarcations. --- src/cmd/operator.rs | 1 + src/components.rs | 2 + src/components/buffer.rs | 74 ++++++- src/components/session.rs | 15 +- src/components/undo.rs | 403 ++++++++++++++++++++++++++++++++++ src/systems/immediate.rs | 11 +- src/systems/immediate/undo.rs | 64 ++++++ src/systems/input/parsers.rs | 1 + src/systems/insert/log.rs | 4 + src/systems/mode.rs | 5 +- src/systems/nav/session.rs | 1 + 11 files changed, 563 insertions(+), 18 deletions(-) create mode 100644 src/components/undo.rs create mode 100644 src/systems/immediate/undo.rs 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..7655f64 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::UndoTxnMeta; pub use yank::YankData; pub type SessionId = usize; diff --git a/src/components/buffer.rs b/src/components/buffer.rs index 0f6db42..66f4c34 100644 --- a/src/components/buffer.rs +++ b/src/components/buffer.rs @@ -2,7 +2,11 @@ use std::ops::Range; use ropey::Rope; -use crate::components::{Change, Marks}; +use super::undo::UndoStack; +use crate::components::{ + Change, Marks, + undo::{UndoChunk, UndoTxnMeta}, +}; // Mutable view of a buffer pub trait MutBuffer { @@ -12,10 +16,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 +30,7 @@ impl Buffer { pub fn new(rope: Rope) -> Self { Self { marks: Marks::new(), + undo_stack: UndoStack::new(), dirty: false, rope, } @@ -32,6 +39,7 @@ impl Buffer { pub fn empty() -> Self { Self { marks: Marks::new(), + undo_stack: UndoStack::new(), dirty: false, rope: Rope::new(), } @@ -60,6 +68,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 +86,7 @@ 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(char_idx, ch); self.buffer.marks.adjust(Change::insert(char_idx, 1)); self.buffer.dirty = true; } @@ -84,6 +97,8 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { } self.buffer.rope.insert(char_idx, text); + self.buffer.undo_stack.insert_str(char_idx, text); + self.buffer .marks .adjust(Change::insert(char_idx, text.chars().count())); @@ -95,18 +110,13 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { for (i, c) in iter.into_iter().enumerate() { self.buffer.rope.insert_char(char_idx + i, c); + self.buffer.undo_stack.insert_char(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; - } - fn insert_rope(&mut self, char_idx: usize, rope: &Rope) { if rope.len_chars() == 0 { return; @@ -115,9 +125,59 @@ 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(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(char_range.clone(), c); + } else { + let text = self.buffer.rope.slice(char_range.clone()).to_string(); + self.buffer.undo_stack.remove(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() { + let range = Some(txn.range()); + for chunk in txn.data.into_iter().rev() { + match chunk { + UndoChunk::Insert { + char_idx, + text, + len_chars, + num_lines, + } => { + let end_idx = char_idx + len_chars; + buffer.rope.remove(char_idx..end_idx); + buffer.marks.adjust(Change::delete(char_idx..end_idx)); + } + UndoChunk::Delete { + char_idx, + text, + len_chars, + num_lines, + } => { + buffer.rope.insert(char_idx, &text); + buffer.marks.adjust(Change::insert(char_idx, len_chars)); + } + } + } + return range; + } + + None + } } diff --git a/src/components/session.rs b/src/components/session.rs index 59863e0..87b0bbd 100644 --- a/src/components/session.rs +++ b/src/components/session.rs @@ -4,8 +4,7 @@ use ratatui::layout::{Position, Rect}; use ropey::Rope; use crate::{ - components::{BufferId, DisplayBuffer, InsertLog, MutBuffer}, - misc, + components::{BufferId, DisplayBuffer, InsertLog, MutBuffer, undo::UndoTxnMeta}, misc, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] @@ -203,10 +202,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 +211,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..38c6264 --- /dev/null +++ b/src/components/undo.rs @@ -0,0 +1,403 @@ +use std::{fmt, ops::Range}; + +use ropey::Rope; + +// -- Undo Chunk --- + +// An undo chunk us a basic unit of text editing work. It can be either +// a series of contiguous insertions or deletions. +pub enum UndoChunk { + Insert { + char_idx: usize, + text: String, + len_chars: usize, + num_lines: usize, + }, + Delete { + char_idx: usize, + text: String, + len_chars: usize, + num_lines: usize, + }, +} + +impl fmt::Debug for UndoChunk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (kind, char_idx, text) = match self { + Self::Insert { char_idx, text, .. } => ("Insert", char_idx, text), + Self::Delete { char_idx, text, .. } => ("Delete", char_idx, text), + }; + + f.debug_struct(kind) + .field("char_idx", char_idx) + .field("text", text) + .finish() + } +} + +impl fmt::Display for UndoChunk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(self, f) + } +} + +// -- Undo Transaction --- + +// Undo transacton metadata. we will use this for computing Damage regions +// and status event messages. +pub struct UndoTxnMeta { + pub timestamp_ms: u64, + pub start_idx: usize, + pub end_idx: usize, + pub multi_line: bool, +} + +impl UndoTxnMeta { + fn new(timestamp_ms: u64, start_idx: usize, end_idx: usize, multi_line: bool) -> Self { + Self { + timestamp_ms, + start_idx, + end_idx, + multi_line, + } + } + + pub fn is_empty(&self) -> bool { + self.timestamp_ms == u64::MAX && self.start_idx == usize::MAX && self.end_idx == 0 + } + + pub fn merge(&mut self, other: Self) { + self.timestamp_ms = self.timestamp_ms.min(other.timestamp_ms); + self.start_idx = self.start_idx.min(other.start_idx); + self.end_idx = self.end_idx.max(other.end_idx); + self.multi_line |= other.multi_line; + } +} + +impl Default for UndoTxnMeta { + fn default() -> Self { + Self { + timestamp_ms: u64::MAX, + start_idx: usize::MAX, + end_idx: 0, + multi_line: false, + } + } +} + +// 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, +} + +impl UndoTxn { + pub fn new(data: Vec, timestamp_ms: u64) -> Self { + Self { data, timestamp_ms } + } + + pub fn is_empty(&self) -> bool { + self.data.is_empty() + } + + pub fn range(&self) -> UndoTxnMeta { + let mut start_idx = usize::MAX; + let mut end_idx = 0; + let mut multi_line = false; + + for chunk in &self.data { + match chunk { + UndoChunk::Insert { + char_idx, + text, + len_chars, + num_lines, + } => { + start_idx = start_idx.min(*char_idx); + end_idx = end_idx.max(char_idx + len_chars); + multi_line |= *num_lines > 1; + } + UndoChunk::Delete { + char_idx, + text, + len_chars, + num_lines, + } => { + start_idx = start_idx.min(*char_idx); + end_idx = end_idx.max(char_idx + len_chars); + multi_line |= *num_lines > 1; + } + } + } + + UndoTxnMeta::new(self.timestamp_ms, start_idx, end_idx, multi_line) + } +} + +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("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: Vec, +} + +impl UndoStack { + pub fn new() -> Self { + Self { + agg: UndoTxnAgg::new(), + txns: Vec::default(), + } + } + + pub fn pop(&mut self) -> Option { + self.txns.pop() + } + + pub fn commit(&mut self) { + if let Some(txn) = self.agg.commit() { + self.txns.push(txn); + } + } + + pub fn insert_char(&mut self, char_idx: usize, c: char) { + self.agg.insert_char(char_idx, c); + } + + pub fn insert_str(&mut self, char_idx: usize, s: &str) { + self.agg.insert_str(char_idx, s); + } + + pub fn insert_rope(&mut self, char_idx: usize, rope: &Rope) { + self.agg.insert_rope(char_idx, rope); + } + + pub fn remove_char(&mut self, char_range: Range, c: char) { + self.agg.remove_char(char_range, c); + } + + pub fn remove(&mut self, char_range: Range, text: &str) { + self.agg.remove(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, + creation_ts: u64, + mode: AggMode, + start_idx: usize, + end_idx: usize, + buffer: Rope, + chunks: Vec, +} + +impl UndoTxnAgg { + fn new() -> Self { + Self { + in_txn: false, + creation_ts: 0, + mode: AggMode::None, + start_idx: 0, + end_idx: 0, + buffer: Rope::new(), + chunks: Vec::with_capacity(8), + } + } + + fn begin_txn(&mut self) { + if self.in_txn { + return; + } + + self.in_txn = true; + self.creation_ts = Self::now(); + 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 { + let txn = UndoTxn::new(std::mem::take(&mut self.chunks), self.creation_ts); + #[cfg(feature = "dev")] + tracing::debug!("UndoTxnAgg::commit: {txn:?}"); + Some(txn) + } + } + + fn insert_char(&mut self, char_idx: usize, c: char) { + self.insert_preamble(char_idx); + self.buffer.insert_char(self.buffer.len_chars(), c); + self.end_idx += 1; + } + + fn insert_str(&mut self, char_idx: usize, s: &str) { + self.insert_preamble(char_idx); + self.buffer.insert(self.buffer.len_chars(), s); + self.end_idx += s.chars().count(); + } + + fn insert_rope(&mut self, char_idx: usize, rope: &Rope) { + self.insert_preamble(char_idx); + self.buffer.append(rope.clone()); + self.end_idx += rope.len_chars(); + } + + fn insert_preamble(&mut self, char_idx: usize) { + if !self.in_txn { + self.begin_txn(); + } + + 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, char_range: Range, c: char) { + self.remove_preamble(&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, char_range: Range, text: &str) { + self.remove_preamble(&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, char_range: &Range) { + if !self.in_txn { + self.begin_txn(); + } + + 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::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::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()); + } + } + + fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as u64 + } +} diff --git a/src/systems/immediate.rs b/src/systems/immediate.rs index 2736aa6..18b318e 100644 --- a/src/systems/immediate.rs +++ b/src/systems/immediate.rs @@ -3,7 +3,7 @@ use crate::{ 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,6 +16,7 @@ mod delete_char; mod join; mod paste; mod replace; +mod undo; mod yank; use delete_char::{backspace, delete_char}; @@ -92,6 +93,7 @@ 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), }; let (session, _) = active_session!(ctx); @@ -119,7 +121,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 +134,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..4aca345 --- /dev/null +++ b/src/systems/immediate/undo.rs @@ -0,0 +1,64 @@ +use ropey::Rope; + +use crate::{ + active_session_and_buffer, cmd::Cmd, components::{EditorCtx, MutBuffer, UndoTxnMeta}, systems::{commons::char_idx_to_coords, insert::Damage, nav::utils::ensure_cursor_inside_line}, +}; + +pub fn undo(ctx: &mut EditorCtx, cmd: Cmd) -> Damage { + let (_, buf_view, buffer) = active_session_and_buffer!(mut ctx); + + let mut cursor_idx = 0; + let mut merged_txn_meta = UndoTxnMeta::default(); + + for _ in 0..cmd.reps.unwrap_or(1) { + if let Some(txn_meta) = buffer.edit().undo() { + cursor_idx = txn_meta.start_idx; + merged_txn_meta.merge(txn_meta); + } else { + break; + } + } + + let damage = txn_meta_to_damage(merged_txn_meta, 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); + + damage +} + +fn txn_meta_to_damage(txn_meta: UndoTxnMeta, rope: &Rope) -> Damage { + if txn_meta.is_empty() { + return Damage::Intact; + } + + let max_idx = rope.len_chars().saturating_sub(1); + let start_idx = txn_meta.start_idx.min(max_idx); + let end_idx = txn_meta.end_idx.min(max_idx); + + let start_line = rope.char_to_line(start_idx); + let end_line = rope.char_to_line(end_idx); + + if txn_meta.multi_line { + Damage::From(start_line) + } else if start_line == end_line { + Damage::Line(start_line) + } else { + Damage::Range(start_line, end_line) + } +} 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/log.rs b/src/systems/insert/log.rs index 3175741..9d858ba 100644 --- a/src/systems/insert/log.rs +++ b/src/systems/insert/log.rs @@ -13,6 +13,10 @@ use crate::{ pub fn apply_insert_log(ctx: &mut EditorCtx, ops: &[EditOp], reps: usize) { let damage_evt = intepret_insert_log(ctx, ops, reps); + + let (_, _, buffer) = active_session_and_buffer!(mut ctx); + buffer.commit_undo_txn(); + broadcast_damage(ctx, damage_evt) } diff --git a/src/systems/mode.rs b/src/systems/mode.rs index 8fd185d..f5c5252 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,11 +37,12 @@ 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; if old_mode == Mode::Insert { + buffer.commit_undo_txn(); post_insert(ctx); } } 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, From 43004962c1fbca6ee50ea0fa2d0fa5453f3564a0 Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Wed, 4 Nov 2026 09:49:49 +0100 Subject: [PATCH 02/11] Format code properly --- src/systems/immediate/undo.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/systems/immediate/undo.rs b/src/systems/immediate/undo.rs index 4aca345..98589b2 100644 --- a/src/systems/immediate/undo.rs +++ b/src/systems/immediate/undo.rs @@ -1,7 +1,10 @@ use ropey::Rope; use crate::{ - active_session_and_buffer, cmd::Cmd, components::{EditorCtx, MutBuffer, UndoTxnMeta}, systems::{commons::char_idx_to_coords, insert::Damage, nav::utils::ensure_cursor_inside_line}, + active_session_and_buffer, + cmd::Cmd, + components::{EditorCtx, MutBuffer, UndoTxnMeta}, + systems::{commons::char_idx_to_coords, insert::Damage, nav::utils::ensure_cursor_inside_line}, }; pub fn undo(ctx: &mut EditorCtx, cmd: Cmd) -> Damage { From 188451f2d6cd81e024f677cd09aef072664ad08e Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Wed, 4 Nov 2026 11:40:35 +0100 Subject: [PATCH 03/11] Use a limited size deque for the undo stack --- src/components/undo.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/components/undo.rs b/src/components/undo.rs index 38c6264..3af7ddc 100644 --- a/src/components/undo.rs +++ b/src/components/undo.rs @@ -1,4 +1,4 @@ -use std::{fmt, ops::Range}; +use std::{collections::VecDeque, fmt, ops::Range}; use ropey::Rope; @@ -158,24 +158,29 @@ impl fmt::Display for UndoTxn { // taken care of by the UndoTxnAgg struct. pub struct UndoStack { agg: UndoTxnAgg, - txns: Vec, + txns: VecDeque, } impl UndoStack { + const MAX_TXNS: usize = 256; + pub fn new() -> Self { Self { agg: UndoTxnAgg::new(), - txns: Vec::default(), + txns: VecDeque::with_capacity(Self::MAX_TXNS), } } pub fn pop(&mut self) -> Option { - self.txns.pop() + self.txns.pop_back() } pub fn commit(&mut self) { if let Some(txn) = self.agg.commit() { - self.txns.push(txn); + if self.txns.len() >= Self::MAX_TXNS { + self.txns.pop_front(); + } + self.txns.push_back(txn); } } From 2bd4c22ad95770d49a6d6d1b5f26a10faafdf63f Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Wed, 4 Nov 2026 13:34:51 +0100 Subject: [PATCH 04/11] Yikes! Fix stupid errors in c command --- src/systems/interactive.rs | 21 +++++++++++---------- src/systems/nav/argint.rs | 2 +- 2 files changed, 12 insertions(+), 11 deletions(-) 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/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, From 60cbe13c120f17b039da70e52bcaebfb819221bb Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Wed, 4 Nov 2026 15:38:18 +0100 Subject: [PATCH 05/11] Better placement for undo txn commits --- src/systems/insert/log.rs | 4 ---- src/systems/insert/post_insert.rs | 6 ++++++ src/systems/mode.rs | 1 - 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/systems/insert/log.rs b/src/systems/insert/log.rs index 9d858ba..3175741 100644 --- a/src/systems/insert/log.rs +++ b/src/systems/insert/log.rs @@ -13,10 +13,6 @@ use crate::{ pub fn apply_insert_log(ctx: &mut EditorCtx, ops: &[EditOp], reps: usize) { let damage_evt = intepret_insert_log(ctx, ops, reps); - - let (_, _, buffer) = active_session_and_buffer!(mut ctx); - buffer.commit_undo_txn(); - broadcast_damage(ctx, damage_evt) } 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/mode.rs b/src/systems/mode.rs index f5c5252..44aa33f 100644 --- a/src/systems/mode.rs +++ b/src/systems/mode.rs @@ -42,7 +42,6 @@ pub fn enter_normal(ctx: &mut EditorCtx) { session.mode = Mode::Normal; if old_mode == Mode::Insert { - buffer.commit_undo_txn(); post_insert(ctx); } } From 4ab4c6c0445718d5e70ef49e6c4aaeab11736900 Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Wed, 4 Nov 2026 16:19:04 +0100 Subject: [PATCH 06/11] Undo all things --- src/systems/immediate.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/systems/immediate.rs b/src/systems/immediate.rs index 18b318e..19393b9 100644 --- a/src/systems/immediate.rs +++ b/src/systems/immediate.rs @@ -1,5 +1,5 @@ use crate::{ - active_session, + active_session, active_session_and_buffer, cmd::{Arg, Cmd, ImmediateOp, Motion, Operator}, components::{EditorCtx, Register}, systems::{ @@ -96,6 +96,11 @@ pub fn handle_immediate(ctx: &mut EditorCtx, args: ImmediateArgs) { 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); From 3a7b6a995ac9c13b18dd085d5054a4a5847b1f6c Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Thu, 5 Nov 2026 16:26:14 +0100 Subject: [PATCH 07/11] Fix damage calculation Computing dmage for an arbitrary set of undo transactions is tricky, since the damage won't be localized, and every extent might be affected by actions executed before. Out approach: record original line numbers, in addition to char indexes. If any chunk in a transaction has multiline scope, use the min line number for destroying from. Using the smaller line number is safe. If all chunks are single line, then joining all chunks using interval union will be safe. Since no lines were added or deleted, line numbers are still valid. Then we can do a destroy range or destroy line. --- src/components.rs | 2 +- src/components/buffer.rs | 60 ++++++------ src/components/session.rs | 4 +- src/components/undo.rs | 167 ++++++++++++++++++---------------- src/systems/immediate/undo.rs | 49 +++++----- 5 files changed, 151 insertions(+), 131 deletions(-) diff --git a/src/components.rs b/src/components.rs index 7655f64..49a746b 100644 --- a/src/components.rs +++ b/src/components.rs @@ -23,7 +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::UndoTxnMeta; +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 66f4c34..3b1b906 100644 --- a/src/components/buffer.rs +++ b/src/components/buffer.rs @@ -3,10 +3,7 @@ use std::ops::Range; use ropey::Rope; use super::undo::UndoStack; -use crate::components::{ - Change, Marks, - undo::{UndoChunk, UndoTxnMeta}, -}; +use crate::components::{Change, Marks, UndoSummary, undo::Action}; // Mutable view of a buffer pub trait MutBuffer { @@ -16,7 +13,7 @@ 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; + fn undo(&mut self) -> Option; } pub struct Buffer { @@ -147,37 +144,46 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { self.buffer.dirty = true; } - fn undo(&mut self) -> Option { + fn undo(&mut self) -> Option { let buffer = &mut self.buffer; - + if let Some(txn) = buffer.undo_stack.pop() { - let range = Some(txn.range()); + let mut summary = UndoSummary::default(); for chunk in txn.data.into_iter().rev() { - match chunk { - UndoChunk::Insert { - char_idx, - text, - len_chars, - num_lines, - } => { - let end_idx = char_idx + len_chars; - buffer.rope.remove(char_idx..end_idx); - buffer.marks.adjust(Change::delete(char_idx..end_idx)); + let s = mk_summary( + &buffer.rope, + txn.timestamp_ms, + 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)); } - UndoChunk::Delete { - char_idx, - text, - len_chars, - num_lines, - } => { - buffer.rope.insert(char_idx, &text); - buffer.marks.adjust(Change::insert(char_idx, len_chars)); + Action::Delete => { + buffer.rope.insert(chunk.char_idx, &chunk.text); + buffer + .marks + .adjust(Change::insert(chunk.char_idx, chunk.len_chars)); } } } - return range; + return Some(summary); } None } } + +fn mk_summary(rope: &Rope, timestamp_ms: 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, char_idx, line_idx) + } else { + UndoSummary::single_line(timestamp_ms, char_idx, line_idx) + } +} diff --git a/src/components/session.rs b/src/components/session.rs index 87b0bbd..0a069bd 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, undo::UndoTxnMeta}, misc, + components::{BufferId, DisplayBuffer, InsertLog, MutBuffer, undo::UndoSummary}, misc, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] @@ -216,7 +216,7 @@ impl MutBuffer for ExMutableBuffer<'_> { self.rope.remove(char_range); } - fn undo(&mut self) -> Option { + fn undo(&mut self) -> Option { None } } diff --git a/src/components/undo.rs b/src/components/undo.rs index 3af7ddc..8706dc1 100644 --- a/src/components/undo.rs +++ b/src/components/undo.rs @@ -2,35 +2,33 @@ use std::{collections::VecDeque, fmt, ops::Range}; use ropey::Rope; -// -- Undo Chunk --- +// --- 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 enum UndoChunk { - Insert { - char_idx: usize, - text: String, - len_chars: usize, - num_lines: usize, - }, - Delete { - char_idx: usize, - text: String, - len_chars: usize, - num_lines: usize, - }, +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 (kind, char_idx, text) = match self { - Self::Insert { char_idx, text, .. } => ("Insert", char_idx, text), - Self::Delete { char_idx, text, .. } => ("Delete", char_idx, text), + let action = match self.action { + Action::Insert => "Insert", + Action::Delete => "Delete", }; - f.debug_struct(kind) - .field("char_idx", char_idx) - .field("text", text) + f.debug_struct(action) + .field("char_idx", &self.char_idx) + .field("text", &self.text) .finish() } } @@ -41,50 +39,100 @@ impl fmt::Display for UndoChunk { } } -// -- Undo Transaction --- +// --- Undo Summary --- + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UndoScope { + None, + PatchRange { start_line: usize, end_line: usize }, + DestroyFrom { start_line: usize }, +} -// Undo transacton metadata. we will use this for computing Damage regions -// and status event messages. -pub struct UndoTxnMeta { +#[derive(Debug, Clone, Copy)] +pub struct UndoSummary { pub timestamp_ms: u64, pub start_idx: usize, - pub end_idx: usize, - pub multi_line: bool, + pub scope: UndoScope, } -impl UndoTxnMeta { - fn new(timestamp_ms: u64, start_idx: usize, end_idx: usize, multi_line: bool) -> Self { +impl UndoSummary { + pub fn single_line(timestamp_ms: u64, start_idx: usize, line: usize) -> Self { + Self { + timestamp_ms, + start_idx, + scope: UndoScope::PatchRange { + start_line: line, + end_line: line, + }, + } + } + + pub fn destroy_from(timestamp_ms: u64, start_idx: usize, line: usize) -> Self { Self { timestamp_ms, start_idx, - end_idx, - multi_line, + scope: UndoScope::DestroyFrom { start_line: line }, } } pub fn is_empty(&self) -> bool { - self.timestamp_ms == u64::MAX && self.start_idx == usize::MAX && self.end_idx == 0 + self.scope == UndoScope::None } - pub fn merge(&mut self, other: Self) { + pub fn merge(&mut self, other: UndoSummary) { self.timestamp_ms = self.timestamp_ms.min(other.timestamp_ms); self.start_idx = self.start_idx.min(other.start_idx); - self.end_idx = self.end_idx.max(other.end_idx); - self.multi_line |= other.multi_line; + + 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 UndoTxnMeta { +impl Default for UndoSummary { fn default() -> Self { Self { timestamp_ms: u64::MAX, start_idx: usize::MAX, - end_idx: 0, - multi_line: false, + 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. @@ -97,43 +145,6 @@ impl UndoTxn { pub fn new(data: Vec, timestamp_ms: u64) -> Self { Self { data, timestamp_ms } } - - pub fn is_empty(&self) -> bool { - self.data.is_empty() - } - - pub fn range(&self) -> UndoTxnMeta { - let mut start_idx = usize::MAX; - let mut end_idx = 0; - let mut multi_line = false; - - for chunk in &self.data { - match chunk { - UndoChunk::Insert { - char_idx, - text, - len_chars, - num_lines, - } => { - start_idx = start_idx.min(*char_idx); - end_idx = end_idx.max(char_idx + len_chars); - multi_line |= *num_lines > 1; - } - UndoChunk::Delete { - char_idx, - text, - len_chars, - num_lines, - } => { - start_idx = start_idx.min(*char_idx); - end_idx = end_idx.max(char_idx + len_chars); - multi_line |= *num_lines > 1; - } - } - } - - UndoTxnMeta::new(self.timestamp_ms, start_idx, end_idx, multi_line) - } } impl fmt::Debug for UndoTxn { @@ -152,7 +163,7 @@ impl fmt::Display for UndoTxn { } } -// -- Undo Stack --- +// --- Undo Stack --- // Stack of undo transactions. The chunk and transactions managing is // taken care of by the UndoTxnAgg struct. @@ -377,7 +388,8 @@ impl UndoTxnAgg { if self.buffer.len_chars() > 0 { match self.mode { AggMode::Insert => { - self.chunks.push(UndoChunk::Insert { + self.chunks.push(UndoChunk { + action: Action::Insert, char_idx: self.start_idx, text: self.buffer.to_string(), len_chars: self.buffer.len_chars(), @@ -385,7 +397,8 @@ impl UndoTxnAgg { }); } AggMode::Delete => { - self.chunks.push(UndoChunk::Delete { + self.chunks.push(UndoChunk { + action: Action::Delete, char_idx: self.start_idx, text: self.buffer.to_string(), len_chars: self.buffer.len_chars(), diff --git a/src/systems/immediate/undo.rs b/src/systems/immediate/undo.rs index 98589b2..b13d1ff 100644 --- a/src/systems/immediate/undo.rs +++ b/src/systems/immediate/undo.rs @@ -3,7 +3,7 @@ use ropey::Rope; use crate::{ active_session_and_buffer, cmd::Cmd, - components::{EditorCtx, MutBuffer, UndoTxnMeta}, + components::{EditorCtx, MutBuffer, UndoScope, UndoSummary}, systems::{commons::char_idx_to_coords, insert::Damage, nav::utils::ensure_cursor_inside_line}, }; @@ -11,18 +11,23 @@ pub fn undo(ctx: &mut EditorCtx, cmd: Cmd) -> Damage { let (_, buf_view, buffer) = active_session_and_buffer!(mut ctx); let mut cursor_idx = 0; - let mut merged_txn_meta = UndoTxnMeta::default(); + let mut merged_summary = UndoSummary::default(); for _ in 0..cmd.reps.unwrap_or(1) { - if let Some(txn_meta) = buffer.edit().undo() { - cursor_idx = txn_meta.start_idx; - merged_txn_meta.merge(txn_meta); + if let Some(undo_summary) = buffer.edit().undo() { + cursor_idx = undo_summary.start_idx; + merged_summary.merge(undo_summary); } else { break; } } - let damage = txn_meta_to_damage(merged_txn_meta, buffer.rope()); + if merged_summary.is_empty() { + return Damage::Intact; + } + + let damage = undo_summary_to_damage(merged_summary, buffer.rope()); + match damage { Damage::Intact => {} Damage::Line(line) => { @@ -45,23 +50,19 @@ pub fn undo(ctx: &mut EditorCtx, cmd: Cmd) -> Damage { damage } -fn txn_meta_to_damage(txn_meta: UndoTxnMeta, rope: &Rope) -> Damage { - if txn_meta.is_empty() { - return Damage::Intact; - } - - let max_idx = rope.len_chars().saturating_sub(1); - let start_idx = txn_meta.start_idx.min(max_idx); - let end_idx = txn_meta.end_idx.min(max_idx); - - let start_line = rope.char_to_line(start_idx); - let end_line = rope.char_to_line(end_idx); - - if txn_meta.multi_line { - Damage::From(start_line) - } else if start_line == end_line { - Damage::Line(start_line) - } else { - Damage::Range(start_line, end_line) +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), } } From 37b3656b820b8f16b965ed13503c447305134742 Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Thu, 5 Nov 2026 16:49:07 +0100 Subject: [PATCH 08/11] Forgot setting buffer dirty --- src/components/buffer.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/components/buffer.rs b/src/components/buffer.rs index 3b1b906..362e258 100644 --- a/src/components/buffer.rs +++ b/src/components/buffer.rs @@ -112,6 +112,7 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { } self.buffer.marks.adjust(Change::insert(char_idx, len)); + self.buffer.dirty = true; } fn insert_rope(&mut self, char_idx: usize, rope: &Rope) { From 177ef8375332e4e46375b6418f990b95b16734a1 Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Fri, 6 Nov 2026 10:12:26 +0100 Subject: [PATCH 09/11] Add dirty flag handling to undo logic --- src/components/buffer.rs | 28 ++++++++++++---- src/components/undo.rs | 70 +++++++++++++++++++++++----------------- test-docs/argint.txt | 4 ++- 3 files changed, 65 insertions(+), 37 deletions(-) diff --git a/src/components/buffer.rs b/src/components/buffer.rs index 362e258..6d8ef55 100644 --- a/src/components/buffer.rs +++ b/src/components/buffer.rs @@ -83,7 +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(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; } @@ -94,7 +96,9 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { } self.buffer.rope.insert(char_idx, text); - self.buffer.undo_stack.insert_str(char_idx, text); + self.buffer + .undo_stack + .insert_str(self.buffer.dirty, char_idx, text); self.buffer .marks @@ -104,10 +108,11 @@ 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(char_idx + i, c); + self.buffer + .undo_stack + .insert_char(self.buffer.dirty, char_idx + i, c); len += 1; } @@ -123,7 +128,10 @@ 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(char_idx, rope); + + self.buffer + .undo_stack + .insert_rope(self.buffer.dirty, char_idx, rope); self.buffer .marks @@ -134,10 +142,14 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { 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(char_range.clone(), c); + 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(char_range.clone(), &text); + self.buffer + .undo_stack + .remove(self.buffer.dirty, char_range.clone(), &text); } self.buffer.rope.remove(char_range.clone()); @@ -149,6 +161,8 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { 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( diff --git a/src/components/undo.rs b/src/components/undo.rs index 8706dc1..65f23d9 100644 --- a/src/components/undo.rs +++ b/src/components/undo.rs @@ -139,11 +139,16 @@ impl Default for UndoSummary { pub struct UndoTxn { pub data: Vec, pub timestamp_ms: u64, + pub dirty: bool, } impl UndoTxn { - pub fn new(data: Vec, timestamp_ms: u64) -> Self { - Self { data, timestamp_ms } + pub fn new(data: Vec, timestamp_ms: u64, dirty: bool) -> Self { + Self { + data, + timestamp_ms, + dirty, + } } } @@ -151,6 +156,7 @@ 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() @@ -195,24 +201,24 @@ impl UndoStack { } } - pub fn insert_char(&mut self, char_idx: usize, c: char) { - self.agg.insert_char(char_idx, c); + 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, char_idx: usize, s: &str) { - self.agg.insert_str(char_idx, s); + 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, char_idx: usize, rope: &Rope) { - self.agg.insert_rope(char_idx, rope); + 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, char_range: Range, c: char) { - self.agg.remove_char(char_range, c); + 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, char_range: Range, text: &str) { - self.agg.remove(char_range, text); + pub fn remove(&mut self, dirty: bool, char_range: Range, text: &str) { + self.agg.remove(dirty, char_range, text); } } @@ -243,6 +249,7 @@ enum AggMode { struct UndoTxnAgg { in_txn: bool, creation_ts: u64, + dirty: bool, mode: AggMode, start_idx: usize, end_idx: usize, @@ -255,6 +262,7 @@ impl UndoTxnAgg { Self { in_txn: false, creation_ts: 0, + dirty: false, mode: AggMode::None, start_idx: 0, end_idx: 0, @@ -263,13 +271,14 @@ impl UndoTxnAgg { } } - fn begin_txn(&mut self) { + fn begin_txn(&mut self, dirty: bool) { if self.in_txn { return; } self.in_txn = true; self.creation_ts = Self::now(); + self.dirty = dirty; self.mode = AggMode::None; self.start_idx = 0; self.end_idx = 0; @@ -288,34 +297,37 @@ impl UndoTxnAgg { if self.chunks.is_empty() { None } else { - let txn = UndoTxn::new(std::mem::take(&mut self.chunks), self.creation_ts); + let data = std::mem::take(&mut self.chunks); + let txn = UndoTxn::new(data, self.creation_ts, self.dirty); #[cfg(feature = "dev")] - tracing::debug!("UndoTxnAgg::commit: {txn:?}"); + { + tracing::debug!("UndoTxnAgg::commit: {txn:?}"); + } Some(txn) } } - fn insert_char(&mut self, char_idx: usize, c: char) { - self.insert_preamble(char_idx); + 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, char_idx: usize, s: &str) { - self.insert_preamble(char_idx); + 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, char_idx: usize, rope: &Rope) { - self.insert_preamble(char_idx); + 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, char_idx: usize) { + fn insert_preamble(&mut self, dirty: bool, char_idx: usize) { if !self.in_txn { - self.begin_txn(); + self.begin_txn(dirty); } let needs_flush = match self.mode { @@ -333,8 +345,8 @@ impl UndoTxnAgg { self.mode = AggMode::Insert; } - fn remove_char(&mut self, char_range: Range, c: char) { - self.remove_preamble(&char_range); + 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) @@ -349,8 +361,8 @@ impl UndoTxnAgg { } } - fn remove(&mut self, char_range: Range, text: &str) { - self.remove_preamble(&char_range); + 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; @@ -362,9 +374,9 @@ impl UndoTxnAgg { } } - fn remove_preamble(&mut self, char_range: &Range) { + fn remove_preamble(&mut self, dirty: bool, char_range: &Range) { if !self.in_txn { - self.begin_txn(); + self.begin_txn(dirty); } let needs_flush = match self.mode { diff --git a/test-docs/argint.txt b/test-docs/argint.txt index 8ede896..e05ec00 100644 --- a/test-docs/argint.txt +++ b/test-docs/argint.txt @@ -6,6 +6,8 @@ aaaa aaaa bbbb bbbb -aaa aaa +Blah aaa bbb bbb ccc ccc + +Extra From f4fc5b2445fe64487f2b095980f236d6acb7b073 Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Fri, 6 Nov 2026 18:20:18 +0100 Subject: [PATCH 10/11] Notify undos --- src/components/buffer.rs | 13 ++++++++++--- src/components/session.rs | 3 ++- src/components/undo.rs | 34 ++++++++++++++++++++++------------ src/misc.rs | 1 + src/misc/time.rs | 27 +++++++++++++++++++++++++++ src/systems/event.rs | 27 ++++++++++++++++++++++++++- src/systems/immediate.rs | 1 + src/systems/immediate/undo.rs | 27 +++++++++++++++++++++++++-- test-docs/argint.txt | 5 +---- 9 files changed, 115 insertions(+), 23 deletions(-) create mode 100644 src/misc/time.rs diff --git a/src/components/buffer.rs b/src/components/buffer.rs index 6d8ef55..a547a39 100644 --- a/src/components/buffer.rs +++ b/src/components/buffer.rs @@ -168,6 +168,7 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { let s = mk_summary( &buffer.rope, txn.timestamp_ms, + txn.change_id, chunk.char_idx, chunk.num_lines, ); @@ -194,11 +195,17 @@ impl<'a> MutBuffer for SessionMutableBuffer<'a> { } } -fn mk_summary(rope: &Rope, timestamp_ms: u64, char_idx: usize, num_lines: usize) -> UndoSummary { +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, char_idx, line_idx) + UndoSummary::destroy_from(timestamp_ms, change_id, char_idx, line_idx) } else { - UndoSummary::single_line(timestamp_ms, char_idx, line_idx) + UndoSummary::single_line(timestamp_ms, change_id, char_idx, line_idx) } } diff --git a/src/components/session.rs b/src/components/session.rs index 0a069bd..b308ff0 100644 --- a/src/components/session.rs +++ b/src/components/session.rs @@ -4,7 +4,8 @@ use ratatui::layout::{Position, Rect}; use ropey::Rope; use crate::{ - components::{BufferId, DisplayBuffer, InsertLog, MutBuffer, undo::UndoSummary}, misc, + components::{BufferId, DisplayBuffer, InsertLog, MutBuffer, undo::UndoSummary}, + misc, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] diff --git a/src/components/undo.rs b/src/components/undo.rs index 65f23d9..bce9cc5 100644 --- a/src/components/undo.rs +++ b/src/components/undo.rs @@ -2,6 +2,8 @@ use std::{collections::VecDeque, fmt, ops::Range}; use ropey::Rope; +use crate::misc; + // --- Undo Chunk --- pub enum Action { @@ -51,14 +53,18 @@ pub enum UndoScope { #[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, start_idx: usize, line: usize) -> Self { + 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, @@ -67,9 +73,11 @@ impl UndoSummary { } } - pub fn destroy_from(timestamp_ms: u64, start_idx: usize, line: usize) -> Self { + 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 }, } @@ -81,6 +89,8 @@ impl UndoSummary { 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) { @@ -125,6 +135,8 @@ 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, } @@ -139,14 +151,16 @@ impl Default for UndoSummary { 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, dirty: bool) -> Self { + pub fn new(data: Vec, timestamp_ms: u64, change_id: u64, dirty: bool) -> Self { Self { data, timestamp_ms, + change_id, dirty, } } @@ -248,6 +262,7 @@ enum AggMode { struct UndoTxnAgg { in_txn: bool, + change_counter: u64, creation_ts: u64, dirty: bool, mode: AggMode, @@ -261,6 +276,7 @@ impl UndoTxnAgg { fn new() -> Self { Self { in_txn: false, + change_counter: 0, creation_ts: 0, dirty: false, mode: AggMode::None, @@ -277,7 +293,7 @@ impl UndoTxnAgg { } self.in_txn = true; - self.creation_ts = Self::now(); + self.creation_ts = misc::time::now(); self.dirty = dirty; self.mode = AggMode::None; self.start_idx = 0; @@ -297,8 +313,9 @@ impl UndoTxnAgg { 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.dirty); + let txn = UndoTxn::new(data, self.creation_ts, self.change_counter, self.dirty); #[cfg(feature = "dev")] { tracing::debug!("UndoTxnAgg::commit: {txn:?}"); @@ -423,11 +440,4 @@ impl UndoTxnAgg { self.buffer.remove(0..self.buffer.len_chars()); } } - - fn now() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_millis() as u64 - } } 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..88413c4 --- /dev/null +++ b/src/misc/time.rs @@ -0,0 +1,27 @@ +use anyhow::Result; +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_time_diff(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 hours = t_diff_secs / 3600; + let mins = (t_diff_secs % 3600) / 60; + let secs = (t_diff_secs % 3600) % 60; + write!(w, "{}:{}:{}", hours, mins, secs)?; + } + + Ok(()) +} diff --git a/src/systems/event.rs b/src/systems/event.rs index 4a2d08a..7fd07de 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_time_diff(&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 19393b9..1ce514f 100644 --- a/src/systems/immediate.rs +++ b/src/systems/immediate.rs @@ -22,6 +22,7 @@ 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)] diff --git a/src/systems/immediate/undo.rs b/src/systems/immediate/undo.rs index b13d1ff..4ed83c5 100644 --- a/src/systems/immediate/undo.rs +++ b/src/systems/immediate/undo.rs @@ -3,12 +3,21 @@ use ropey::Rope; use crate::{ active_session_and_buffer, cmd::Cmd, - components::{EditorCtx, MutBuffer, UndoScope, UndoSummary}, - systems::{commons::char_idx_to_coords, insert::Damage, nav::utils::ensure_cursor_inside_line}, + 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(); @@ -23,9 +32,11 @@ pub fn undo(ctx: &mut EditorCtx, cmd: Cmd) -> Damage { } 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 { @@ -47,6 +58,7 @@ pub fn undo(ctx: &mut EditorCtx, cmd: Cmd) -> Damage { 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 } @@ -66,3 +78,14 @@ fn undo_summary_to_damage(summary: UndoSummary, rope: &Rope) -> Damage { 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/test-docs/argint.txt b/test-docs/argint.txt index e05ec00..b5157c0 100644 --- a/test-docs/argint.txt +++ b/test-docs/argint.txt @@ -5,9 +5,6 @@ ddd eee aaaa aaaa bbbb bbbb - -Blah aaa +aaa aaa bbb bbb ccc ccc - -Extra From 0a6f41c32a2bf8a6f2bce3986ca6adc323bc1377 Mon Sep 17 00:00:00 2001 From: Pablo Pedemonte Date: Fri, 6 Nov 2026 18:50:24 +0100 Subject: [PATCH 11/11] Better undo reporting --- Cargo.lock | 246 +++++++++++++++++++++++++++++++++++++++++-- Cargo.toml | 1 + src/misc/time.rs | 26 +++-- src/systems/event.rs | 2 +- 4 files changed, 259 insertions(+), 16 deletions(-) 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/misc/time.rs b/src/misc/time.rs index 88413c4..707393f 100644 --- a/src/misc/time.rs +++ b/src/misc/time.rs @@ -1,4 +1,5 @@ -use anyhow::Result; +use anyhow::{Context, Result}; +use chrono::{Datelike, Local, TimeZone, Timelike}; use std::{fmt::Write, write}; pub fn now() -> u64 { @@ -8,7 +9,7 @@ pub fn now() -> u64 { .as_millis() as u64 } -pub fn ppr_time_diff(mut w: impl Write, timestamp_ms: u64) -> Result<()> { +pub fn ppr_timestamp_ms(mut w: impl Write, timestamp_ms: u64) -> Result<()> { let now = now(); let t_diff_secs = (now - timestamp_ms) / 1000; @@ -17,10 +18,23 @@ pub fn ppr_time_diff(mut w: impl Write, timestamp_ms: u64) -> Result<()> { } else if t_diff_secs < 100 { write!(w, "{} seconds ago", t_diff_secs)?; } else { - let hours = t_diff_secs / 3600; - let mins = (t_diff_secs % 3600) / 60; - let secs = (t_diff_secs % 3600) % 60; - write!(w, "{}:{}:{}", hours, mins, secs)?; + 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 7fd07de..32aefe4 100644 --- a/src/systems/event.rs +++ b/src/systems/event.rs @@ -86,5 +86,5 @@ pub fn on_undo( status.set_msg(Level::Info, ""); write!(status.msg, "{count} {change}; before #{change_id} ") .expect("writing to a String cannot fail"); - time::ppr_time_diff(&mut status.msg, timestamp_ms).expect("writing to a String cannot fail"); + time::ppr_timestamp_ms(&mut status.msg, timestamp_ms).expect("writing to a String cannot fail"); }