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