1pub mod history;
5pub mod id;
6pub mod layout;
7pub mod selection;
8
9use history::{Edit, EditKind, History};
10use ropey::Rope;
11
12pub struct Buffer {
14 pub rope: Rope,
15 pub path: Option<String>,
16 pub dirty: bool,
17 pub epoch: u64,
19 pub readonly: bool,
21 pub name: Option<String>,
24 pub history: History,
27 pub replaying: bool,
29 disk_stamp: Option<std::time::SystemTime>,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum MotionShape {
38 Characterwise { inclusive: bool },
39 Linewise,
40}
41
42#[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 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 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 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 pub fn save(&mut self, force: bool) -> std::io::Result<()> {
133 let Some(path) = self.path.clone() else {
134 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 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 pub fn save_as(&mut self, path: &str) -> std::io::Result<()> {
168 self.path = Some(path.to_string());
169 self.disk_stamp = None; self.save(true)
171 }
172 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn replace_all(&mut self, text: &str) {
336 if self.readonly {
337 return;
338 }
339 self.replace_all_system(text);
340 }
341
342 pub fn replace_all_system(&mut self, text: &str) {
346 self.rope = Rope::from_str(text);
347 self.epoch += 1;
348 }
349
350 pub fn delete(&mut self, range: Range) -> String {
354 if self.readonly && !self.replaying {
355 return String::new();
356 }
357 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 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 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(); 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 assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
456 }
457
458 #[test]
459 fn readonly_refuses_mutation_at_the_boundary() {
460 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 b.replace_all_system("gen\n");
469 assert_eq!(b.rope.to_string(), "gen\n");
470 }
471}