Skip to main content

strop_core/
lib.rs

1//! strop-core: the buffer. A rope, byte-offset positions, edit ops.
2//! No UI, no modes, no grammar — the thing everything else edits.
3
4pub mod history;
5pub mod id;
6pub mod layout;
7pub mod selection;
8
9use history::{Edit, EditKind, History};
10use ropey::Rope;
11
12/// A text buffer. Positions are UTF-8 byte offsets, everywhere (0001 §5.1).
13pub struct Buffer {
14    pub rope: Rope,
15    pub path: Option<String>,
16    pub dirty: bool,
17    /// Monotonic edit counter; async readers (git gutter) diff lazily.
18    pub epoch: u64,
19    /// Read-only views (git surfaces): motions/yank work, edits refuse.
20    pub readonly: bool,
21    /// Display name for virtual buffers (statusline shows "[scratch]"
22    /// otherwise): "git log", "commit 1a2b3c", …
23    pub name: Option<String>,
24    /// Undo history (helix-style revision tree). Readonly buffers never
25    /// record (their content is owned by jobs, not the user).
26    pub history: History,
27    /// Suppresses recording while applying undo/redo ops.
28    pub replaying: bool,
29    /// Disk mtime at load/last save — overwrite protection for `:w`.
30    disk_stamp: Option<std::time::SystemTime>,
31}
32
33/// How vim thinks about a range (0014): charwise ops carry the motion's
34/// inclusivity (dfx vs dtx differ by it); linewise is line-shaped.
35/// Blockwise lands with visual block — the enum is the extension point.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum MotionShape {
38    Characterwise { inclusive: bool },
39    Linewise,
40}
41
42/// A half-open byte range `[start, end)` plus its vim shape. Fields are
43/// ByteOffset — the storage coordinate is typed end to end (0014).
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct Range {
46    pub start: usize,
47    pub end: usize,
48    pub shape: MotionShape,
49}
50
51impl Range {
52    pub fn charwise(start: impl Into<id::ByteOffset>, end: impl Into<id::ByteOffset>) -> Self {
53        let (start, end) = (start.into().get(), end.into().get());
54        debug_assert!(start <= end);
55        Self {
56            start,
57            end,
58            shape: MotionShape::Characterwise { inclusive: false },
59        }
60    }
61    pub fn linewise(start: impl Into<id::ByteOffset>, end: impl Into<id::ByteOffset>) -> Self {
62        let (start, end) = (start.into().get(), end.into().get());
63        debug_assert!(start <= end);
64        Self {
65            start,
66            end,
67            shape: MotionShape::Linewise,
68        }
69    }
70    pub fn is_linewise(&self) -> bool {
71        matches!(self.shape, MotionShape::Linewise)
72    }
73    /// The resolver's inclusive flag folds into the shape (0014).
74    pub fn with_inclusive(mut self, inclusive: bool) -> Self {
75        if let MotionShape::Characterwise { inclusive: i } = &mut self.shape {
76            *i = inclusive;
77        }
78        self
79    }
80    pub fn inclusive(&self) -> bool {
81        matches!(self.shape, MotionShape::Characterwise { inclusive: true })
82    }
83    /// Length in bytes.
84    pub fn len(&self) -> usize {
85        self.end - self.start
86    }
87    pub fn is_empty(&self) -> bool {
88        self.start == self.end
89    }
90}
91
92impl Buffer {
93    pub fn from_text(text: &str) -> Self {
94        Self {
95            rope: Rope::from_str(text),
96            path: None,
97            dirty: false,
98            epoch: 0,
99            readonly: false,
100            name: None,
101            history: History::default(),
102            replaying: false,
103            disk_stamp: None,
104        }
105    }
106
107    /// Open a file; a missing file is a new empty buffer with that path
108    /// (vim semantics — `:w` creates it). Real I/O errors still error.
109    pub fn open(path: &str) -> std::io::Result<Self> {
110        let text = match std::fs::read_to_string(path) {
111            Ok(t) => t,
112            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
113            Err(e) => return Err(e),
114        };
115        let disk_stamp = std::fs::metadata(path).and_then(|m| m.modified()).ok();
116        Ok(Self {
117            rope: Rope::from_str(&text),
118            path: Some(path.to_string()),
119            dirty: false,
120            epoch: 0,
121            readonly: false,
122            name: None,
123            history: History::default(),
124            replaying: false,
125            disk_stamp,
126        })
127    }
128
129    /// `:w` — atomic (temp + rename in the same dir), refuses to
130    /// overwrite a file another process touched since we loaded it.
131    /// `force` is `:w!`.
132    pub fn save(&mut self, force: bool) -> std::io::Result<()> {
133        let Some(path) = self.path.clone() else {
134            // a pathless buffer has nothing to persist to — "written"
135            // would be a lie (0015)
136            return Err(std::io::Error::new(
137                std::io::ErrorKind::NotFound,
138                "no file name — :w {path} to name it",
139            ));
140        };
141        let current = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
142        if !force && current.is_some() && current != self.disk_stamp {
143            return Err(std::io::Error::new(
144                std::io::ErrorKind::PermissionDenied,
145                "file changed on disk — :w! to force",
146            ));
147        }
148        let target = std::path::Path::new(&path);
149        let tmp = target.with_file_name(format!(
150            ".strop-tmp-{}-{}",
151            std::process::id(),
152            target.file_name().and_then(|n| n.to_str()).unwrap_or("x")
153        ));
154        std::fs::write(&tmp, self.rope.to_string())?;
155        if let Ok(meta) = std::fs::metadata(target) {
156            // keep the file's permissions across the atomic swap
157            let _ = std::fs::set_permissions(&tmp, meta.permissions());
158        }
159        std::fs::rename(&tmp, target)?;
160        self.disk_stamp = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
161        self.dirty = false;
162        Ok(())
163    }
164
165    /// `:w {path}` — vim's write-to: persist under a new name and adopt
166    /// it (the buffer is now that file).
167    pub fn save_as(&mut self, path: &str) -> std::io::Result<()> {
168        self.path = Some(path.to_string());
169        self.disk_stamp = None; // fresh target: no overwrite baseline
170        self.save(true)
171    }
172    /// Display CELL of an offset within its line (0017): cursor
173    /// placement and overlays need terminal cells, not byte cols —
174    /// wide chars and tabs make the difference. The LineLayout is the
175    /// single translation seam.
176    pub fn cell_col_of(&self, offset: impl Into<id::ByteOffset>) -> u16 {
177        let offset = offset.into().get();
178        if self.len_bytes() == 0 {
179            return 0;
180        }
181        let line = self.line_of(offset);
182        let (s, e) = (self.line_start(line), self.line_end(line));
183        let text = self.rope.byte_slice(s..e).to_string();
184        let col = offset.saturating_sub(s);
185        let layout = layout::LineLayout::build(text.trim_end_matches('\n'), 8);
186        layout.cell_at_byte(col.min(layout.len_bytes))
187    }
188
189    pub fn len_bytes(&self) -> usize {
190        self.rope.len_bytes()
191    }
192    pub fn len_lines(&self) -> usize {
193        self.rope.len_lines()
194    }
195
196    /// Last *content* line index — a trailing newline's phantom empty
197    /// line doesn't count (vim's G lands on real text).
198    pub fn last_content_line(&self) -> usize {
199        let mut l = self.len_lines().saturating_sub(1);
200        if self.len_bytes() > 0 && self.byte(self.len_bytes() - 1) == b'\n' && l > 0 {
201            l -= 1;
202        }
203        l
204    }
205
206    /// Byte offset of the first char of `line` (0-indexed).
207    pub fn line_start(&self, line: impl Into<id::LineIndex>) -> usize {
208        self.rope
209            .line_to_byte(line.into().get().min(self.len_lines().saturating_sub(1)))
210    }
211
212    /// Byte offset one past the last content char of `line` (excludes `\n`).
213    pub fn line_end(&self, line: impl Into<id::LineIndex>) -> usize {
214        let line = line.into().get();
215        let start = self.line_start(line);
216        let mut end = self.line_start((line + 1).min(self.len_lines().saturating_sub(1)));
217        if line + 1 >= self.len_lines() {
218            end = self.len_bytes();
219        }
220        // strip the trailing newline
221        if end > start && self.byte(end - 1) == b'\n' {
222            end -= 1;
223        }
224        end
225    }
226
227    pub fn line_of(&self, offset: impl Into<id::ByteOffset>) -> usize {
228        self.rope
229            .byte_to_line(offset.into().get().min(self.len_bytes()))
230    }
231
232    /// Column (in bytes) of `offset` within its line.
233    pub fn col_of(&self, offset: impl Into<id::ByteOffset>) -> usize {
234        let offset = offset.into();
235        offset.get() - self.line_start(self.line_of(offset))
236    }
237    /// Byte at a position. An empty rope reads as NUL: every classifier
238    /// treats NUL as a boundary, and the alternative (a panic) is how
239    /// the second review found this (0015). `byte_at` when absence
240    /// itself matters.
241    pub fn byte(&self, offset: impl Into<id::ByteOffset>) -> u8 {
242        if self.len_bytes() == 0 {
243            return 0;
244        }
245        self.rope
246            .byte(offset.into().get().min(self.len_bytes().saturating_sub(1)))
247    }
248
249    pub fn byte_at(&self, offset: impl Into<id::ByteOffset>) -> Option<u8> {
250        let off = offset.into().get();
251        if off < self.len_bytes() {
252            Some(self.rope.byte(off))
253        } else {
254            None
255        }
256    }
257
258    /// Is `offset` a UTF-8 char boundary? ropey's `try_byte_to_char`
259    /// maps a mid-char byte to its containing char without complaint —
260    /// only the byte↔char roundtrip actually detects boundaries. (The
261    /// pre-0.3.9 clamp trusted it and never clamped anything.)
262    pub fn is_boundary(&self, offset: impl Into<id::ByteOffset>) -> bool {
263        let off = offset.into().get();
264        if off == 0 || off == self.len_bytes() {
265            return true;
266        }
267        if off > self.len_bytes() {
268            return false;
269        }
270        match self.rope.try_byte_to_char(off) {
271            Ok(c) => self.rope.try_char_to_byte(c).is_ok_and(|b| b == off),
272            Err(_) => false,
273        }
274    }
275
276    /// Clamp a byte offset down to a char boundary (the grapheme policy
277    /// in 0001 §5.9 hardens this further when text goes wide).
278    pub fn clamp_boundary(&self, offset: impl Into<id::ByteOffset>) -> usize {
279        let mut offset = offset.into().get().min(self.len_bytes());
280        while offset > 0 && !self.is_boundary(offset) {
281            offset -= 1;
282        }
283        offset
284    }
285
286    /// Smallest char boundary >= offset. Byte arithmetic on a cursor
287    /// (`cursor + 1` in x/a/r/~) lands inside a multibyte char; deleting
288    /// or inserting there panics ropey. Round up, never down — a
289    /// deletion that rounds down eats the previous char's tail.
290    pub fn ceil_boundary(&self, offset: impl Into<id::ByteOffset>) -> usize {
291        let mut offset = offset.into().get().min(self.len_bytes());
292        while offset < self.len_bytes() && !self.is_boundary(offset) {
293            offset += 1;
294        }
295        offset
296    }
297
298    /// Slice as String — for register/paste paths, never for per-frame render.
299    /// Stale ranges clamp (fuzz-driven cascades hand these around).
300    pub fn slice_string(&self, range: Range) -> String {
301        let start = range.start.min(self.len_bytes());
302        let end = range.end.min(self.len_bytes());
303        self.rope.byte_slice(start..end.max(start)).to_string()
304    }
305
306    /// Apply history edits (undo/redo replay — never recorded).
307    pub fn apply_history(&mut self, ops: Vec<Edit>) {
308        self.replaying = true;
309        for op in ops {
310            match op.kind {
311                EditKind::Insert => {
312                    let at = self.clamp_boundary(op.at.min(self.len_bytes()));
313                    self.rope.insert(self.rope.byte_to_char(at), &op.text);
314                }
315                EditKind::Delete => {
316                    // both bounds must land on char boundaries — a stale
317                    // replay against drifted text panics ropey otherwise
318                    let end = self.clamp_boundary((op.at + op.text.len()).min(self.len_bytes()));
319                    let start = self.clamp_boundary(op.at.min(end));
320                    if start < end {
321                        self.rope
322                            .remove(self.rope.byte_to_char(start)..self.rope.byte_to_char(end));
323                    }
324                }
325            }
326        }
327        self.replaying = false;
328        self.dirty = true;
329        self.epoch += 1;
330    }
331
332    /// Replace the whole contents (user-facing path). Refuses on
333    /// readonly buffers — the owning subsystem uses
334    /// `replace_all_system`.
335    pub fn replace_all(&mut self, text: &str) {
336        if self.readonly {
337            return;
338        }
339        self.replace_all_system(text);
340    }
341
342    /// The privileged replace for generated surfaces: their content is
343    /// owned by jobs (git/LSP/shell), refreshed under the user's feet —
344    /// the readonly guard is about *user* edits, not the owner.
345    pub fn replace_all_system(&mut self, text: &str) {
346        self.rope = Rope::from_str(text);
347        self.epoch += 1;
348    }
349
350    /// Returns the deleted text (register payoff). Refuses on readonly
351    /// buffers: the input layer checks first, but the mutation boundary
352    /// enforces — no caller-remembered guard (0014).
353    pub fn delete(&mut self, range: Range) -> String {
354        if self.readonly && !self.replaying {
355            return String::new();
356        }
357        // stale ranges (fuzz-driven cascades, replay drift) clamp, not panic
358        let start = self.clamp_boundary(range.start.min(self.len_bytes()));
359        let end = self.clamp_boundary(range.end.min(self.len_bytes()));
360        if start >= end {
361            return String::new();
362        }
363        let text = self.rope.byte_slice(start..end).to_string();
364        // ropey mutates by CHAR index; our offsets are bytes
365        let cstart = self.rope.byte_to_char(start);
366        let cend = self.rope.byte_to_char(end);
367        self.rope.remove(cstart..cend);
368        self.dirty = true;
369        self.epoch += 1;
370        if !self.replaying && !self.readonly {
371            self.history.record(
372                Edit {
373                    at: range.start,
374                    text: text.clone(),
375                    kind: EditKind::Insert,
376                },
377                Edit {
378                    at: range.start,
379                    text: text.clone(),
380                    kind: EditKind::Delete,
381                },
382            );
383        }
384        text
385    }
386
387    pub fn insert(&mut self, at: impl Into<id::ByteOffset>, text: &str) {
388        if self.readonly && !self.replaying {
389            return;
390        }
391        let at = self.clamp_boundary(at);
392        self.rope.insert(self.rope.byte_to_char(at), text);
393        self.dirty = true;
394        self.epoch += 1;
395        if !self.replaying && !self.readonly {
396            self.history.record(
397                Edit {
398                    at,
399                    text: text.into(),
400                    kind: EditKind::Delete,
401                },
402                Edit {
403                    at,
404                    text: text.into(),
405                    kind: EditKind::Insert,
406                },
407            );
408        }
409    }
410
411    pub fn line_text(&self, line: impl Into<id::LineIndex>) -> String {
412        let line = line.into().get();
413        let start = self.line_start(line);
414        let end = self.line_end(line);
415        self.rope.byte_slice(start..end).to_string()
416    }
417}
418
419#[cfg(test)]
420mod safety_tests {
421    use super::*;
422
423    #[test]
424    fn save_refuses_external_change_unless_forced() {
425        let dir = tempfile::tempdir().unwrap();
426        let f = dir.path().join("f.txt");
427        std::fs::write(&f, "original\n").unwrap();
428        let mut b = Buffer::open(f.to_str().unwrap()).unwrap();
429        b.insert(id::ByteOffset::new(0), "mine ");
430        // another process touches the file
431        std::thread::sleep(std::time::Duration::from_millis(5));
432        std::fs::write(&f, "theirs\n").unwrap();
433        let err = b.save(false).unwrap_err();
434        assert!(err.to_string().contains("changed on disk"));
435        assert_eq!(std::fs::read_to_string(&f).unwrap(), "theirs\n");
436        b.save(true).unwrap(); // :w!
437        assert_eq!(std::fs::read_to_string(&f).unwrap(), "mine original\n");
438        assert!(!b.dirty);
439    }
440
441    #[test]
442    fn save_is_atomic_and_keeps_permissions() {
443        use std::os::unix::fs::PermissionsExt;
444        let dir = tempfile::tempdir().unwrap();
445        let f = dir.path().join("x.sh");
446        std::fs::write(&f, "#!/bin/sh\n").unwrap();
447        std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o750)).unwrap();
448        let mut b = Buffer::open(f.to_str().unwrap()).unwrap();
449        b.insert(id::ByteOffset::new(b.len_bytes()), "echo hi\n");
450        b.save(false).unwrap();
451        assert_eq!(std::fs::read_to_string(&f).unwrap(), "#!/bin/sh\necho hi\n");
452        let mode = std::fs::metadata(&f).unwrap().permissions().mode() & 0o777;
453        assert_eq!(mode, 0o750, "permissions survive the swap");
454        // no temp litter
455        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
456    }
457
458    #[test]
459    fn readonly_refuses_mutation_at_the_boundary() {
460        // 0014: the guard lives in Buffer, not in every caller's memory
461        let mut b = Buffer::from_text("abc\n");
462        b.readonly = true;
463        b.insert(id::ByteOffset::new(0), "nope");
464        let gone = b.delete(Range::charwise(0, 2));
465        assert_eq!(gone, "");
466        assert_eq!(b.rope.to_string(), "abc\n", "untouched");
467        // the owner path still works (job-generated surfaces)
468        b.replace_all_system("gen\n");
469        assert_eq!(b.rope.to_string(), "gen\n");
470    }
471}