Skip to main content

rustaco_core/
change.rs

1//! Change sets: a batch of non-overlapping edits applied to a rope in one step.
2
3use ropey::Rope;
4
5use crate::position::{Point, Utf16Position, char_to_point, char_to_utf16};
6
7/// Replace chars `start..end` with `text`. Offsets refer to the document before the change set.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct Edit {
10    pub start: usize,
11    pub end: usize,
12    pub text: String,
13}
14
15impl Edit {
16    pub fn new(start: usize, end: usize, text: impl Into<String>) -> Self {
17        assert!(start <= end, "edit range is reversed");
18        Self { start, end, text: text.into() }
19    }
20
21    pub fn insert(at: usize, text: impl Into<String>) -> Self {
22        Self::new(at, at, text)
23    }
24
25    pub fn delete(start: usize, end: usize) -> Self {
26        Self::new(start, end, String::new())
27    }
28
29    fn is_noop(&self) -> bool {
30        self.start == self.end && self.text.is_empty()
31    }
32}
33
34/// Which side of an insertion a mapped position lands on.
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum Assoc {
37    Before,
38    After,
39}
40
41/// Edits sorted by position. Overlapping or touching edits are merged on construction,
42/// so every position belongs to at most one edit.
43#[derive(Clone, Debug, Default, PartialEq, Eq)]
44pub struct ChangeSet {
45    edits: Vec<Edit>,
46}
47
48impl ChangeSet {
49    /// Sorts and merges `edits`. When two edits overlap, the merged edit replaces the
50    /// union of both ranges with their texts concatenated in position order.
51    pub fn new(mut edits: Vec<Edit>) -> Self {
52        edits.retain(|e| !e.is_noop());
53        edits.sort_by_key(|e| (e.start, e.end));
54        let mut merged: Vec<Edit> = Vec::with_capacity(edits.len());
55        for e in edits {
56            match merged.last_mut() {
57                Some(last) if e.start <= last.end => {
58                    last.end = last.end.max(e.end);
59                    last.text.push_str(&e.text);
60                }
61                _ => merged.push(e),
62            }
63        }
64        Self { edits: merged }
65    }
66
67    /// Moves edit boundaries that fall between `\r` and `\n` outside the pair, adjusting the
68    /// text so the result is unchanged. Such a position has no line/column form, so an edit
69    /// there could not be reported to LSP servers.
70    pub(crate) fn snap_crlf(self, rope: &Rope) -> ChangeSet {
71        if !self.needs_crlf_snap(rope) {
72            return self;
73        }
74        let edits = self
75            .edits
76            .into_iter()
77            .map(|mut e| {
78                if inside_crlf(rope, e.start) {
79                    e.start -= 1;
80                    e.text.insert(0, '\r');
81                }
82                if inside_crlf(rope, e.end) {
83                    e.end += 1;
84                    e.text.push('\n');
85                }
86                e
87            })
88            .collect();
89        // Snapping can make edits touch but never overlap; touching edits merge correctly.
90        ChangeSet::new(edits)
91    }
92
93    pub(crate) fn needs_crlf_snap(&self, rope: &Rope) -> bool {
94        self.edits.iter().any(|e| inside_crlf(rope, e.start) || inside_crlf(rope, e.end))
95    }
96
97    pub fn edits(&self) -> &[Edit] {
98        &self.edits
99    }
100
101    pub fn is_empty(&self) -> bool {
102        self.edits.is_empty()
103    }
104
105    /// Applies the change set and returns its inverse.
106    pub fn apply(&self, rope: &mut Rope) -> ChangeSet {
107        let mut inverse = Vec::with_capacity(self.edits.len());
108        let mut delta = 0isize;
109        for e in &self.edits {
110            let removed = rope.slice(e.start..e.end).to_string();
111            let start = e.start.wrapping_add_signed(delta);
112            let inserted = e.text.chars().count();
113            inverse.push(Edit::new(start, start + inserted, removed));
114            delta += inserted as isize - (e.end - e.start) as isize;
115        }
116        // Back to front, so earlier offsets stay valid.
117        for e in self.edits.iter().rev() {
118            rope.remove(e.start..e.end);
119            rope.insert(e.start, &e.text);
120        }
121        ChangeSet { edits: inverse }
122    }
123
124    /// Maps a char offset from before the change to after it.
125    /// A position inside a replaced range moves to its start (`Before`) or end (`After`).
126    pub fn map(&self, pos: usize, assoc: Assoc) -> usize {
127        let mut delta = 0isize;
128        for e in &self.edits {
129            if pos < e.start {
130                break;
131            }
132            let inserted = e.text.chars().count();
133            if pos > e.end || (pos == e.end && e.start < e.end) {
134                delta += inserted as isize - (e.end - e.start) as isize;
135                continue;
136            }
137            let start = e.start.wrapping_add_signed(delta);
138            return match assoc {
139                Assoc::Before => start,
140                Assoc::After => start + inserted,
141            };
142        }
143        pos.wrapping_add_signed(delta)
144    }
145
146    /// Describes the edits for incremental consumers (LSP `didChange`, tree-sitter `Tree::edit`).
147    ///
148    /// `rope` must be the document before the change. Events come last edit first, so each
149    /// event's coordinates stay valid after the events before it have been applied.
150    pub fn describe(&self, rope: &Rope) -> Vec<EditEvent> {
151        self.edits
152            .iter()
153            .rev()
154            .map(|e| {
155                let extent = TextExtent::of(&e.text);
156                let start_point = char_to_point(rope, e.start);
157                let start_byte = rope.char_to_byte(e.start);
158                EditEvent {
159                    start: e.start,
160                    old_end: e.end,
161                    new_end: e.start + extent.chars,
162                    start_byte,
163                    old_end_byte: rope.char_to_byte(e.end),
164                    new_end_byte: start_byte + e.text.len(),
165                    start_point,
166                    old_end_point: char_to_point(rope, e.end),
167                    new_end_point: if extent.line_breaks == 0 {
168                        Point { row: start_point.row, column: start_point.column + extent.last_line_bytes }
169                    } else {
170                        Point { row: start_point.row + extent.line_breaks, column: extent.last_line_bytes }
171                    },
172                    start_utf16: char_to_utf16(rope, e.start),
173                    old_end_utf16: char_to_utf16(rope, e.end),
174                    text: e.text.clone(),
175                }
176            })
177            .collect()
178    }
179}
180
181/// One applied edit, in every unit a consumer might need.
182#[derive(Clone, Debug, PartialEq, Eq)]
183pub struct EditEvent {
184    pub start: usize,
185    pub old_end: usize,
186    pub new_end: usize,
187    pub start_byte: usize,
188    pub old_end_byte: usize,
189    pub new_end_byte: usize,
190    pub start_point: Point,
191    pub old_end_point: Point,
192    pub new_end_point: Point,
193    pub start_utf16: Utf16Position,
194    pub old_end_utf16: Utf16Position,
195    pub text: String,
196}
197
198/// True when `pos` sits between the `\r` and `\n` of a CRLF pair.
199pub(crate) fn inside_crlf(rope: &Rope, pos: usize) -> bool {
200    pos > 0 && pos < rope.len_chars() && rope.char(pos - 1) == '\r' && rope.char(pos) == '\n'
201}
202
203struct TextExtent {
204    chars: usize,
205    line_breaks: usize,
206    last_line_bytes: usize,
207}
208
209impl TextExtent {
210    fn of(text: &str) -> Self {
211        let mut ext = TextExtent { chars: 0, line_breaks: 0, last_line_bytes: 0 };
212        let mut chars = text.chars().peekable();
213        while let Some(c) = chars.next() {
214            ext.chars += 1;
215            match c {
216                '\r' => {
217                    if chars.peek() == Some(&'\n') {
218                        chars.next();
219                        ext.chars += 1;
220                    }
221                    ext.line_breaks += 1;
222                    ext.last_line_bytes = 0;
223                }
224                '\n' => {
225                    ext.line_breaks += 1;
226                    ext.last_line_bytes = 0;
227                }
228                _ => ext.last_line_bytes += c.len_utf8(),
229            }
230        }
231        ext
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    #[test]
240    fn apply_and_invert() {
241        let mut rope = Rope::from_str("hello world");
242        let cs = ChangeSet::new(vec![Edit::new(6, 11, "rust"), Edit::insert(0, ">> ")]);
243        let inverse = cs.apply(&mut rope);
244        assert_eq!(rope.to_string(), ">> hello rust");
245        inverse.apply(&mut rope);
246        assert_eq!(rope.to_string(), "hello world");
247    }
248
249    #[test]
250    fn merges_overlapping_and_touching() {
251        let cs = ChangeSet::new(vec![Edit::delete(2, 3), Edit::delete(1, 2), Edit::delete(0, 2)]);
252        assert_eq!(cs.edits(), [Edit::delete(0, 3)]);
253    }
254
255    #[test]
256    fn map_positions() {
257        let cs = ChangeSet::new(vec![Edit::insert(2, "xx"), Edit::new(5, 8, "y")]);
258        assert_eq!(cs.map(1, Assoc::After), 1);
259        assert_eq!(cs.map(2, Assoc::Before), 2);
260        assert_eq!(cs.map(2, Assoc::After), 4);
261        assert_eq!(cs.map(6, Assoc::Before), 7);
262        assert_eq!(cs.map(8, Assoc::Before), 8);
263        assert_eq!(cs.map(10, Assoc::Before), 10);
264    }
265
266    #[test]
267    fn describe_reports_bytes_points_and_utf16() {
268        let rope = Rope::from_str("é\nab");
269        let cs = ChangeSet::new(vec![Edit::new(3, 4, "x\nyz"), Edit::insert(0, "\u{1F600}")]);
270        let ev = cs.describe(&rope);
271        assert_eq!(ev.len(), 2);
272        // Last edit first.
273        assert_eq!(ev[0].start_point, Point { row: 1, column: 1 });
274        assert_eq!(ev[0].new_end_point, Point { row: 2, column: 2 });
275        assert_eq!(ev[0].start_byte, 4);
276        assert_eq!(ev[1].start_utf16, Utf16Position { line: 0, character: 0 });
277        assert_eq!(ev[1].new_end_byte, 4);
278    }
279}