]> git.lizzy.rs Git - rust.git/blob - crates/text_edit/src/lib.rs
Reuse existing element rendering
[rust.git] / crates / text_edit / src / lib.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 pub use text_size::{TextRange, TextSize};
7
8 /// `InsertDelete` -- a single "atomic" change to text
9 ///
10 /// Must not overlap with other `InDel`s
11 #[derive(Debug, Clone)]
12 pub struct Indel {
13     pub insert: String,
14     /// Refers to offsets in the original text
15     pub delete: TextRange,
16 }
17
18 #[derive(Default, Debug, Clone)]
19 pub struct TextEdit {
20     indels: Vec<Indel>,
21 }
22
23 #[derive(Debug, Default, Clone)]
24 pub struct TextEditBuilder {
25     indels: Vec<Indel>,
26 }
27
28 impl Indel {
29     pub fn insert(offset: TextSize, text: String) -> Indel {
30         Indel::replace(TextRange::empty(offset), text)
31     }
32     pub fn delete(range: TextRange) -> Indel {
33         Indel::replace(range, String::new())
34     }
35     pub fn replace(range: TextRange, replace_with: String) -> Indel {
36         Indel { delete: range, insert: replace_with }
37     }
38
39     pub fn apply(&self, text: &mut String) {
40         let start: usize = self.delete.start().into();
41         let end: usize = self.delete.end().into();
42         text.replace_range(start..end, &self.insert);
43     }
44 }
45
46 impl TextEdit {
47     pub fn builder() -> TextEditBuilder {
48         TextEditBuilder::default()
49     }
50
51     pub fn into_builder(self) -> TextEditBuilder {
52         TextEditBuilder { indels: self.indels }
53     }
54
55     pub fn insert(offset: TextSize, text: String) -> TextEdit {
56         let mut builder = TextEdit::builder();
57         builder.insert(offset, text);
58         builder.finish()
59     }
60
61     pub fn delete(range: TextRange) -> TextEdit {
62         let mut builder = TextEdit::builder();
63         builder.delete(range);
64         builder.finish()
65     }
66
67     pub fn replace(range: TextRange, replace_with: String) -> TextEdit {
68         let mut builder = TextEdit::builder();
69         builder.replace(range, replace_with);
70         builder.finish()
71     }
72
73     pub fn len(&self) -> usize {
74         self.indels.len()
75     }
76
77     pub fn is_empty(&self) -> bool {
78         self.indels.is_empty()
79     }
80
81     pub fn iter(&self) -> std::slice::Iter<'_, Indel> {
82         self.into_iter()
83     }
84
85     pub fn apply(&self, text: &mut String) {
86         match self.len() {
87             0 => return,
88             1 => {
89                 self.indels[0].apply(text);
90                 return;
91             }
92             _ => (),
93         }
94
95         let mut total_len = TextSize::of(&*text);
96         for indel in self.indels.iter() {
97             total_len += TextSize::of(&indel.insert);
98             total_len -= indel.delete.end() - indel.delete.start();
99         }
100         let mut buf = String::with_capacity(total_len.into());
101         let mut prev = 0;
102         for indel in self.indels.iter() {
103             let start: usize = indel.delete.start().into();
104             let end: usize = indel.delete.end().into();
105             if start > prev {
106                 buf.push_str(&text[prev..start]);
107             }
108             buf.push_str(&indel.insert);
109             prev = end;
110         }
111         buf.push_str(&text[prev..text.len()]);
112         assert_eq!(TextSize::of(&buf), total_len);
113
114         // FIXME: figure out a way to mutate the text in-place or reuse the
115         // memory in some other way
116         *text = buf
117     }
118
119     pub fn union(&mut self, other: TextEdit) -> Result<(), TextEdit> {
120         // FIXME: can be done without allocating intermediate vector
121         let mut all = self.iter().chain(other.iter()).collect::<Vec<_>>();
122         if !check_disjoint(&mut all) {
123             return Err(other);
124         }
125         self.indels.extend(other.indels);
126         assert_disjoint(&mut self.indels);
127         Ok(())
128     }
129
130     pub fn apply_to_offset(&self, offset: TextSize) -> Option<TextSize> {
131         let mut res = offset;
132         for indel in self.indels.iter() {
133             if indel.delete.start() >= offset {
134                 break;
135             }
136             if offset < indel.delete.end() {
137                 return None;
138             }
139             res += TextSize::of(&indel.insert);
140             res -= indel.delete.len();
141         }
142         Some(res)
143     }
144 }
145
146 impl IntoIterator for TextEdit {
147     type Item = Indel;
148     type IntoIter = std::vec::IntoIter<Indel>;
149
150     fn into_iter(self) -> Self::IntoIter {
151         self.indels.into_iter()
152     }
153 }
154
155 impl<'a> IntoIterator for &'a TextEdit {
156     type Item = &'a Indel;
157     type IntoIter = std::slice::Iter<'a, Indel>;
158
159     fn into_iter(self) -> Self::IntoIter {
160         self.indels.iter()
161     }
162 }
163
164 impl TextEditBuilder {
165     pub fn replace(&mut self, range: TextRange, replace_with: String) {
166         self.indel(Indel::replace(range, replace_with))
167     }
168     pub fn delete(&mut self, range: TextRange) {
169         self.indel(Indel::delete(range))
170     }
171     pub fn insert(&mut self, offset: TextSize, text: String) {
172         self.indel(Indel::insert(offset, text))
173     }
174     pub fn finish(self) -> TextEdit {
175         let mut indels = self.indels;
176         assert_disjoint(&mut indels);
177         TextEdit { indels }
178     }
179     pub fn invalidates_offset(&self, offset: TextSize) -> bool {
180         self.indels.iter().any(|indel| indel.delete.contains_inclusive(offset))
181     }
182     fn indel(&mut self, indel: Indel) {
183         self.indels.push(indel);
184         if self.indels.len() <= 16 {
185             assert_disjoint(&mut self.indels);
186         }
187     }
188 }
189
190 fn assert_disjoint(indels: &mut [impl std::borrow::Borrow<Indel>]) {
191     assert!(check_disjoint(indels));
192 }
193 fn check_disjoint(indels: &mut [impl std::borrow::Borrow<Indel>]) -> bool {
194     indels.sort_by_key(|indel| (indel.borrow().delete.start(), indel.borrow().delete.end()));
195     indels
196         .iter()
197         .zip(indels.iter().skip(1))
198         .all(|(l, r)| l.borrow().delete.end() <= r.borrow().delete.start())
199 }