1pub mod history;
5pub mod id;
6pub mod selection;
7
8use history::{Edit, EditKind, History};
9use ropey::Rope;
10
11pub struct Buffer {
13 pub rope: Rope,
14 pub path: Option<String>,
15 pub dirty: bool,
16 pub epoch: u64,
18 pub readonly: bool,
20 pub name: Option<String>,
23 pub history: History,
26 pub replaying: bool,
28 disk_stamp: Option<std::time::SystemTime>,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum MotionShape {
37 Characterwise { inclusive: bool },
38 Linewise,
39}
40
41#[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn replace_all(&mut self, text: &str) {
299 if self.readonly {
300 return;
301 }
302 self.replace_all_system(text);
303 }
304
305 pub fn replace_all_system(&mut self, text: &str) {
309 self.rope = Rope::from_str(text);
310 self.epoch += 1;
311 }
312
313 pub fn delete(&mut self, range: Range) -> String {
317 if self.readonly && !self.replaying {
318 return String::new();
319 }
320 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 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 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(); 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 assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
419 }
420
421 #[test]
422 fn readonly_refuses_mutation_at_the_boundary() {
423 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 b.replace_all_system("gen\n");
432 assert_eq!(b.rope.to_string(), "gen\n");
433 }
434}