Skip to main content

rustaco_core/
document.rs

1//! Single-editor convenience: one [`TextModel`] with one set of [`Cursors`].
2
3use crate::change::{Edit, EditEvent};
4use crate::editor::{Cursors, Editor, EditorId};
5use crate::model::{LineEnding, Options, TextModel};
6use crate::selection::Selections;
7use ropey::Rope;
8
9/// A model and the cursors of its only editor. Editors sharing a model use
10/// [`TextModel`], [`Cursors`] and [`Editor`] directly.
11#[derive(Clone, Debug)]
12pub struct Document {
13    model: TextModel,
14    cursors: Cursors,
15    events_seen: u64,
16}
17
18macro_rules! delegate {
19    ($($(#[$doc:meta])* $name:ident($($arg:ident: $ty:ty),*) $(-> $ret:ty)?;)*) => {
20        $($(#[$doc])* pub fn $name(&mut self, $($arg: $ty),*) $(-> $ret)? {
21            self.editor().$name($($arg),*)
22        })*
23    };
24}
25
26impl Document {
27    pub fn new(text: &str) -> Self {
28        let model = TextModel::new(text);
29        let cursors = Cursors::new(EditorId::default(), &model);
30        Self { model, cursors, events_seen: 0 }
31    }
32
33    pub fn model(&self) -> &TextModel {
34        &self.model
35    }
36
37    pub fn editor(&mut self) -> Editor<'_> {
38        Editor::new(&mut self.model, &mut self.cursors)
39    }
40
41    pub fn rope(&self) -> &Rope {
42        self.model.rope()
43    }
44
45    pub fn text(&self) -> String {
46        self.model.text()
47    }
48
49    pub fn len_chars(&self) -> usize {
50        self.model.len_chars()
51    }
52
53    pub fn version(&self) -> u64 {
54        self.model.version()
55    }
56
57    pub fn line_ending(&self) -> LineEnding {
58        self.model.line_ending()
59    }
60
61    pub fn options(&self) -> Options {
62        self.model.options
63    }
64
65    pub fn set_options(&mut self, options: Options) {
66        self.model.options = options;
67    }
68
69    pub fn selections(&self) -> &Selections {
70        self.cursors.selections()
71    }
72
73    pub fn can_undo(&self) -> bool {
74        self.model.can_undo()
75    }
76
77    pub fn can_redo(&self) -> bool {
78        self.model.can_redo()
79    }
80
81    pub fn checkpoint(&mut self) {
82        self.model.checkpoint();
83    }
84
85    /// Replaces the whole text and clears the undo history.
86    pub fn set_text(&mut self, text: &str) {
87        self.model.set_text(text);
88        self.cursors.sync(&self.model);
89    }
90
91    /// Returns the edits applied since the last call, in application order.
92    /// Calls must come at least every 1024 change sets, or older events are lost.
93    pub fn take_events(&mut self) -> Vec<EditEvent> {
94        let events = self.model.events_since(self.events_seen).map(|e| e.cloned().collect()).unwrap_or_default();
95        self.events_seen = self.model.version();
96        events
97    }
98
99    pub fn copy(&mut self) -> String {
100        self.editor().copy()
101    }
102
103    delegate! {
104        set_selections(selections: Selections);
105        insert(text: &str);
106        newline();
107        indent();
108        delete_backward();
109        delete_forward();
110        delete_word_backward();
111        delete_word_forward();
112        apply_edits(edits: Vec<Edit>);
113        cut() -> String;
114        paste(text: &str);
115        move_left(extend: bool);
116        move_right(extend: bool);
117        move_word_left(extend: bool);
118        move_word_right(extend: bool);
119        move_up(extend: bool);
120        move_down(extend: bool);
121        move_vertical(lines: isize, extend: bool);
122        move_line_start(extend: bool);
123        move_line_end(extend: bool);
124        move_document_start(extend: bool);
125        move_document_end(extend: bool);
126        select_all();
127        add_cursor_vertical(below: bool);
128        undo() -> bool;
129        redo() -> bool;
130        tab();
131        indent_lines();
132        outdent_lines();
133        move_lines(up: bool);
134        copy_lines(up: bool);
135        delete_lines();
136        insert_line(below: bool);
137        toggle_line_comment();
138        toggle_block_comment();
139        type_char(c: char);
140        delete_backward_pair();
141        add_next_occurrence();
142        select_all_occurrences();
143        transform_case(upper: bool);
144        trim_trailing_whitespace();
145        cursor_undo() -> bool;
146        shrink_selection() -> bool;
147        type_char_in(c: char, in_literal: bool);
148    }
149
150    pub fn expand_selection(&mut self, ranges: &[std::ops::Range<usize>]) -> bool {
151        self.editor().expand_selection(ranges)
152    }
153
154    pub fn set_language_editing(&mut self, editing: crate::model::LanguageEditing) {
155        self.model.editing = editing;
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use crate::editor::word_at;
163    use crate::selection::Selection;
164
165    fn doc_with_cursors(text: &str, cursors: &[usize]) -> Document {
166        let mut d = Document::new(text);
167        d.set_selections(Selections::new(cursors.iter().map(|&c| Selection::cursor(c)).collect(), 0));
168        d
169    }
170
171    fn carets(d: &Document) -> Vec<usize> {
172        d.selections().iter().map(|s| s.head).collect()
173    }
174
175    #[test]
176    fn multi_cursor_typing_and_grouped_undo() {
177        let mut d = doc_with_cursors("ab\ncd", &[1, 4]);
178        d.insert("x");
179        d.insert("y");
180        assert_eq!(d.text(), "axyb\ncxyd");
181        assert_eq!(carets(&d), [3, 8]);
182        assert!(d.undo());
183        assert_eq!(d.text(), "ab\ncd");
184        assert_eq!(carets(&d), [1, 4]);
185        assert!(d.redo());
186        assert_eq!(d.text(), "axyb\ncxyd");
187        assert_eq!(d.version(), 6, "one version per applied change set");
188    }
189
190    #[test]
191    fn movement_breaks_undo_group() {
192        let mut d = Document::new("");
193        d.insert("a");
194        d.move_left(false);
195        d.insert("b");
196        d.undo();
197        assert_eq!(d.text(), "a");
198    }
199
200    #[test]
201    fn backspace_merges_adjacent_cursors() {
202        let mut d = doc_with_cursors("abcd", &[2, 3]);
203        d.delete_backward();
204        assert_eq!(d.text(), "ad");
205        assert_eq!(carets(&d), [1]);
206    }
207
208    #[test]
209    fn backspace_removes_crlf_as_one() {
210        let mut d = doc_with_cursors("a\r\nb", &[3]);
211        d.delete_backward();
212        assert_eq!(d.text(), "ab");
213    }
214
215    #[test]
216    fn newline_keeps_indent_and_line_ending() {
217        let mut d = doc_with_cursors("    foo\r\n", &[7]);
218        d.newline();
219        assert_eq!(d.text(), "    foo\r\n    \r\n");
220    }
221
222    #[test]
223    fn vertical_movement_keeps_goal_column() {
224        let mut d = doc_with_cursors("abcdef\nab\nabcdef", &[5]);
225        d.move_down(false);
226        assert_eq!(carets(&d), [9]);
227        d.move_down(false);
228        assert_eq!(carets(&d), [15]);
229    }
230
231    #[test]
232    fn smart_home_toggles() {
233        let mut d = doc_with_cursors("  foo", &[4]);
234        d.move_line_start(false);
235        assert_eq!(carets(&d), [2]);
236        d.move_line_start(false);
237        assert_eq!(carets(&d), [0]);
238    }
239
240    #[test]
241    fn paste_spreads_lines_over_cursors() {
242        let mut d = doc_with_cursors("a\nb", &[1, 3]);
243        d.paste("1\n2");
244        assert_eq!(d.text(), "a1\nb2");
245    }
246
247    #[test]
248    fn cut_empty_cursor_takes_line() {
249        let mut d = doc_with_cursors("one\ntwo\n", &[5]);
250        assert_eq!(d.cut(), "two\n");
251        assert_eq!(d.text(), "one\n");
252    }
253
254    #[test]
255    fn events_describe_applied_edits() {
256        let mut d = doc_with_cursors("ab\ncd", &[1, 4]);
257        d.insert("Z");
258        let ev = d.take_events();
259        assert_eq!(ev.len(), 2);
260        assert_eq!((ev[0].start, ev[0].text.as_str()), (4, "Z"));
261        assert_eq!((ev[1].start, ev[1].text.as_str()), (1, "Z"));
262        assert!(d.take_events().is_empty());
263    }
264
265    #[test]
266    fn add_cursor_below_clamps_column() {
267        let mut d = doc_with_cursors("abcd\nx", &[3]);
268        d.add_cursor_vertical(true);
269        assert_eq!(carets(&d), [3, 6]);
270        assert_eq!(d.selections().primary_index(), 1);
271    }
272
273    #[test]
274    fn word_movement_and_deletion() {
275        let mut d = doc_with_cursors("foo.bar  baz\nqux", &[0]);
276        let mut stops = Vec::new();
277        for _ in 0..6 {
278            d.move_word_right(false);
279            stops.push(carets(&d)[0]);
280        }
281        assert_eq!(stops, [3, 4, 7, 12, 13, 16]);
282        d.move_word_left(false);
283        assert_eq!(carets(&d), [13]);
284        let mut d = doc_with_cursors("let value = 1", &[7]);
285        d.delete_word_backward();
286        assert_eq!(d.text(), "let ue = 1");
287        assert_eq!(word_at(d.rope(), 5), (4, 6));
288        assert_eq!(word_at(d.rope(), 3), (0, 3));
289    }
290
291    #[test]
292    fn indent_to_next_tab_stop() {
293        let mut d = doc_with_cursors("ab", &[2]);
294        d.indent();
295        assert_eq!(d.text(), "ab  ");
296    }
297}