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