ide_db/
text_edit.rs

1//! Representation of a `TextEdit`.
2//!
3//! `rust-analyzer` never mutates text itself and only sends diffs to clients,
4//! so `TextEdit` is the ultimate representation of the work done by
5//! rust-analyzer.
6
7use itertools::Itertools;
8use macros::UpmapFromRaFixture;
9pub use span::{TextRange, TextSize};
10use std::cmp::max;
11
12use crate::source_change::ChangeAnnotationId;
13
14/// `InsertDelete` -- a single "atomic" change to text
15///
16/// Must not overlap with other `InDel`s
17#[derive(Debug, Clone, PartialEq, Eq, Hash, UpmapFromRaFixture)]
18pub struct Indel {
19    pub insert: String,
20    /// Refers to offsets in the original text
21    pub delete: TextRange,
22}
23
24#[derive(Default, Debug, Clone, UpmapFromRaFixture)]
25pub struct TextEdit {
26    /// Invariant: disjoint and sorted by `delete`.
27    indels: Vec<Indel>,
28    annotation: Option<ChangeAnnotationId>,
29}
30
31#[derive(Debug, Default, Clone)]
32pub struct TextEditBuilder {
33    indels: Vec<Indel>,
34    annotation: Option<ChangeAnnotationId>,
35}
36
37impl Indel {
38    pub fn insert(offset: TextSize, text: String) -> Indel {
39        Indel::replace(TextRange::empty(offset), text)
40    }
41    pub fn delete(range: TextRange) -> Indel {
42        Indel::replace(range, String::new())
43    }
44    pub fn replace(range: TextRange, replace_with: String) -> Indel {
45        Indel { delete: range, insert: replace_with }
46    }
47
48    pub fn apply(&self, text: &mut String) {
49        let start: usize = self.delete.start().into();
50        let end: usize = self.delete.end().into();
51        text.replace_range(start..end, &self.insert);
52    }
53}
54
55impl TextEdit {
56    pub fn builder() -> TextEditBuilder {
57        TextEditBuilder::default()
58    }
59
60    pub fn insert(offset: TextSize, text: String) -> TextEdit {
61        let mut builder = TextEdit::builder();
62        builder.insert(offset, text);
63        builder.finish()
64    }
65
66    pub fn delete(range: TextRange) -> TextEdit {
67        let mut builder = TextEdit::builder();
68        builder.delete(range);
69        builder.finish()
70    }
71
72    pub fn replace(range: TextRange, replace_with: String) -> TextEdit {
73        let mut builder = TextEdit::builder();
74        builder.replace(range, replace_with);
75        builder.finish()
76    }
77
78    pub fn len(&self) -> usize {
79        self.indels.len()
80    }
81
82    pub fn is_empty(&self) -> bool {
83        self.indels.is_empty()
84    }
85
86    pub fn iter(&self) -> std::slice::Iter<'_, Indel> {
87        self.into_iter()
88    }
89
90    pub fn apply(&self, text: &mut String) {
91        match self.len() {
92            0 => return,
93            1 => {
94                self.indels[0].apply(text);
95                return;
96            }
97            _ => (),
98        }
99
100        let text_size = TextSize::of(&*text);
101        let mut total_len = text_size;
102        let mut max_total_len = text_size;
103        for indel in &self.indels {
104            total_len += TextSize::of(&indel.insert);
105            total_len -= indel.delete.len();
106            max_total_len = max(max_total_len, total_len);
107        }
108
109        if let Some(additional) = max_total_len.checked_sub(text_size) {
110            text.reserve(additional.into());
111        }
112
113        for indel in self.indels.iter().rev() {
114            indel.apply(text);
115        }
116
117        assert_eq!(TextSize::of(&*text), total_len);
118    }
119
120    pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> {
121        let iter_merge =
122            self.iter().merge_by(other.iter(), |l, r| l.delete.start() <= r.delete.start());
123        if !check_disjoint(&mut iter_merge.clone()) {
124            return Err(other);
125        }
126
127        // Only dedup deletions and replacements, keep all insertions
128        self.indels = iter_merge.dedup_by(|a, b| a == b && !a.delete.is_empty()).cloned().collect();
129        Ok(())
130    }
131
132    pub fn apply_to_offset(&self, offset: TextSize) -> Option<TextSize> {
133        let mut res = offset;
134        for indel in &self.indels {
135            if indel.delete.start() >= offset {
136                break;
137            }
138            if offset < indel.delete.end() {
139                return None;
140            }
141            res += TextSize::of(&indel.insert);
142            res -= indel.delete.len();
143        }
144        Some(res)
145    }
146
147    pub(crate) fn set_annotation(&mut self, conflict_annotation: Option<ChangeAnnotationId>) {
148        self.annotation = conflict_annotation;
149    }
150
151    pub fn change_annotation(&self) -> Option<ChangeAnnotationId> {
152        self.annotation
153    }
154}
155
156impl IntoIterator for TextEdit {
157    type Item = Indel;
158    type IntoIter = std::vec::IntoIter<Indel>;
159
160    fn into_iter(self) -> Self::IntoIter {
161        self.indels.into_iter()
162    }
163}
164
165impl<'a> IntoIterator for &'a TextEdit {
166    type Item = &'a Indel;
167    type IntoIter = std::slice::Iter<'a, Indel>;
168
169    fn into_iter(self) -> Self::IntoIter {
170        self.indels.iter()
171    }
172}
173
174impl TextEditBuilder {
175    pub fn is_empty(&self) -> bool {
176        self.indels.is_empty()
177    }
178    pub fn replace(&mut self, range: TextRange, replace_with: String) {
179        self.indel(Indel::replace(range, replace_with));
180    }
181    pub fn delete(&mut self, range: TextRange) {
182        self.indel(Indel::delete(range));
183    }
184    pub fn insert(&mut self, offset: TextSize, text: String) {
185        self.indel(Indel::insert(offset, text));
186    }
187    pub fn finish(self) -> TextEdit {
188        let TextEditBuilder { mut indels, annotation } = self;
189        assert_disjoint_or_equal(&mut indels);
190        indels = coalesce_indels(indels);
191        TextEdit { indels, annotation }
192    }
193    pub fn invalidates_offset(&self, offset: TextSize) -> bool {
194        self.indels.iter().any(|indel| indel.delete.contains_inclusive(offset))
195    }
196    pub fn indel(&mut self, indel: Indel) {
197        self.indels.push(indel);
198        if self.indels.len() <= 16 {
199            assert_disjoint_or_equal(&mut self.indels);
200        }
201    }
202}
203
204fn assert_disjoint_or_equal(indels: &mut [Indel]) {
205    assert!(check_disjoint_and_sort(indels));
206}
207
208fn check_disjoint_and_sort(indels: &mut [Indel]) -> bool {
209    indels.sort_by_key(|indel| (indel.delete.start(), indel.delete.end()));
210    check_disjoint(&mut indels.iter())
211}
212
213fn check_disjoint<'a, I>(indels: &mut I) -> bool
214where
215    I: std::iter::Iterator<Item = &'a Indel> + Clone,
216{
217    indels.clone().zip(indels.skip(1)).all(|(l, r)| l.delete.end() <= r.delete.start() || l == r)
218}
219
220fn coalesce_indels(indels: Vec<Indel>) -> Vec<Indel> {
221    indels
222        .into_iter()
223        .coalesce(|mut a, b| {
224            if a.delete.end() == b.delete.start() {
225                a.insert.push_str(&b.insert);
226                a.delete = TextRange::new(a.delete.start(), b.delete.end());
227                Ok(a)
228            } else {
229                Err((a, b))
230            }
231        })
232        .collect_vec()
233}
234
235#[cfg(test)]
236mod tests {
237    use super::{TextEdit, TextEditBuilder, TextRange};
238
239    fn range(start: u32, end: u32) -> TextRange {
240        TextRange::new(start.into(), end.into())
241    }
242
243    #[test]
244    fn test_apply() {
245        let mut text = "_11h1_2222_xx3333_4444_6666".to_owned();
246        let mut builder = TextEditBuilder::default();
247        builder.replace(range(3, 4), "1".to_owned());
248        builder.delete(range(11, 13));
249        builder.insert(22.into(), "_5555".to_owned());
250
251        let text_edit = builder.finish();
252        text_edit.apply(&mut text);
253
254        assert_eq!(text, "_1111_2222_3333_4444_5555_6666")
255    }
256
257    #[test]
258    fn test_union() {
259        let mut edit1 = TextEdit::delete(range(7, 11));
260        let mut builder = TextEditBuilder::default();
261        builder.delete(range(1, 5));
262        builder.delete(range(13, 17));
263
264        let edit2 = builder.finish();
265        assert!(edit1.union(edit2).is_ok());
266        assert_eq!(edit1.indels.len(), 3);
267    }
268
269    #[test]
270    fn test_union_with_duplicates() {
271        let mut builder1 = TextEditBuilder::default();
272        builder1.delete(range(7, 11));
273        builder1.delete(range(13, 17));
274
275        let mut builder2 = TextEditBuilder::default();
276        builder2.delete(range(1, 5));
277        builder2.delete(range(13, 17));
278
279        let mut edit1 = builder1.finish();
280        let edit2 = builder2.finish();
281        assert!(edit1.union(edit2).is_ok());
282        assert_eq!(edit1.indels.len(), 3);
283    }
284
285    #[test]
286    fn test_union_panics() {
287        let mut edit1 = TextEdit::delete(range(7, 11));
288        let edit2 = TextEdit::delete(range(9, 13));
289        assert!(edit1.union(edit2).is_err());
290    }
291
292    #[test]
293    fn test_coalesce_disjoint() {
294        let mut builder = TextEditBuilder::default();
295        builder.replace(range(1, 3), "aa".into());
296        builder.replace(range(5, 7), "bb".into());
297        let edit = builder.finish();
298
299        assert_eq!(edit.indels.len(), 2);
300    }
301
302    #[test]
303    fn test_coalesce_adjacent() {
304        let mut builder = TextEditBuilder::default();
305        builder.replace(range(1, 3), "aa".into());
306        builder.replace(range(3, 5), "bb".into());
307
308        let edit = builder.finish();
309        assert_eq!(edit.indels.len(), 1);
310        assert_eq!(edit.indels[0].insert, "aabb");
311        assert_eq!(edit.indels[0].delete, range(1, 5));
312    }
313
314    #[test]
315    fn test_coalesce_adjacent_series() {
316        let mut builder = TextEditBuilder::default();
317        builder.replace(range(1, 3), "au".into());
318        builder.replace(range(3, 5), "www".into());
319        builder.replace(range(5, 8), "".into());
320        builder.replace(range(8, 9), "ub".into());
321
322        let edit = builder.finish();
323        assert_eq!(edit.indels.len(), 1);
324        assert_eq!(edit.indels[0].insert, "auwwwub");
325        assert_eq!(edit.indels[0].delete, range(1, 9));
326    }
327}