Skip to main content

strop_core/
buffer.rs

1//! The buffer: a rope, byte-offset positions, edit ops, persistence.
2//! No UI, no modes, no grammar — the thing everything else edits.
3
4mod io;
5pub use io::{SaveReceipt, SaveRequest};
6mod seed;
7pub use seed::BufferSeed;
8mod layout_cache;
9mod mutation;
10use crate::diagnostics::BufferTraceId;
11use crate::history::History;
12use crate::id;
13use crate::range::Range;
14pub use mutation::{
15    Change, ChangeOrigin, EditError, HistoryMove, PreparedReplacements, Replacement, SystemEdit,
16    UserEdit,
17};
18use ropey::Rope;
19
20/// Why a buffer refuses edits (0056 AR14): the typed owner `:explain`
21/// renders, recorded at the site that actually imposed the policy — never
22/// a generic hint. `None` alongside `readonly` is reserved for tests that
23/// poke the mutation guard directly.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum ReadonlyReason {
27    /// The filesystem reports the file not writable.
28    Filesystem,
29    /// `:set ro` or `:view`.
30    Command,
31    /// A remote snapshot without write authority (`:remote edit` grants it).
32    RemoteAuthority,
33    /// Container bytes have no local write path (0037 DC1b).
34    Container,
35    /// A git memory surface — content derived from history.
36    GitSurface,
37    /// Transient named output (help, `:!`, the undo browser, `:explain`).
38    Output,
39    /// A directory listing without an editable filename draft.
40    DirectoryListing,
41    /// A directory operation is applying or reloading.
42    DirectoryOperation,
43    /// A stale collection whose projection failed.
44    CollectionProjection,
45    /// The recovery checkpoint surface.
46    RecoveryCheckpoint,
47    /// Navigation landed outside the workspace root.
48    OutsideWorkspace,
49}
50
51/// A text buffer. Positions are UTF-8 byte offsets, everywhere (0001 §5.1).
52pub struct Buffer {
53    pub(crate) trace_identity: BufferTraceId,
54    rope: Rope,
55    /// Filesystem identity (0021 §3: Unix filenames aren't UTF-8 — a
56    /// String path makes the filesystem model a UI model). Display via
57    /// to_string_lossy at the edge only.
58    pub path: Option<std::path::PathBuf>,
59    pub dirty: bool,
60    /// Monotonic edit counter; async readers (git gutter) diff lazily.
61    epoch: u64,
62    /// Read-only views (git surfaces): motions/yank work, edits refuse.
63    pub readonly: bool,
64    /// The typed owner of the readonly policy (0056 AR14).
65    pub readonly_reason: Option<ReadonlyReason>,
66    /// Display name for virtual buffers (statusline shows "[scratch]"
67    /// otherwise): "git log", "commit 1a2b3c", …
68    pub name: Option<String>,
69    /// Undo history (helix-style revision tree). Readonly buffers never
70    /// record (their content is owned by jobs, not the user).
71    history: History,
72    changes: Vec<Change>,
73    /// Disk mtime at load/last save — overwrite protection for `:w`.
74    disk_stamp: Option<std::time::SystemTime>,
75    file_identity: Option<std::path::PathBuf>,
76    line_layouts: layout_cache::LineLayouts,
77}
78
79impl Buffer {
80    /// Impose readonly policy with its typed reason. Re-imposing while a
81    /// reason stands keeps the original owner — a later generic open must
82    /// not erase a more specific source.
83    pub fn set_readonly(&mut self, reason: ReadonlyReason) {
84        if !self.readonly {
85            self.readonly_reason = Some(reason);
86        }
87        self.readonly = true;
88    }
89
90    /// Explicit write authority (`:set noro`, a granted `:remote edit`, a
91    /// successful collection projection) clears the flag and its reason.
92    pub fn clear_readonly(&mut self) {
93        self.readonly = false;
94        self.readonly_reason = None;
95    }
96
97    pub fn text(&self) -> &Rope {
98        &self.rope
99    }
100    pub fn snapshot(&self) -> Rope {
101        self.rope.clone()
102    }
103
104    /// Diagnostic head excerpt: copies at most [`strop_trace::MAX_EXCERPT_BYTES`]
105    /// instead of materializing the whole buffer, and reports whether the
106    /// text was cut.
107    pub fn text_excerpt(&self) -> (String, bool) {
108        let rope = &self.rope;
109        if rope.len_bytes() <= strop_trace::MAX_EXCERPT_BYTES {
110            return (rope.to_string(), false);
111        }
112        let mut end = strop_trace::MAX_EXCERPT_BYTES;
113        while end > 0 && (rope.byte(end - 1) & 0xC0) == 0x80 {
114            end -= 1;
115        }
116        (
117            rope.get_byte_slice(..end)
118                .map_or_else(String::new, |head| head.to_string()),
119            true,
120        )
121    }
122    pub fn history(&self) -> &History {
123        &self.history
124    }
125    pub fn revision(&self) -> id::BufferRevision {
126        id::BufferRevision::new(self.epoch)
127    }
128    pub fn file_identity(&self) -> Option<&std::path::Path> {
129        self.file_identity.as_deref()
130    }
131
132    pub fn restore_history(
133        &mut self,
134        history: History,
135    ) -> Result<(), crate::history::HistoryError> {
136        history.validate_for(&self.rope)?;
137        self.adopt_history(history);
138        Ok(())
139    }
140
141    pub fn from_text(text: &str) -> Self {
142        Self::from_snapshot(Rope::from_str(text))
143    }
144
145    /// A cheap independent reader over immutable rope structure. No text copy,
146    /// disk identity, or history is inherited from the publishing document.
147    pub fn from_snapshot(rope: Rope) -> Self {
148        Self {
149            trace_identity: BufferTraceId::next(),
150            rope,
151            path: None,
152            dirty: false,
153            readonly_reason: None,
154            epoch: 0,
155            readonly: false,
156            name: None,
157            history: History::default(),
158            changes: Vec::new(),
159            disk_stamp: None,
160            file_identity: None,
161            line_layouts: layout_cache::LineLayouts::default(),
162        }
163    }
164
165    /// Open a file; a missing file is a new empty buffer with that path
166    /// (vim semantics — `:w` creates it). Real I/O errors still error.
167    /// A file whose permissions report not writable opens readonly with
168    /// that typed reason (0056 AR14) — `:set noro` / `:w!` stay explicit.
169    pub fn open(path: impl AsRef<std::path::Path>) -> std::io::Result<Self> {
170        let path = path.as_ref();
171        let (rope, disk_stamp, writable) = match std::fs::File::open(path) {
172            Ok(file) => {
173                let metadata = file.metadata()?;
174                let stamp = metadata.modified()?;
175                (
176                    Rope::from_reader(file)?,
177                    Some(stamp),
178                    !metadata.permissions().readonly(),
179                )
180            }
181            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (Rope::new(), None, true),
182            Err(e) => return Err(e),
183        };
184        let mut buffer = Self {
185            trace_identity: BufferTraceId::next(),
186            rope,
187            path: Some(path.to_path_buf()),
188            dirty: false,
189            epoch: 0,
190            readonly: false,
191            readonly_reason: None,
192            name: None,
193            history: History::default(),
194            changes: Vec::new(),
195            disk_stamp,
196            file_identity: Some(std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())),
197            line_layouts: layout_cache::LineLayouts::default(),
198        };
199        if !writable {
200            buffer.set_readonly(ReadonlyReason::Filesystem);
201        }
202        Ok(buffer)
203    }
204
205    /// Display CELL of an offset within its line (0017/R6): cursor placement
206    /// and overlays need terminal cells, not byte columns — wide chars and
207    /// tabs make the difference. Streams through the containing cluster only:
208    /// no whole-line String, no layout vector, no u16 saturation.
209    pub fn cell_col_with_tab(
210        &self,
211        offset: impl Into<id::ByteOffset>,
212        tab: usize,
213    ) -> id::DisplayColumn {
214        match self.column_from_layout(offset.into().get(), tab, false) {
215            Some(column) => column,
216            None => unreachable!("an unbounded layout projection always completes"),
217        }
218    }
219
220    pub fn len_bytes(&self) -> usize {
221        self.rope.len_bytes()
222    }
223    pub fn len_lines(&self) -> usize {
224        self.rope.len_lines()
225    }
226
227    /// Last *content* line index — a trailing newline's phantom empty
228    /// line doesn't count (vim's G lands on real text).
229    pub fn last_content_line(&self) -> usize {
230        let mut l = self.len_lines().saturating_sub(1);
231        if self.len_bytes() > 0 && self.byte(self.len_bytes() - 1) == b'\n' && l > 0 {
232            l -= 1;
233        }
234        l
235    }
236
237    /// Byte offset of the first char of `line` (0-indexed).
238    pub fn line_start(&self, line: impl Into<id::LineIndex>) -> usize {
239        self.rope
240            .line_to_byte(line.into().get().min(self.len_lines().saturating_sub(1)))
241    }
242
243    /// Byte offset one past the last content char (excludes LF or CRLF).
244    pub fn line_end(&self, line: impl Into<id::LineIndex>) -> usize {
245        let line = line.into().get();
246        let start = self.line_start(line);
247        let mut end = self.line_start((line + 1).min(self.len_lines().saturating_sub(1)));
248        if line + 1 >= self.len_lines() {
249            end = self.len_bytes();
250        }
251        // strip the trailing newline
252        if end > start && self.byte(end - 1) == b'\n' {
253            end -= 1;
254            if end > start && self.byte(end - 1) == b'\r' {
255                end -= 1;
256            }
257        }
258        end
259    }
260
261    pub fn line_of(&self, offset: impl Into<id::ByteOffset>) -> usize {
262        self.rope
263            .byte_to_line(offset.into().get().min(self.len_bytes()))
264    }
265
266    /// Column (in bytes) of `offset` within its line.
267    pub fn col_of(&self, offset: impl Into<id::ByteOffset>) -> usize {
268        let offset = offset.into();
269        offset.get() - self.line_start(self.line_of(offset))
270    }
271    /// Byte at a position. An empty rope reads as NUL: every classifier
272    /// treats NUL as a boundary, and the alternative (a panic) is how
273    /// the second review found this (0015). `byte_at` when absence
274    /// itself matters.
275    pub fn byte(&self, offset: impl Into<id::ByteOffset>) -> u8 {
276        if self.len_bytes() == 0 {
277            return 0;
278        }
279        self.rope
280            .byte(offset.into().get().min(self.len_bytes().saturating_sub(1)))
281    }
282
283    pub fn byte_at(&self, offset: impl Into<id::ByteOffset>) -> Option<u8> {
284        let off = offset.into().get();
285        if off < self.len_bytes() {
286            Some(self.rope.byte(off))
287        } else {
288            None
289        }
290    }
291
292    /// Is `offset` a UTF-8 char boundary? ropey's `try_byte_to_char`
293    /// maps a mid-char byte to its containing char without complaint —
294    /// only the byte↔char roundtrip actually detects boundaries. (The
295    /// pre-0.3.9 clamp trusted it and never clamped anything.)
296    pub fn is_boundary(&self, offset: impl Into<id::ByteOffset>) -> bool {
297        let off = offset.into().get();
298        if off == 0 || off == self.len_bytes() {
299            return true;
300        }
301        if off > self.len_bytes() {
302            return false;
303        }
304        match self.rope.try_byte_to_char(off) {
305            Ok(c) => self.rope.try_char_to_byte(c).is_ok_and(|b| b == off),
306            Err(_) => false,
307        }
308    }
309
310    /// Clamp a byte offset down to a char boundary (the grapheme policy
311    /// in 0001 §5.9 hardens this further when text goes wide).
312    pub fn clamp_boundary(&self, offset: impl Into<id::ByteOffset>) -> usize {
313        let mut offset = offset.into().get().min(self.len_bytes());
314        while offset > 0 && !self.is_boundary(offset) {
315            offset -= 1;
316        }
317        offset
318    }
319
320    /// Smallest char boundary >= offset. Byte arithmetic on a cursor
321    /// (`cursor + 1` in x/a/r/~) lands inside a multibyte char; deleting
322    /// or inserting there panics ropey. Round up, never down — a
323    /// deletion that rounds down eats the previous char's tail.
324    pub fn ceil_boundary(&self, offset: impl Into<id::ByteOffset>) -> usize {
325        let mut offset = offset.into().get().min(self.len_bytes());
326        while offset < self.len_bytes() && !self.is_boundary(offset) {
327            offset += 1;
328        }
329        offset
330    }
331
332    /// Slice as String — for register/paste paths, never for per-frame render.
333    /// Stale ranges clamp (fuzz-driven cascades hand these around).
334    pub fn slice_string(&self, range: Range) -> String {
335        let start = self.clamp_boundary(range.start);
336        let end = self.clamp_boundary(range.end);
337        self.rope.byte_slice(start..end.max(start)).to_string()
338    }
339
340    pub fn line_text(&self, line: impl Into<id::LineIndex>) -> String {
341        let line = line.into().get();
342        let start = self.line_start(line);
343        let end = self.line_end(line);
344        self.rope.byte_slice(start..end).to_string()
345    }
346}
347
348/// Pre-edit and post-edit geometry recorded at the instant text changes.
349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
350pub struct InputEdit {
351    pub start_byte: usize,
352    pub old_end_byte: usize,
353    pub new_end_byte: usize,
354    pub start_point: (usize, usize),
355    pub old_end_point: (usize, usize),
356    pub new_end_point: (usize, usize),
357}
358
359impl Buffer {
360    /// (line, col) of a byte offset, as tree-sitter Points.
361    pub fn point_of(&self, offset: usize) -> (usize, usize) {
362        let offset = offset.min(self.len_bytes());
363        (self.line_of(offset), self.col_of(offset))
364    }
365
366    /// The (line, col) extent of a text fragment.
367    fn point_extent(text: &str) -> (usize, usize) {
368        let lines = text.bytes().filter(|b| *b == b'\n').count();
369        let col = if lines == 0 {
370            text.len()
371        } else {
372            text.rsplit('\n').next().map(str::len).unwrap_or(0)
373        };
374        (lines, col)
375    }
376}
377
378#[cfg(test)]
379mod safety_tests {
380    use super::*;
381
382    #[test]
383    fn save_refuses_external_change_unless_forced() {
384        let dir = tempfile::tempdir().unwrap();
385        let f = dir.path().join("f.txt");
386        std::fs::write(&f, "original\n").unwrap();
387        let mut b = Buffer::open(f.to_str().unwrap()).unwrap();
388        b.edit().insert(id::ByteOffset::new(0), "mine ").unwrap();
389        // another process touches the file
390        std::fs::write(&f, "theirs\n").unwrap();
391        std::fs::File::options()
392            .write(true)
393            .open(&f)
394            .unwrap()
395            .set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(123))
396            .unwrap();
397        let err = b.prepare_save(None, false).unwrap().execute().unwrap_err();
398        assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied);
399        assert_eq!(std::fs::read_to_string(&f).unwrap(), "theirs\n");
400        let receipt = b.prepare_save(None, true).unwrap().execute().unwrap();
401        assert!(b.accept_save(receipt));
402        assert_eq!(std::fs::read_to_string(&f).unwrap(), "mine original\n");
403        assert!(!b.dirty);
404    }
405
406    #[test]
407    fn save_is_atomic_and_keeps_permissions() {
408        use std::os::unix::fs::PermissionsExt;
409        let dir = tempfile::tempdir().unwrap();
410        let f = dir.path().join("x.sh");
411        std::fs::write(&f, "#!/bin/sh\n").unwrap();
412        std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o750)).unwrap();
413        let mut b = Buffer::open(f.to_str().unwrap()).unwrap();
414        let end = b.len_bytes();
415        b.edit()
416            .insert(id::ByteOffset::new(end), "echo hi\n")
417            .unwrap();
418        let receipt = b.prepare_save(None, false).unwrap().execute().unwrap();
419        assert!(b.accept_save(receipt));
420        assert_eq!(std::fs::read_to_string(&f).unwrap(), "#!/bin/sh\necho hi\n");
421        let mode = std::fs::metadata(&f).unwrap().permissions().mode() & 0o777;
422        assert_eq!(mode, 0o750, "permissions survive the swap");
423        // no temp litter
424        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
425    }
426
427    #[test]
428    fn readonly_refuses_mutation_at_the_boundary() {
429        // 0014: the guard lives in Buffer, not in every caller's memory
430        let mut b = Buffer::from_text("abc\n");
431        b.readonly = true;
432        assert_eq!(b.edit().insert(0, "nope"), Err(EditError::ReadOnly));
433        assert_eq!(
434            b.edit().delete(Range::charwise(0, 2)),
435            Err(EditError::ReadOnly)
436        );
437        assert_eq!(b.rope.to_string(), "abc\n", "untouched");
438        // the owner path still works (job-generated surfaces)
439        b.system_edit().replace_all("gen\n").unwrap();
440        assert_eq!(b.rope.to_string(), "gen\n");
441    }
442    #[test]
443    fn non_utf8_filename_opens_and_roundtrips() {
444        // 0021 §3: the filesystem is not UTF-8 — a weird name must open,
445        // save, and keep its identity
446        use std::os::unix::ffi::OsStrExt;
447        let dir = tempfile::tempdir().unwrap();
448        let weird = dir
449            .path()
450            .join(std::ffi::OsStr::from_bytes(b"weird-\xff.rs"));
451        std::fs::write(&weird, "fn main() {}\n").unwrap();
452        let mut b = Buffer::open(&weird).unwrap();
453        assert_eq!(b.path.as_deref(), Some(weird.as_path()));
454        b.edit().insert(0, "// x\n").unwrap();
455        let receipt = b.prepare_save(None, false).unwrap().execute().unwrap();
456        assert!(b.accept_save(receipt));
457        assert_eq!(
458            std::fs::read_to_string(&weird).unwrap(),
459            "// x\nfn main() {}\n"
460        );
461    }
462}