Skip to main content

hjkl_buffer/
content.rs

1//! Per-document text content. Arc-shareable across multiple [`crate::View`]
2//! views.
3//!
4//! [`Buffer`] owns everything that belongs to the document itself:
5//!
6//! - The `text` rope (text content).
7//! - The `dirty_gen` render-cache generation counter.
8//! - Manual folds (`folds`).
9//!
10//! [`crate::View`] is the per-window wrapper. It holds an
11//! `Arc<Mutex<Buffer>>` plus the per-window cursor. Two `View`
12//! instances that share one `Buffer` see the same text and folds, but
13//! each moves its cursor independently.
14//!
15//! ## Concurrency
16//!
17//! Held inside `Arc<Mutex<Buffer>>` so multiple `View` views can share
18//! one document safely. `Mutex` (not `RefCell`) because the engine's
19//! `Cursor`, `Query`, `BufferEdit`, and `Search` traits require `Send`,
20//! and `RefCell` is `!Send`. Lock contention is near-zero in the
21//! single-threaded app loop; the Mutex is essentially a free `Send`
22//! adapter.
23
24use crate::folds::Fold;
25
26/// Per-document state shared across all [`crate::View`] views of the
27/// same file. Wrap in `Arc<Mutex<Buffer>>` and pass to
28/// [`crate::View::new_view`] to create an additional window onto the
29/// same content.
30///
31/// Uses a `ropey::Rope` for O(log N) edits and O(1) byte-length queries.
32/// The rope always contains at least one logical line: a freshly constructed
33/// `Buffer` holds an empty rope (which `ropey` reports as 1 line) so
34/// cursor positions never need an "is the buffer empty?" branch.
35///
36/// ## Line semantics
37///
38/// `ropey::Rope::len_lines()` and `split('\n').count()` agree for all inputs:
39/// - `""` → 1 line
40/// - `"foo\n"` → 2 lines (trailing empty line)
41/// - `"a\nb\n"` → 3 lines
42///
43/// `Rope::line(i)` returns a `RopeSlice` that includes the trailing `\n`
44/// for non-final lines. Public accessors strip it before returning `String`.
45pub struct Buffer {
46    /// Rope-backed document text. Always non-empty: `ropey::Rope::new()`
47    /// (an empty rope) reports `len_lines() == 1`, satisfying the "at least
48    /// one row" invariant without a separate sentinel.
49    pub(crate) text: ropey::Rope,
50    /// Bumps on every mutation; render cache keys against this so a
51    /// per-row `Line` gets recomputed when its source row changes.
52    pub(crate) dirty_gen: u64,
53    /// Manual folds — closed ranges hide rows in the render path.
54    /// `pub(crate)` so the [`crate::folds`] module can read/write
55    /// directly (same visibility as before the split).
56    pub(crate) folds: Vec<Fold>,
57    /// Cached `rope.to_string()` keyed by the `dirty_gen` at build time.
58    /// Multiple per-tick consumers (syntax submit, LSP notify, git
59    /// signature, dirty hash) all need the joined document; rebuilding
60    /// per consumer was ~4× the line-clone + alloc cost per keystroke
61    /// on a 400-line file (visible as insert-mode lag).
62    pub(crate) cached_joined: Option<(u64, std::sync::Arc<String>)>,
63    /// Cached canonical byte length keyed by `dirty_gen` at compute time.
64    /// `Rope::len_bytes()` is O(1) but holding the cache avoids even that
65    /// small overhead on repeated callers within the same tick.
66    pub(crate) cached_byte_len: Option<(u64, usize)>,
67
68    // ── Per-buffer engine state (relocated from hjkl-engine::Editor) ──────
69    /// Undo history: an arena tree of O(1)-clone rope snapshots (Phase 2a).
70    /// Replaces the old `undo_stack` /
71    /// `redo_stack` `Vec<UndoEntry>` pair; the tree stays linear (each node
72    /// has ≤ 1 child) so its behaviour is byte-identical to the two stacks —
73    /// see [`crate::UndoTree`]'s module comment for the mapping.
74    pub(crate) undo: crate::UndoTree,
75    /// Undo-group nesting depth. `> 0` while an [`crate::UndoGroup`] guard is
76    /// live (see hjkl-engine). At depth `0` `push_undo` behaves exactly as it
77    /// always has (one entry per call); at depth `> 0` every mutation inside
78    /// the outermost group coalesces into a single undo entry.
79    pub(crate) undo_group_depth: u32,
80    /// Set once the outermost open group has taken its single pre-group
81    /// snapshot; every later `push_undo` in the group is then suppressed.
82    pub(crate) undo_group_armed: bool,
83    /// `dirty_gen` captured when the outermost group opened. If it is
84    /// unchanged when the group closes, the group mutated nothing and its
85    /// armed snapshot is popped so a no-op group leaves zero undo entries.
86    pub(crate) undo_group_open_gen: u64,
87    /// Set whenever the buffer content changes; cleared by the engine's
88    /// `take_dirty` accessor.
89    pub(crate) content_dirty: bool,
90    /// Cached `Arc<String>` of the joined document for the engine's
91    /// `content_arc` fast path. Invalidated by `mark_content_dirty`.
92    pub(crate) cached_editor_content: Option<std::sync::Arc<String>>,
93    /// Pending [`crate::FoldOp`]s raised by `z…` keystrokes, `:fold*` ex
94    /// commands, and the edit-pipeline's fold invalidation. Drained by
95    /// hosts via `Editor::take_fold_ops`.
96    pub(crate) pending_fold_ops: Vec<crate::FoldOp>,
97    /// Pending edit log drained by `Editor::take_changes`. Each entry is
98    /// a [`crate::EngineEdit`] mapped from the underlying buffer edit.
99    pub(crate) change_log: Vec<crate::EngineEdit>,
100    /// Pending `ContentEdit` records emitted by `mutate_edit`. Drained by
101    /// hosts via `Editor::take_content_edits` for fan-in to a syntax tree.
102    pub(crate) pending_content_edits: Vec<crate::ContentEdit>,
103    /// Pending "reset" flag set when the entire buffer is replaced
104    /// (e.g. `set_content` / `restore`). Supersedes any queued
105    /// `pending_content_edits` on the same frame.
106    pub(crate) pending_content_reset: bool,
107    /// Named marks (`'a`–`'z`, `'A`–`'Z`) — buffer-scoped cursor positions
108    /// `(row, col)`. Shared across all window views of this buffer (#154).
109    pub(crate) marks: std::collections::BTreeMap<char, (usize, usize)>,
110    /// Cached syntax-derived foldable block ranges that `:foldsyntax`
111    /// consumes; a property of the buffer content, shared across views (#154).
112    pub(crate) syntax_fold_ranges: Vec<(usize, usize)>,
113    /// Last cursor `(row, col)` committed on this document by ANY view.
114    /// Every [`crate::View::set_cursor`] (the single choke point all engine
115    /// cursor moves route through) writes it, so with several windows onto
116    /// one buffer the most-recently-moved cursor wins by construction. Read
117    /// at write/close/exit to persist cross-session cursor memory.
118    /// In-memory only — no I/O on move.
119    pub(crate) last_cursor: (usize, usize),
120}
121
122impl Default for Buffer {
123    fn default() -> Self {
124        Self::new()
125    }
126}
127
128impl Buffer {
129    /// New empty content with one empty row.
130    pub fn new() -> Self {
131        let text = ropey::Rope::new();
132        let undo = crate::UndoTree::new(text.clone());
133        Self {
134            text,
135            dirty_gen: 0,
136            folds: Vec::new(),
137            cached_joined: None,
138            cached_byte_len: None,
139            undo,
140            undo_group_depth: 0,
141            undo_group_armed: false,
142            undo_group_open_gen: 0,
143            content_dirty: false,
144            cached_editor_content: None,
145            pending_fold_ops: Vec::new(),
146            change_log: Vec::new(),
147            pending_content_edits: Vec::new(),
148            pending_content_reset: false,
149            marks: std::collections::BTreeMap::new(),
150            syntax_fold_ranges: Vec::new(),
151            last_cursor: (0, 0),
152        }
153    }
154
155    /// Build content from a flat string. Splits on `\n`; a trailing
156    /// `\n` produces a trailing empty line (matches ropey's own convention).
157    #[allow(clippy::should_implement_trait)]
158    pub fn from_str(text: &str) -> Self {
159        let text = ropey::Rope::from_str(text);
160        let undo = crate::UndoTree::new(text.clone());
161        Self {
162            text,
163            dirty_gen: 0,
164            folds: Vec::new(),
165            cached_joined: None,
166            cached_byte_len: None,
167            undo,
168            undo_group_depth: 0,
169            undo_group_armed: false,
170            undo_group_open_gen: 0,
171            content_dirty: false,
172            cached_editor_content: None,
173            pending_fold_ops: Vec::new(),
174            change_log: Vec::new(),
175            pending_content_edits: Vec::new(),
176            pending_content_reset: false,
177            marks: std::collections::BTreeMap::new(),
178            syntax_fold_ranges: Vec::new(),
179            last_cursor: (0, 0),
180        }
181    }
182
183    // ── Undo-group coalescing (Phase 1) ────────────────────────────────────
184    //
185    // A group makes a composed operation (`:g`, `:normal`, a macro replay)
186    // record ONE undo step instead of one per underlying `push_undo`. The
187    // depth counter is re-entrant: nested groups just nest, only the
188    // outermost close commits.
189
190    /// Open (nest into) an undo group. On the outermost open (depth `0→1`)
191    /// record the current `dirty_gen` and disarm, so the group's first
192    /// mutating `push_undo` takes exactly one snapshot.
193    pub fn undo_group_enter(&mut self) {
194        if self.undo_group_depth == 0 {
195            self.undo_group_armed = false;
196            self.undo_group_open_gen = self.dirty_gen;
197        }
198        self.undo_group_depth = self.undo_group_depth.saturating_add(1);
199    }
200
201    /// Close (unnest) an undo group. On the outermost close (depth `1→0`), if
202    /// the group armed a snapshot but `dirty_gen` is unchanged since it opened
203    /// (nothing was mutated), pop that snapshot so a no-op group leaves zero
204    /// undo entries. Resets the group flags.
205    pub fn undo_group_exit(&mut self) {
206        if self.undo_group_depth == 0 {
207            return;
208        }
209        self.undo_group_depth -= 1;
210        if self.undo_group_depth == 0 {
211            if self.undo_group_armed && self.dirty_gen == self.undo_group_open_gen {
212                // Drop the armed snapshot: splice out the just-committed
213                // boundary node, restoring the tree to its pre-group shape.
214                self.undo.pop_committed();
215            }
216            self.undo_group_armed = false;
217        }
218    }
219
220    /// Whether an undo group is currently open (depth `> 0`).
221    pub fn undo_group_active(&self) -> bool {
222        self.undo_group_depth > 0
223    }
224
225    /// Arm the open group's single snapshot. Returns `true` if this call armed
226    /// it (the first mutating `push_undo` in the group, which must take the
227    /// snapshot), `false` if it was already armed (a later push to suppress).
228    pub fn undo_group_arm(&mut self) -> bool {
229        if self.undo_group_armed {
230            false
231        } else {
232            self.undo_group_armed = true;
233            true
234        }
235    }
236}