hjkl_buffer/content.rs
1//! Per-document text content. Arc-shareable across multiple [`crate::Buffer`]
2//! views.
3//!
4//! [`Content`] 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::Buffer`] is the per-window wrapper. It holds an
11//! `Arc<Mutex<Content>>` plus the per-window cursor. Two `Buffer`
12//! instances that share one `Content` see the same text and folds, but
13//! each moves its cursor independently.
14//!
15//! ## Concurrency
16//!
17//! Held inside `Arc<Mutex<Content>>` so multiple `Buffer` 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::Buffer`] views of the
27/// same file. Wrap in `Arc<Mutex<Content>>` and pass to
28/// [`crate::Buffer::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/// `Content` 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 Content {
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: O(1)-clone rope snapshots before each edit group.
70 pub(crate) undo_stack: Vec<crate::UndoEntry>,
71 /// Redo history: entries pushed when the user undoes.
72 pub(crate) redo_stack: Vec<crate::UndoEntry>,
73 /// Set whenever the buffer content changes; cleared by the engine's
74 /// `take_dirty` accessor.
75 pub(crate) content_dirty: bool,
76 /// Cached `Arc<String>` of the joined document for the engine's
77 /// `content_arc` fast path. Invalidated by `mark_content_dirty`.
78 pub(crate) cached_editor_content: Option<std::sync::Arc<String>>,
79 /// Pending [`crate::FoldOp`]s raised by `z…` keystrokes, `:fold*` ex
80 /// commands, and the edit-pipeline's fold invalidation. Drained by
81 /// hosts via `Editor::take_fold_ops`.
82 pub(crate) pending_fold_ops: Vec<crate::FoldOp>,
83 /// Pending edit log drained by `Editor::take_changes`. Each entry is
84 /// a [`crate::EngineEdit`] mapped from the underlying buffer edit.
85 pub(crate) change_log: Vec<crate::EngineEdit>,
86 /// Pending `ContentEdit` records emitted by `mutate_edit`. Drained by
87 /// hosts via `Editor::take_content_edits` for fan-in to a syntax tree.
88 pub(crate) pending_content_edits: Vec<crate::ContentEdit>,
89 /// Pending "reset" flag set when the entire buffer is replaced
90 /// (e.g. `set_content` / `restore`). Supersedes any queued
91 /// `pending_content_edits` on the same frame.
92 pub(crate) pending_content_reset: bool,
93 /// Named marks (`'a`–`'z`, `'A`–`'Z`) — buffer-scoped cursor positions
94 /// `(row, col)`. Shared across all window views of this buffer (#154).
95 pub(crate) marks: std::collections::BTreeMap<char, (usize, usize)>,
96 /// Cached syntax-derived foldable block ranges that `:foldsyntax`
97 /// consumes; a property of the buffer content, shared across views (#154).
98 pub(crate) syntax_fold_ranges: Vec<(usize, usize)>,
99}
100
101impl Default for Content {
102 fn default() -> Self {
103 Self::new()
104 }
105}
106
107impl Content {
108 /// New empty content with one empty row.
109 pub fn new() -> Self {
110 Self {
111 text: ropey::Rope::new(),
112 dirty_gen: 0,
113 folds: Vec::new(),
114 cached_joined: None,
115 cached_byte_len: None,
116 undo_stack: Vec::new(),
117 redo_stack: Vec::new(),
118 content_dirty: false,
119 cached_editor_content: None,
120 pending_fold_ops: Vec::new(),
121 change_log: Vec::new(),
122 pending_content_edits: Vec::new(),
123 pending_content_reset: false,
124 marks: std::collections::BTreeMap::new(),
125 syntax_fold_ranges: Vec::new(),
126 }
127 }
128
129 /// Build content from a flat string. Splits on `\n`; a trailing
130 /// `\n` produces a trailing empty line (matches ropey's own convention).
131 #[allow(clippy::should_implement_trait)]
132 pub fn from_str(text: &str) -> Self {
133 Self {
134 text: ropey::Rope::from_str(text),
135 dirty_gen: 0,
136 folds: Vec::new(),
137 cached_joined: None,
138 cached_byte_len: None,
139 undo_stack: Vec::new(),
140 redo_stack: Vec::new(),
141 content_dirty: false,
142 cached_editor_content: None,
143 pending_fold_ops: Vec::new(),
144 change_log: Vec::new(),
145 pending_content_edits: Vec::new(),
146 pending_content_reset: false,
147 marks: std::collections::BTreeMap::new(),
148 syntax_fold_ranges: Vec::new(),
149 }
150 }
151}