Skip to main content

rustaco_core/
model.rs

1//! The shared text model: buffer, version, undo history and the change log.
2//!
3//! Several editors can show one model, each with its own [`crate::Cursors`].
4//! Consumers that follow the text (other editors' cursors, syntax trees, LSP
5//! clients) read the change log by version instead of being notified, so the
6//! model holds no references to them.
7
8use std::collections::VecDeque;
9
10use ropey::Rope;
11
12use crate::change::{ChangeSet, Edit, EditEvent};
13use crate::decorations::Decorations;
14use crate::history::History;
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
17pub enum LineEnding {
18    #[default]
19    Lf,
20    CrLf,
21    Cr,
22}
23
24impl LineEnding {
25    pub fn as_str(self) -> &'static str {
26        match self {
27            LineEnding::Lf => "\n",
28            LineEnding::CrLf => "\r\n",
29            LineEnding::Cr => "\r",
30        }
31    }
32
33    /// The first line terminator in the text decides; text without one gets `Lf`.
34    pub fn detect(rope: &Rope) -> Self {
35        let mut chars = rope.chars();
36        while let Some(c) = chars.next() {
37            match c {
38                '\n' => return LineEnding::Lf,
39                '\r' => return if chars.next() == Some('\n') { LineEnding::CrLf } else { LineEnding::Cr },
40                _ => {}
41            }
42        }
43        LineEnding::Lf
44    }
45}
46
47/// Indentation settings. More fields may come: build one from `Options::default()`.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49#[non_exhaustive]
50pub struct Options {
51    pub tab_size: usize,
52    pub insert_spaces: bool,
53}
54
55impl Default for Options {
56    fn default() -> Self {
57        Self { tab_size: 4, insert_spaces: true }
58    }
59}
60
61/// Language-specific editing data, set by the frontend from its language catalog: comment
62/// tokens for comment toggling, bracket and quote pairs for auto-closing. More fields may
63/// come: start from `LanguageEditing::default()` and set the fields.
64#[derive(Clone, Debug, Default, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct LanguageEditing {
67    pub line_comment: Option<String>,
68    pub block_comment: Option<(String, String)>,
69    pub auto_closing: Vec<(String, String)>,
70    /// Bracket pairs: Enter after an opening bracket indents, and between a pair it opens an
71    /// empty line with the closing bracket below.
72    pub brackets: Vec<(String, String)>,
73    /// Line endings after which Enter indents one level more (`:` in Python).
74    pub indent_after: Vec<String>,
75}
76
77/// Change sets kept in the log. A consumer further behind than this must resync from the full text.
78const LOG_CAPACITY: usize = 1024;
79
80/// Returned when a consumer asks for changes older than the log keeps.
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub struct Stale;
83
84#[derive(Clone, Debug)]
85struct LogEntry {
86    changes: ChangeSet,
87    events: Vec<EditEvent>,
88}
89
90#[derive(Clone, Debug)]
91pub struct TextModel {
92    pub(crate) rope: Rope,
93    pub(crate) history: History,
94    pub(crate) line_ending: LineEnding,
95    pub options: Options,
96    pub editing: LanguageEditing,
97    /// Ranges that move with edits (search matches, diagnostics, diff hunks).
98    pub decorations: Decorations,
99    version: u64,
100    log: VecDeque<LogEntry>,
101    /// Version of the text before the oldest log entry.
102    log_base: u64,
103}
104
105impl TextModel {
106    pub fn new(text: &str) -> Self {
107        let rope = Rope::from_str(text);
108        Self {
109            line_ending: LineEnding::detect(&rope),
110            rope,
111            history: History::default(),
112            options: Options::default(),
113            editing: LanguageEditing::default(),
114            decorations: Decorations::default(),
115            version: 0,
116            log: VecDeque::new(),
117            log_base: 0,
118        }
119    }
120
121    pub fn rope(&self) -> &Rope {
122        &self.rope
123    }
124
125    pub fn text(&self) -> String {
126        self.rope.to_string()
127    }
128
129    pub fn len_chars(&self) -> usize {
130        self.rope.len_chars()
131    }
132
133    /// Increases by one with every applied change set, including undo and redo.
134    pub fn version(&self) -> u64 {
135        self.version
136    }
137
138    pub fn line_ending(&self) -> LineEnding {
139        self.line_ending
140    }
141
142    pub fn can_undo(&self) -> bool {
143        self.history.can_undo()
144    }
145
146    pub fn can_redo(&self) -> bool {
147        self.history.can_redo()
148    }
149
150    /// Ends the current undo group explicitly.
151    pub fn checkpoint(&mut self) {
152        self.history.break_group();
153    }
154
155    /// Replaces the whole text and clears the undo history (like Monaco's `setValue`).
156    /// The replacement goes through the log, so cursors and other consumers follow it.
157    pub fn set_text(&mut self, text: &str) {
158        let all = ChangeSet::new(vec![Edit::new(0, self.rope.len_chars(), text)]);
159        self.apply(&all);
160        self.line_ending = LineEnding::detect(&self.rope);
161        self.history = History::default();
162    }
163
164    /// Change sets applied after `version`, oldest first.
165    pub fn changes_since(&self, version: u64) -> Result<impl Iterator<Item = &ChangeSet>, Stale> {
166        Ok(self.log_since(version)?.map(|e| &e.changes))
167    }
168
169    /// Edit events applied after `version`, in application order.
170    pub fn events_since(&self, version: u64) -> Result<impl Iterator<Item = &EditEvent>, Stale> {
171        Ok(self.log_since(version)?.flat_map(|e| e.events.iter()))
172    }
173
174    fn log_since(&self, version: u64) -> Result<std::collections::vec_deque::Iter<'_, LogEntry>, Stale> {
175        if version < self.log_base || version > self.version {
176            return Err(Stale);
177        }
178        Ok(self.log.range((version - self.log_base) as usize..))
179    }
180
181    /// The only place the rope changes. Returns the inverse change set.
182    ///
183    /// Undo inverses can land inside a CRLF pair that a deletion created, so every change
184    /// set is snapped here, not only new edits.
185    pub(crate) fn apply(&mut self, changes: &ChangeSet) -> ChangeSet {
186        if changes.needs_crlf_snap(&self.rope) {
187            let snapped = changes.clone().snap_crlf(&self.rope);
188            return self.apply(&snapped);
189        }
190        let events = changes.describe(&self.rope);
191        let inverse = changes.apply(&mut self.rope);
192        self.decorations.apply(changes);
193        self.version += 1;
194        self.log.push_back(LogEntry { changes: changes.clone(), events });
195        if self.log.len() > LOG_CAPACITY {
196            self.log.pop_front();
197            self.log_base += 1;
198        }
199        inverse
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn log_serves_consumers_by_version() {
209        let mut m = TextModel::new("abc");
210        m.apply(&ChangeSet::new(vec![Edit::insert(0, "x")]));
211        m.apply(&ChangeSet::new(vec![Edit::insert(4, "y")]));
212        assert_eq!(m.text(), "xabcy");
213        assert_eq!(m.changes_since(0).unwrap().count(), 2);
214        assert_eq!(m.events_since(1).unwrap().map(|e| e.text.as_str()).collect::<Vec<_>>(), ["y"]);
215        assert_eq!(m.changes_since(2).unwrap().count(), 0);
216        assert!(m.changes_since(3).is_err());
217    }
218
219    #[test]
220    fn log_drops_old_entries() {
221        let mut m = TextModel::new("");
222        for _ in 0..LOG_CAPACITY + 5 {
223            m.apply(&ChangeSet::new(vec![Edit::insert(0, "a")]));
224        }
225        assert!(m.changes_since(0).is_err());
226        assert_eq!(m.changes_since(5).unwrap().count(), LOG_CAPACITY);
227    }
228}