Skip to main content

iced_code_editor/canvas_editor/lsp/
edits.rs

1//! Applying an LSP `TextEdit[]` reply to the buffer.
2//!
3//! Formatting is the first feature to need this, but the shape is the one
4//! every edit-returning request uses (code actions, rename, organise
5//! imports), so the entry point takes a plain slice of [`LspTextChange`]
6//! rather than anything formatting-specific.
7//!
8//! The edits arrive in document coordinates that all refer to the *same*
9//! original document, so they are applied last-first: an earlier edit would
10//! otherwise shift the positions of every edit after it.
11
12use 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/// An LSP edit resolved to in-bounds buffer coordinates.
20#[derive(Debug, PartialEq, Eq)]
21struct ResolvedEdit {
22    /// Start of the replaced range, as `(line, column)`.
23    start: (usize, usize),
24    /// End of the replaced range, as `(line, column)`.
25    end: (usize, usize),
26    /// Text replacing that range.
27    text: String,
28}
29
30/// Clamps an LSP position onto an existing buffer position.
31///
32/// Servers routinely describe "the end of the document" as the start of a line
33/// one past the last one — the shape a whole-document format reply uses. Such a
34/// position folds onto the *end* of the last line rather than its start, which
35/// is the position it actually denotes; a column past the end of a real line is
36/// clamped onto that line's end.
37fn 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
49/// Resolves `edits` against `buffer`, dropping the ones that change nothing.
50///
51/// The result is sorted by start position. Returns `None` when two edits
52/// overlap: LSP forbids that, and applying an overlapping pair would silently
53/// corrupt the buffer, so the whole reply is refused instead.
54fn 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            // A reversed range is not meaningful; normalise rather than
64            // trusting the order the server sent the endpoints in.
65            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    /// Applies a batch of LSP text edits to the buffer as one undo step.
83    ///
84    /// This is how a `TextEdit[]` reply — a `textDocument/formatting`
85    /// response, for instance — reaches the document. Positions outside the
86    /// buffer are clamped onto it, so an end-of-document range expressed as a
87    /// line past the last one still lands correctly.
88    ///
89    /// The cursor keeps its line and column where the reformatted document
90    /// still has one, clamped onto the nearest position where it does not, and
91    /// any selection is dropped: after a whole-document rewrite the old
92    /// selection no longer covers what the user selected.
93    ///
94    /// # Arguments
95    ///
96    /// * `edits` - Edits from the server, all in coordinates of the current document
97    ///
98    /// # Returns
99    ///
100    /// `true` when the buffer was modified; `false` when `edits` is empty,
101    /// contains only no-op edits, or describes overlapping ranges — which LSP
102    /// forbids and which cannot be applied without corrupting the buffer
103    ///
104    /// # Example
105    ///
106    /// ```
107    /// use iced_code_editor::{CodeEditor, LspPosition, LspRange, LspTextChange};
108    ///
109    /// let mut editor = CodeEditor::new("fn  main() {}", "rs");
110    ///
111    /// // The server asks for the double space to become a single one.
112    /// let edit = LspTextChange {
113    ///     range: LspRange {
114    ///         start: LspPosition { line: 0, character: 2 },
115    ///         end: LspPosition { line: 0, character: 4 },
116    ///     },
117    ///     text: " ".to_string(),
118    /// };
119    ///
120    /// assert!(editor.apply_lsp_text_edits(&[edit]));
121    /// assert_eq!(editor.content(), "fn main() {}");
122    ///
123    /// // An empty reply — an already-formatted document — changes nothing.
124    /// assert!(!editor.apply_lsp_text_edits(&[]));
125    /// ```
126    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        // A format lands as its own undo step rather than joining whatever
135        // typing group happens to be open.
136        self.end_grouping_if_active();
137
138        let cursor_before = self.cursors.primary_position();
139        let mut composite = CompositeCommand::new();
140
141        // Last edit first: every range is expressed against the document as it
142        // stands now, so applying an earlier one would move the ranges of all
143        // the edits that follow it.
144        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        // The edits may sit anywhere in the document, so no prefix of the
168        // highlight cache can be assumed to have survived them.
169        self.pre_edit_line = 0;
170        self.pre_edit_last_line = usize::MAX;
171        self.finish_edit_operation();
172        true
173    }
174
175    /// Clamps a `(line, column)` position onto an existing buffer position.
176    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    /// Builds an edit replacing `start..end` on a single line with `text`.
188    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        // The shape servers use for "the very end of the document".
211        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        // Both ranges describe the document as it stands *before* either edit,
294        // so applying the first must not shift the second.
295        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        // The document shrinks to a single line under the cursor's position.
342        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}