1use crate::buffer::TextBuffer;
13use crate::canvas_editor::CodeEditor;
14use crate::canvas_editor::editing::command::{
15 Command, CompositeCommand, DeleteRangeCommand, InsertTextCommand,
16};
17use crate::canvas_editor::lsp::{LspPosition, LspTextChange};
18
19#[derive(Debug, PartialEq, Eq)]
21struct ResolvedEdit {
22 start: (usize, usize),
24 end: (usize, usize),
26 text: String,
28}
29
30fn clamp_position(
38 buffer: &TextBuffer,
39 position: LspPosition,
40) -> (usize, usize) {
41 let last_line = buffer.line_count().saturating_sub(1);
42 let line = position.line as usize;
43 if line > last_line {
44 return (last_line, buffer.line_len(last_line));
45 }
46 (line, (position.character as usize).min(buffer.line_len(line)))
47}
48
49fn resolve_edits(
55 buffer: &TextBuffer,
56 edits: &[LspTextChange],
57) -> Option<Vec<ResolvedEdit>> {
58 let mut resolved: Vec<ResolvedEdit> = edits
59 .iter()
60 .map(|edit| {
61 let start = clamp_position(buffer, edit.range.start);
62 let end = clamp_position(buffer, edit.range.end);
63 let (start, end) =
66 if start <= end { (start, end) } else { (end, start) };
67 ResolvedEdit { start, end, text: edit.text.clone() }
68 })
69 .filter(|edit| !(edit.start == edit.end && edit.text.is_empty()))
70 .collect();
71
72 resolved.sort_by_key(|edit| edit.start);
73
74 if resolved.windows(2).any(|pair| pair[1].start < pair[0].end) {
75 return None;
76 }
77
78 Some(resolved)
79}
80
81impl CodeEditor {
82 pub fn apply_lsp_text_edits(&mut self, edits: &[LspTextChange]) -> bool {
127 let Some(resolved) = resolve_edits(&self.buffer, edits) else {
128 return false;
129 };
130 if resolved.is_empty() {
131 return false;
132 }
133
134 self.end_grouping_if_active();
137
138 let cursor_before = self.cursors.primary_position();
139 let mut composite = CompositeCommand::new();
140
141 for edit in resolved.iter().rev() {
145 composite.add(Box::new(DeleteRangeCommand::new(
146 &self.buffer,
147 edit.start,
148 edit.end,
149 cursor_before,
150 )));
151 if !edit.text.is_empty() {
152 composite.add(Box::new(InsertTextCommand::new(
153 edit.start.0,
154 edit.start.1,
155 edit.text.clone(),
156 cursor_before,
157 )));
158 }
159 }
160
161 let mut cursor_position = cursor_before;
162 composite.execute(&mut self.buffer, &mut cursor_position);
163 self.history.push(Box::new(composite));
164
165 self.cursors.set_single(self.clamp_to_buffer(cursor_before));
166
167 self.pre_edit_line = 0;
170 self.pre_edit_last_line = usize::MAX;
171 self.finish_edit_operation();
172 true
173 }
174
175 fn clamp_to_buffer(&self, position: (usize, usize)) -> (usize, usize) {
177 let line = position.0.min(self.buffer.line_count().saturating_sub(1));
178 (line, position.1.min(self.buffer.line_len(line)))
179 }
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185 use crate::canvas_editor::lsp::LspRange;
186
187 fn edit(start: (u32, u32), end: (u32, u32), text: &str) -> LspTextChange {
189 LspTextChange {
190 range: LspRange {
191 start: LspPosition { line: start.0, character: start.1 },
192 end: LspPosition { line: end.0, character: end.1 },
193 },
194 text: text.to_string(),
195 }
196 }
197
198 #[test]
199 fn test_clamp_position_keeps_an_in_bounds_position() {
200 let buffer = TextBuffer::new("abc\ndef");
201 assert_eq!(
202 clamp_position(&buffer, LspPosition { line: 1, character: 2 }),
203 (1, 2)
204 );
205 }
206
207 #[test]
208 fn test_clamp_position_folds_a_past_the_end_position_onto_the_document() {
209 let buffer = TextBuffer::new("abc\ndef");
210 assert_eq!(
212 clamp_position(
213 &buffer,
214 LspPosition { line: u32::MAX, character: 0 }
215 ),
216 (1, 3)
217 );
218 assert_eq!(
219 clamp_position(
220 &buffer,
221 LspPosition { line: 0, character: u32::MAX }
222 ),
223 (0, 3)
224 );
225 }
226
227 #[test]
228 fn test_resolve_edits_sorts_and_drops_no_ops() {
229 let buffer = TextBuffer::new("abcdef");
230 let resolved = resolve_edits(
231 &buffer,
232 &[
233 edit((0, 4), (0, 5), "Y"),
234 edit((0, 2), (0, 2), ""),
235 edit((0, 0), (0, 1), "X"),
236 ],
237 );
238
239 assert_eq!(
240 resolved,
241 Some(vec![
242 ResolvedEdit {
243 start: (0, 0),
244 end: (0, 1),
245 text: "X".to_string()
246 },
247 ResolvedEdit {
248 start: (0, 4),
249 end: (0, 5),
250 text: "Y".to_string()
251 },
252 ])
253 );
254 }
255
256 #[test]
257 fn test_resolve_edits_refuses_overlapping_ranges() {
258 let buffer = TextBuffer::new("abcdef");
259 assert_eq!(
260 resolve_edits(
261 &buffer,
262 &[edit((0, 0), (0, 3), "X"), edit((0, 2), (0, 4), "Y")]
263 ),
264 None
265 );
266 }
267
268 #[test]
269 fn test_resolve_edits_accepts_ranges_that_only_touch() {
270 let buffer = TextBuffer::new("abcdef");
271 let resolved = resolve_edits(
272 &buffer,
273 &[edit((0, 0), (0, 2), "X"), edit((0, 2), (0, 4), "Y")],
274 );
275 assert!(resolved.is_some_and(|edits| edits.len() == 2));
276 }
277
278 #[test]
279 fn test_apply_replaces_the_whole_document() {
280 let mut editor = CodeEditor::new("fn main( ) {}", "rs");
281 let applied = editor.apply_lsp_text_edits(&[edit(
282 (0, 0),
283 (1, 0),
284 "fn main() {}",
285 )]);
286
287 assert!(applied);
288 assert_eq!(editor.content(), "fn main() {}");
289 }
290
291 #[test]
292 fn test_apply_several_edits_uses_the_original_coordinates() {
293 let mut editor = CodeEditor::new("aXbYc", "rs");
296 let applied = editor.apply_lsp_text_edits(&[
297 edit((0, 1), (0, 2), "1"),
298 edit((0, 3), (0, 4), "22"),
299 ]);
300
301 assert!(applied);
302 assert_eq!(editor.content(), "a1b22c");
303 }
304
305 #[test]
306 fn test_apply_across_lines_reflows_the_document() {
307 let mut editor = CodeEditor::new("one\ntwo\nthree", "rs");
308 let applied =
309 editor.apply_lsp_text_edits(&[edit((0, 3), (2, 0), "\n")]);
310
311 assert!(applied);
312 assert_eq!(editor.content(), "one\nthree");
313 }
314
315 #[test]
316 fn test_apply_is_a_single_undo_step() {
317 let mut editor = CodeEditor::new("a\nb\nc", "rs");
318 let applied = editor.apply_lsp_text_edits(&[
319 edit((0, 0), (0, 1), "A"),
320 edit((2, 0), (2, 1), "C"),
321 ]);
322 assert!(applied);
323 assert_eq!(editor.content(), "A\nb\nC");
324
325 let _ = editor.update(&crate::canvas_editor::Message::Undo);
326 assert_eq!(editor.content(), "a\nb\nc");
327 }
328
329 #[test]
330 fn test_apply_keeps_the_cursor_where_it_was() {
331 let mut editor = CodeEditor::new("one\ntwo\nthree", "rs");
332 let _ = editor.set_cursor(1, 2);
333 assert!(editor.apply_lsp_text_edits(&[edit((0, 0), (0, 3), "1")]));
334 assert_eq!(editor.cursor_position(), (1, 2));
335 }
336
337 #[test]
338 fn test_apply_clamps_a_cursor_the_edits_left_out_of_bounds() {
339 let mut editor = CodeEditor::new("one\ntwo\nthree", "rs");
340 let _ = editor.set_cursor(2, 5);
341 assert!(editor.apply_lsp_text_edits(&[edit((0, 0), (2, 5), "x")]));
343 assert_eq!(editor.cursor_position(), (0, 1));
344 }
345
346 #[test]
347 fn test_apply_reports_nothing_done_for_an_empty_reply() {
348 let mut editor = CodeEditor::new("fn main() {}", "rs");
349 assert!(!editor.apply_lsp_text_edits(&[]));
350 assert_eq!(editor.content(), "fn main() {}");
351 }
352
353 #[test]
354 fn test_apply_reports_nothing_done_for_overlapping_edits() {
355 let mut editor = CodeEditor::new("abcdef", "rs");
356 assert!(!editor.apply_lsp_text_edits(&[
357 edit((0, 0), (0, 3), "X"),
358 edit((0, 2), (0, 4), "Y"),
359 ]));
360 assert_eq!(editor.content(), "abcdef");
361 }
362
363 #[test]
364 fn test_apply_marks_the_document_modified() {
365 let mut editor = CodeEditor::new("fn main() {}", "rs");
366 assert!(!editor.is_modified());
367 assert!(editor.apply_lsp_text_edits(&[edit((0, 2), (0, 4), " ")]));
368 assert!(editor.is_modified());
369 }
370}