Skip to main content

indigo_core/
buffer.rs

1use crate::{fs::Fs, syntax::Language, text::Text};
2use camino::Utf8Path;
3use ropey::{Rope, extra::esoterica::ropes_are_instances};
4use std::sync::Arc;
5
6slotmap::new_key_type! {
7    #[must_use]
8    pub struct BufferKey;
9}
10
11#[derive(Clone, Default)]
12pub enum BufferKind {
13    /// In-memory scratch buffer.
14    #[default]
15    Scratch,
16    /// Buffer mapping to a file on disk.
17    File {
18        /// Absolute path. Symlinks and `..` components aren't resolved, so the same file can appear
19        /// under different paths.
20        path: Arc<Utf8Path>,
21        /// Last known state of file on disk, used for modification tracking.
22        on_disk: Rope,
23    },
24}
25
26#[derive(Clone, Default)]
27pub struct Buffer {
28    kind: BufferKind,
29    pub text: Text,
30}
31
32impl Buffer {
33    #[must_use]
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    pub fn open(fs: &impl Fs, path: impl AsRef<Utf8Path>) -> anyhow::Result<Self> {
39        let path = path.as_ref();
40        let exists = fs.exists(path)?;
41        let rope = if exists {
42            let bytes = fs.read(path)?;
43            let string = str::from_utf8(&bytes)?;
44            Rope::from(string)
45        } else {
46            Rope::new()
47        };
48        let mut buffer = Self::from(rope);
49        // Using the normalized rope (with trailing newline appended if missing) instead of the
50        // original so it doesn't appear already modified.
51        buffer.kind = BufferKind::File {
52            path: Arc::from(path),
53            on_disk: buffer.text.rope().clone(),
54        };
55        if let Ok(language) = Language::try_from(path) {
56            buffer.text.set_language(language);
57        }
58        Ok(buffer)
59    }
60
61    pub fn save(&mut self, fs: &impl Fs) -> anyhow::Result<()> {
62        if let BufferKind::File { path, on_disk } = &mut self.kind {
63            let mut bytes = Vec::with_capacity(self.text.len());
64            self.text.write_to(&mut bytes)?;
65            fs.write(path, &bytes)?;
66            *on_disk = self.text.rope().clone();
67        }
68        Ok(())
69    }
70
71    pub fn save_as(&mut self, fs: &impl Fs, path: impl AsRef<Utf8Path>) -> anyhow::Result<()> {
72        let path = path.as_ref();
73        let mut bytes = Vec::with_capacity(self.text.len());
74        self.text.write_to(&mut bytes)?;
75        fs.write(path, &bytes)?;
76        self.kind = BufferKind::File {
77            path: Arc::from(path),
78            on_disk: self.text.rope().clone(),
79        };
80        Ok(())
81    }
82
83    #[must_use]
84    pub fn kind(&self) -> &BufferKind {
85        &self.kind
86    }
87
88    #[must_use]
89    pub fn path(&self) -> Option<&Utf8Path> {
90        if let BufferKind::File { path, .. } = &self.kind {
91            Some(path)
92        } else {
93            None
94        }
95    }
96
97    // Unlike other editors, a buffer is considered modified only if its content diverges from
98    // what's on disk. Making further changes to restore the content is treated the same as undoing
99    // the changes.
100    #[must_use]
101    pub fn is_modified(&self) -> Option<bool> {
102        let BufferKind::File { on_disk, .. } = &self.kind else {
103            return None;
104        };
105        let rope = self.text.rope();
106        if ropes_are_instances(rope, on_disk) {
107            return Some(false);
108        }
109        Some(rope != on_disk)
110    }
111
112    pub fn assert_invariants(&self) -> anyhow::Result<()> {
113        if let Some(path) = self.path() {
114            anyhow::ensure!(path.is_absolute(), "Path is not absolute: `{path}`");
115        }
116        self.text.assert_invariants()
117    }
118}
119
120impl From<Rope> for Buffer {
121    fn from(rope: Rope) -> Self {
122        Self::from(Text::from(rope))
123    }
124}
125
126impl From<Text> for Buffer {
127    fn from(text: Text) -> Self {
128        Self {
129            text,
130            ..Self::default()
131        }
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use crate::fs::TestFs;
139
140    #[test]
141    fn fs() -> anyhow::Result<()> {
142        let fs = TestFs::default();
143        fs.write("/main.rs".into(), b"fn main() {}")?;
144        let mut buffer = Buffer::open(&fs, "/main.rs")?;
145        buffer.assert_invariants()?;
146        // Text normalization appends the missing trailing newline on open.
147        assert_eq!(&buffer.text.to_string(), "fn main() {}\n");
148        assert_eq!(buffer.is_modified(), Some(false));
149        let BufferKind::File { path, .. } = &mut buffer.kind else {
150            unreachable!();
151        };
152        *path = Arc::from(Utf8Path::new("/main2.rs"));
153        buffer.save(&fs)?;
154        assert_eq!(fs.read("/main2.rs".into())?, b"fn main() {}\n");
155        Ok(())
156    }
157}