1mod 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#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum ReadonlyReason {
27 Filesystem,
29 Command,
31 RemoteAuthority,
33 Container,
35 GitSurface,
37 Output,
39 DirectoryListing,
41 DirectoryOperation,
43 CollectionProjection,
45 RecoveryCheckpoint,
47 OutsideWorkspace,
49}
50
51pub struct Buffer {
53 pub(crate) trace_identity: BufferTraceId,
54 rope: Rope,
55 pub path: Option<std::path::PathBuf>,
59 pub dirty: bool,
60 epoch: u64,
62 pub readonly: bool,
64 pub readonly_reason: Option<ReadonlyReason>,
66 pub name: Option<String>,
69 history: History,
72 changes: Vec<Change>,
73 disk_stamp: Option<std::time::SystemTime>,
75 file_identity: Option<std::path::PathBuf>,
76 line_layouts: layout_cache::LineLayouts,
77}
78
79impl Buffer {
80 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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#[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 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 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 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 assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
425 }
426
427 #[test]
428 fn readonly_refuses_mutation_at_the_boundary() {
429 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 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 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}