Skip to main content

iced_code_editor/canvas_editor/lsp/
sync.rs

1//! LSP synchronization for [`CodeEditor`]: attaching/detaching a client,
2//! tracking buffer edits as queued `didChange` notifications, and issuing
3//! hover/completion/definition requests.
4
5use crate::buffer::TextBuffer;
6use crate::canvas_editor::CodeEditor;
7use crate::canvas_editor::lsp;
8
9impl CodeEditor {
10    /// Attaches an LSP client and opens a document for the current buffer.
11    ///
12    /// This sends an initial `did_open` with the current buffer contents and
13    /// resets any pending LSP change state.
14    ///
15    /// # Arguments
16    ///
17    /// * `client` - The LSP client to notify
18    /// * `document` - Document metadata describing the buffer
19    pub fn attach_lsp(
20        &mut self,
21        mut client: Box<dyn lsp::LspClient>,
22        document: lsp::LspDocument,
23    ) {
24        if !self.lsp_enabled {
25            return;
26        }
27        let (document, text) =
28            open_lsp_document(client.as_mut(), &self.buffer, document);
29        self.lsp_client = Some(client);
30        self.lsp_document = Some(document);
31        self.reset_lsp_shadow_state(text);
32    }
33
34    /// Opens a new document on the attached LSP client.
35    ///
36    /// If a document is already open, this will close it before opening the new
37    /// one and reset pending change tracking.
38    ///
39    /// # Arguments
40    ///
41    /// * `document` - Document metadata describing the buffer
42    pub fn lsp_open_document(&mut self, document: lsp::LspDocument) {
43        let Some(client) = self.lsp_client.as_mut() else { return };
44        if let Some(current) = self.lsp_document.as_ref() {
45            client.did_close(current);
46        }
47        let (document, text) =
48            open_lsp_document(client.as_mut(), &self.buffer, document);
49        self.lsp_document = Some(document);
50        self.reset_lsp_shadow_state(text);
51    }
52
53    /// Resets LSP shadow-sync bookkeeping after (re)opening a document whose
54    /// buffer contents are `text`.
55    fn reset_lsp_shadow_state(&mut self, text: String) {
56        self.lsp_shadow_text = text;
57        self.lsp_shadow_is_current = true;
58        self.update_lsp_synced_extent();
59        self.lsp_edit_snapshot = None;
60        self.lsp_pending_changes.clear();
61    }
62
63    /// Runs `f` with the attached LSP client and document, if both are
64    /// present. Returns `None` (without calling `f`) if either is absent.
65    ///
66    /// `f` receives only `client`/`document`, not `&mut self`, so callers
67    /// needing other `self` state (e.g. `self.buffer`) must compute it
68    /// before calling this helper and move it into the closure.
69    fn with_lsp<R>(
70        &mut self,
71        f: impl FnOnce(&mut dyn lsp::LspClient, &lsp::LspDocument) -> R,
72    ) -> Option<R> {
73        let client = self.lsp_client.as_deref_mut()?;
74        let document = self.lsp_document.as_ref()?;
75        Some(f(client, document))
76    }
77
78    /// Like [`Self::with_lsp`], but gives `f` a mutable reference to the
79    /// document (needed to bump `document.version`).
80    fn with_lsp_mut_document<R>(
81        &mut self,
82        f: impl FnOnce(&mut dyn lsp::LspClient, &mut lsp::LspDocument) -> R,
83    ) -> Option<R> {
84        let client = self.lsp_client.as_deref_mut()?;
85        let document = self.lsp_document.as_mut()?;
86        Some(f(client, document))
87    }
88
89    /// Detaches the current LSP client and closes any open document.
90    ///
91    /// This clears all LSP-related state on the editor instance.
92    pub fn detach_lsp(&mut self) {
93        self.with_lsp(|client, document| client.did_close(document));
94        self.lsp_client = None;
95        self.lsp_document = None;
96        self.lsp_shadow_text = String::new();
97        self.lsp_shadow_is_current = true;
98        self.lsp_synced_line_count = 1;
99        self.lsp_synced_last_line_len = 0;
100        self.lsp_edit_snapshot = None;
101        self.lsp_pending_changes.clear();
102    }
103
104    /// Sends a `did_save` notification with the current buffer contents.
105    pub fn lsp_did_save(&mut self) {
106        // Skip serializing the whole buffer when no client/document is
107        // attached: `with_lsp` would just discard the closure unused, but the
108        // full-document `to_string()` allocation would still happen on every
109        // save for hosts that never enable LSP.
110        if self.lsp_client.is_none() || self.lsp_document.is_none() {
111            return;
112        }
113        let text = self.buffer.to_string();
114        self.with_lsp(|client, document| client.did_save(document, &text));
115    }
116
117    /// Requests hover information at the current cursor position.
118    pub fn lsp_request_hover(&mut self) {
119        let position = self.lsp_position_from_cursor();
120        self.with_lsp(|client, document| {
121            client.request_hover(document, position);
122        });
123    }
124
125    /// Requests hover information at a canvas point.
126    ///
127    /// Returns `true` if the point maps to a valid buffer position and the
128    /// request was sent.
129    pub fn lsp_request_hover_at(&mut self, point: iced::Point) -> bool {
130        let Some(position) = self.lsp_position_from_point(point) else {
131            return false;
132        };
133        self.with_lsp(|client, document| {
134            client.request_hover(document, position);
135        })
136        .is_some()
137    }
138
139    /// Requests hover information at an explicit LSP position.
140    ///
141    /// Returns `true` if an LSP client is attached and the request was sent.
142    pub fn lsp_request_hover_at_position(
143        &mut self,
144        position: lsp::LspPosition,
145    ) -> bool {
146        self.with_lsp(|client, document| {
147            client.request_hover(document, position);
148        })
149        .is_some()
150    }
151
152    /// Converts a canvas point to an LSP position, if possible.
153    pub fn lsp_position_at_point(
154        &self,
155        point: iced::Point,
156    ) -> Option<lsp::LspPosition> {
157        self.lsp_position_from_point(point)
158    }
159
160    /// Returns the hover anchor position and its canvas point for a given
161    /// cursor location.
162    ///
163    /// The anchor is the start of the word under the cursor, which is useful
164    /// for LSP hover and definition requests.
165    pub fn lsp_hover_anchor_at_point(
166        &self,
167        point: iced::Point,
168    ) -> Option<(lsp::LspPosition, iced::Point)> {
169        let (line, col) = self.calculate_cursor_from_point(point)?;
170        let line_content = self.buffer.line(line);
171        let anchor_col = Self::word_start_in_line(line_content, col);
172        let anchor_point =
173            self.point_from_position(line, anchor_col).unwrap_or(point);
174        let line = u32::try_from(line).unwrap_or(u32::MAX);
175        let character = u32::try_from(anchor_col).unwrap_or(u32::MAX);
176        Some((lsp::LspPosition { line, character }, anchor_point))
177    }
178
179    /// Requests completion items at the current cursor position.
180    pub fn lsp_request_completion(&mut self) {
181        let position = self.lsp_position_from_cursor();
182        self.with_lsp(|client, document| {
183            client.request_completion(document, position);
184        });
185    }
186
187    /// Flushes pending LSP text changes to the attached client.
188    ///
189    /// This increments the document version and sends `did_change` with all
190    /// queued changes.
191    pub fn lsp_flush_pending_changes(&mut self) {
192        if self.lsp_pending_changes.is_empty() {
193            return;
194        }
195        // Only drain the queue once a client and document are confirmed
196        // attached — otherwise the changes must stay queued for a future
197        // `attach_lsp`/`lsp_open_document` flush.
198        if self.lsp_client.is_none() || self.lsp_document.is_none() {
199            return;
200        }
201
202        let changes = std::mem::take(&mut self.lsp_pending_changes);
203        self.with_lsp_mut_document(|client, document| {
204            document.version = document.version.saturating_add(1);
205            client.did_change(document, &changes);
206        });
207    }
208
209    /// Sets whether LSP changes are flushed automatically after edits.
210    pub fn set_lsp_auto_flush(&mut self, auto_flush: bool) {
211        self.lsp_auto_flush = auto_flush;
212    }
213
214    /// Converts the current cursor position into an LSP position.
215    fn lsp_position_from_cursor(&self) -> lsp::LspPosition {
216        let pos = self.cursors.primary_position();
217        let line = u32::try_from(pos.0).unwrap_or(u32::MAX);
218        let character = u32::try_from(pos.1).unwrap_or(u32::MAX);
219        lsp::LspPosition { line, character }
220    }
221
222    /// Converts a canvas point into an LSP position, if it hits the buffer.
223    fn lsp_position_from_point(
224        &self,
225        point: iced::Point,
226    ) -> Option<lsp::LspPosition> {
227        let (line, col) = self.calculate_cursor_from_point(point)?;
228        let line = u32::try_from(line).unwrap_or(u32::MAX);
229        let character = u32::try_from(col).unwrap_or(u32::MAX);
230        Some(lsp::LspPosition { line, character })
231    }
232
233    /// Computes and queues the latest LSP text change for the buffer.
234    ///
235    /// When auto-flush is enabled, this immediately sends changes.
236    pub(crate) fn enqueue_lsp_change(&mut self) {
237        if self.lsp_document.is_none() {
238            return;
239        }
240
241        let new_text = self.buffer.to_string();
242        let change = if self.lsp_shadow_is_current {
243            lsp::compute_text_change(&self.lsp_shadow_text, &new_text)
244        } else {
245            let end_line = self.lsp_synced_line_count.saturating_sub(1);
246            Some(lsp::LspTextChange {
247                range: lsp::LspRange {
248                    start: lsp::LspPosition { line: 0, character: 0 },
249                    end: lsp::LspPosition {
250                        line: u32::try_from(end_line).unwrap_or(u32::MAX),
251                        character: u32::try_from(self.lsp_synced_last_line_len)
252                            .unwrap_or(u32::MAX),
253                    },
254                },
255                text: new_text.clone(),
256            })
257        };
258        if let Some(change) = change {
259            self.lsp_pending_changes.push(change);
260        }
261        self.lsp_shadow_text = new_text;
262        self.lsp_shadow_is_current = true;
263        self.update_lsp_synced_extent();
264        if self.lsp_auto_flush {
265            self.lsp_flush_pending_changes();
266        }
267    }
268
269    /// Queues the bounded range replacement captured before a normal editor
270    /// command. Unlike `enqueue_lsp_change`, this never serializes or diffs the
271    /// complete document.
272    pub(crate) fn enqueue_incremental_lsp_change(&mut self) {
273        if self.lsp_document.is_none() {
274            self.lsp_edit_snapshot = None;
275            return;
276        }
277
278        let Some(snapshot) = self.lsp_edit_snapshot.take() else {
279            self.enqueue_lsp_change();
280            return;
281        };
282
283        let new_line_count = self.buffer.line_count();
284        let start_line =
285            snapshot.start_line.min(new_line_count.saturating_sub(1));
286        let new_end_exclusive = if new_line_count >= snapshot.old_line_count {
287            snapshot
288                .old_end_exclusive
289                .saturating_add(new_line_count - snapshot.old_line_count)
290                .min(new_line_count)
291        } else {
292            snapshot
293                .old_end_exclusive
294                .saturating_sub(snapshot.old_line_count - new_line_count)
295                .max(start_line.saturating_add(1))
296                .min(new_line_count)
297        };
298        let text =
299            self.buffer.line_range_to_string(start_line, new_end_exclusive);
300        self.lsp_pending_changes.push(lsp::LspTextChange {
301            range: lsp::LspRange {
302                start: lsp::LspPosition {
303                    line: u32::try_from(snapshot.start_line)
304                        .unwrap_or(u32::MAX),
305                    character: 0,
306                },
307                end: snapshot.old_end,
308            },
309            text,
310        });
311
312        // The shadow string is intentionally not rewritten here: doing so
313        // would reintroduce an O(document size) copy. The compact extent below
314        // is sufficient for a rare future full-document fallback.
315        self.lsp_shadow_text = String::new();
316        self.lsp_shadow_is_current = false;
317        self.update_lsp_synced_extent();
318        if self.lsp_auto_flush {
319            self.lsp_flush_pending_changes();
320        }
321    }
322
323    /// Updates the compact extent of the document state represented by queued
324    /// and already-flushed LSP changes.
325    fn update_lsp_synced_extent(&mut self) {
326        self.lsp_synced_line_count = self.buffer.line_count();
327        self.lsp_synced_last_line_len =
328            self.buffer.line_len(self.lsp_synced_line_count.saturating_sub(1));
329    }
330
331    /// Sets whether LSP support is enabled.
332    ///
333    /// When set to `false`, any attached LSP client is detached automatically.
334    /// Calling [`attach_lsp`] while disabled is a no-op.
335    ///
336    /// # Example
337    ///
338    /// ```
339    /// use iced_code_editor::CodeEditor;
340    ///
341    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
342    /// editor.set_lsp_enabled(false);
343    /// ```
344    ///
345    /// [`attach_lsp`]: CodeEditor::attach_lsp
346    pub fn set_lsp_enabled(&mut self, enabled: bool) {
347        self.lsp_enabled = enabled;
348        if !enabled {
349            self.detach_lsp();
350        }
351    }
352
353    /// Returns whether LSP support is enabled.
354    ///
355    /// `true` if LSP is enabled, `false` otherwise
356    pub fn lsp_enabled(&self) -> bool {
357        self.lsp_enabled
358    }
359
360    /// Initiates a "Go to Definition" request for the symbol at the current cursor position.
361    ///
362    /// This method converts the current cursor coordinates into an LSP-compatible position
363    /// and delegates the request to the active `LspClient`, if one is attached.
364    pub fn lsp_request_definition(&mut self) {
365        let position = self.lsp_position_from_cursor();
366        self.with_lsp(|client, document| {
367            client.request_definition(document, position);
368        });
369    }
370
371    /// Initiates a "Go to Definition" request for the symbol at the specified screen coordinates.
372    ///
373    /// This is typically used for mouse interactions (e.g., Ctrl+Click). It first resolves
374    /// the screen coordinates to a text position and then sends the request.
375    ///
376    /// # Returns
377    ///
378    /// `true` if the request was successfully sent (i.e., a valid position was found and an LSP client is active),
379    /// `false` otherwise.
380    pub fn lsp_request_definition_at(&mut self, point: iced::Point) -> bool {
381        let Some(position) = self.lsp_position_from_point(point) else {
382            return false;
383        };
384        self.with_lsp(|client, document| {
385            client.request_definition(document, position);
386        })
387        .is_some()
388    }
389}
390
391/// Sends `did_open` for `document` (after stamping `version = 1`) on
392/// `client`, using `buffer`'s current contents.
393///
394/// Returns the stamped document and the serialized buffer text, both needed
395/// by the caller to update its LSP shadow-sync bookkeeping.
396///
397/// Free function (not a method) so callers can hold a mutable borrow of
398/// `self.lsp_client` while still passing `&self.buffer` — a method taking
399/// `&mut self` here would conflict with that borrow in `lsp_open_document`.
400fn open_lsp_document(
401    client: &mut dyn lsp::LspClient,
402    buffer: &TextBuffer,
403    mut document: lsp::LspDocument,
404) -> (lsp::LspDocument, String) {
405    document.version = 1;
406    let text = buffer.to_string();
407    client.did_open(&document, &text);
408    (document, text)
409}
410
411#[cfg(test)]
412mod tests {
413    use std::cell::RefCell;
414    use std::rc::Rc;
415
416    use crate::canvas_editor::Message;
417
418    use super::*;
419
420    #[derive(Default)]
421    struct TestLspClient {
422        changes: Rc<RefCell<Vec<Vec<lsp::LspTextChange>>>>,
423    }
424
425    impl lsp::LspClient for TestLspClient {
426        fn did_change(
427            &mut self,
428            _document: &lsp::LspDocument,
429            changes: &[lsp::LspTextChange],
430        ) {
431            self.changes.borrow_mut().push(changes.to_vec());
432        }
433    }
434
435    /// Records every [`lsp::LspClient`] method invoked on it, by name.
436    #[derive(Default)]
437    struct RecordingLspClient {
438        calls: Rc<RefCell<Vec<String>>>,
439    }
440
441    impl lsp::LspClient for RecordingLspClient {
442        fn did_open(&mut self, _document: &lsp::LspDocument, _text: &str) {
443            self.calls.borrow_mut().push("did_open".to_string());
444        }
445        fn did_close(&mut self, _document: &lsp::LspDocument) {
446            self.calls.borrow_mut().push("did_close".to_string());
447        }
448        fn did_save(&mut self, _document: &lsp::LspDocument, _text: &str) {
449            self.calls.borrow_mut().push("did_save".to_string());
450        }
451        fn request_hover(
452            &mut self,
453            _document: &lsp::LspDocument,
454            _position: lsp::LspPosition,
455        ) {
456            self.calls.borrow_mut().push("request_hover".to_string());
457        }
458        fn did_change(
459            &mut self,
460            _document: &lsp::LspDocument,
461            _changes: &[lsp::LspTextChange],
462        ) {
463            self.calls.borrow_mut().push("did_change".to_string());
464        }
465    }
466
467    #[test]
468    fn test_enqueue_lsp_change_auto_flush() {
469        let changes = Rc::new(RefCell::new(Vec::new()));
470        let client = TestLspClient { changes: Rc::clone(&changes) };
471        let mut editor = CodeEditor::new("hello", "rs");
472        editor.attach_lsp(
473            Box::new(client),
474            lsp::LspDocument::new("file:///test.rs", "rust"),
475        );
476        editor.set_lsp_auto_flush(true);
477
478        editor.buffer.insert_char(0, 5, '!');
479        editor.enqueue_lsp_change();
480
481        let changes = changes.borrow();
482        assert_eq!(changes.len(), 1);
483        assert_eq!(changes[0].len(), 1);
484        let change = &changes[0][0];
485        assert_eq!(change.text, "!");
486        assert_eq!(change.range.start.line, 0);
487        assert_eq!(change.range.start.character, 5);
488        assert_eq!(change.range.end.line, 0);
489        assert_eq!(change.range.end.character, 5);
490    }
491
492    #[test]
493    fn test_editor_update_sends_bounded_incremental_lsp_change() {
494        let changes = Rc::new(RefCell::new(Vec::new()));
495        let client = TestLspClient { changes: Rc::clone(&changes) };
496        let content = (0..10)
497            .map(|line| format!("line{line}"))
498            .collect::<Vec<_>>()
499            .join("\n");
500        let mut editor = CodeEditor::new(&content, "rs");
501        editor.attach_lsp(
502            Box::new(client),
503            lsp::LspDocument::new("file:///large.rs", "rust"),
504        );
505        editor.request_focus();
506        editor.has_canvas_focus = true;
507        editor.focus_locked = false;
508        editor.cursors.primary_mut().position = (5, 2);
509
510        let _ = editor.update(&Message::CharacterInput('X'));
511
512        let changes = changes.borrow();
513        assert_eq!(changes.len(), 1);
514        assert_eq!(changes[0].len(), 1);
515        let change = &changes[0][0];
516        assert_eq!(change.range.start.line, 4);
517        assert_eq!(change.range.start.character, 0);
518        assert_eq!(change.range.end.line, 7);
519        assert_eq!(change.range.end.character, 0);
520        assert_eq!(change.text, "line4\nliXne5\nline6\n");
521        assert!(!editor.lsp_shadow_is_current);
522        assert!(editor.lsp_shadow_text.is_empty());
523    }
524
525    #[test]
526    fn test_open_lsp_document_stamps_version_and_sends_did_open() {
527        let calls = Rc::new(RefCell::new(Vec::new()));
528        let mut client = RecordingLspClient { calls: Rc::clone(&calls) };
529        let buffer = TextBuffer::new("hello");
530        let document = lsp::LspDocument::new("file:///test.rs", "rust");
531
532        let (document, text) =
533            open_lsp_document(&mut client, &buffer, document);
534
535        assert_eq!(document.version, 1);
536        assert_eq!(text, "hello");
537        assert_eq!(calls.borrow().as_slice(), ["did_open"]);
538    }
539
540    #[test]
541    fn test_with_lsp_runs_closure_when_client_and_document_present() {
542        let calls = Rc::new(RefCell::new(Vec::new()));
543        let client = RecordingLspClient { calls: Rc::clone(&calls) };
544        let mut editor = CodeEditor::new("hello", "rs");
545        editor.attach_lsp(
546            Box::new(client),
547            lsp::LspDocument::new("file:///test.rs", "rust"),
548        );
549        calls.borrow_mut().clear(); // attach_lsp itself already logged did_open
550
551        let ran = editor.with_lsp(|client, document| {
552            client.did_save(document, "hello");
553        });
554
555        assert!(ran.is_some());
556        assert_eq!(calls.borrow().as_slice(), ["did_save"]);
557    }
558
559    #[test]
560    fn test_with_lsp_returns_none_when_client_absent() {
561        let mut editor = CodeEditor::new("hello", "rs");
562        let ran = editor.with_lsp(|_client, _document| {});
563        assert!(ran.is_none());
564    }
565
566    #[test]
567    fn test_lsp_did_save_sends_current_buffer_contents() {
568        let calls = Rc::new(RefCell::new(Vec::new()));
569        let client = RecordingLspClient { calls: Rc::clone(&calls) };
570        let mut editor = CodeEditor::new("hello", "rs");
571        editor.attach_lsp(
572            Box::new(client),
573            lsp::LspDocument::new("file:///test.rs", "rust"),
574        );
575        calls.borrow_mut().clear(); // attach_lsp itself already logged did_open
576
577        editor.lsp_did_save();
578
579        assert_eq!(calls.borrow().as_slice(), ["did_save"]);
580    }
581
582    #[test]
583    fn test_lsp_did_save_is_a_noop_without_an_attached_client() {
584        // Regression: this used to serialize the whole buffer via
585        // `to_string()` even with no client/document attached.
586        let mut editor = CodeEditor::new("hello", "rs");
587        editor.lsp_did_save(); // must not panic
588    }
589
590    #[test]
591    fn test_with_lsp_returns_none_when_document_absent() {
592        let calls = Rc::new(RefCell::new(Vec::new()));
593        let client = RecordingLspClient { calls: Rc::clone(&calls) };
594        let mut editor = CodeEditor::new("hello", "rs");
595        editor.attach_lsp(
596            Box::new(client),
597            lsp::LspDocument::new("file:///test.rs", "rust"),
598        );
599        editor.lsp_document = None;
600
601        let ran = editor.with_lsp(|_client, _document| {});
602        assert!(ran.is_none());
603    }
604
605    #[test]
606    #[allow(clippy::unwrap_used)]
607    fn test_with_lsp_mut_document_allows_version_bump() {
608        let calls = Rc::new(RefCell::new(Vec::new()));
609        let client = RecordingLspClient { calls: Rc::clone(&calls) };
610        let mut editor = CodeEditor::new("hello", "rs");
611        editor.attach_lsp(
612            Box::new(client),
613            lsp::LspDocument::new("file:///test.rs", "rust"),
614        );
615
616        editor.with_lsp_mut_document(|_client, document| {
617            document.version = document.version.saturating_add(1);
618        });
619
620        assert_eq!(editor.lsp_document.as_ref().unwrap().version, 2);
621    }
622
623    #[test]
624    fn test_lsp_flush_pending_changes_preserves_queue_when_no_client_attached()
625    {
626        let mut editor = CodeEditor::new("hello", "rs");
627        editor.lsp_pending_changes.push(lsp::LspTextChange {
628            range: lsp::LspRange {
629                start: lsp::LspPosition { line: 0, character: 0 },
630                end: lsp::LspPosition { line: 0, character: 0 },
631            },
632            text: "x".to_string(),
633        });
634
635        editor.lsp_flush_pending_changes();
636
637        assert_eq!(editor.lsp_pending_changes.len(), 1);
638    }
639}