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. It is a no-op while LSP support is
14    /// disabled — see [`Self::set_lsp_enabled`].
15    ///
16    /// # Arguments
17    ///
18    /// * `client` - The LSP client to notify
19    /// * `document` - Document metadata describing the buffer
20    ///
21    /// # Example
22    ///
23    /// ```
24    /// use std::cell::RefCell;
25    /// use std::rc::Rc;
26    ///
27    /// use iced_code_editor::{CodeEditor, LspClient, LspDocument};
28    ///
29    /// /// Records the text the editor sent on `did_open`.
30    /// struct RecordingClient(Rc<RefCell<Option<String>>>);
31    ///
32    /// impl LspClient for RecordingClient {
33    ///     fn did_open(&mut self, _document: &LspDocument, text: &str) {
34    ///         *self.0.borrow_mut() = Some(text.to_string());
35    ///     }
36    /// }
37    ///
38    /// let opened = Rc::new(RefCell::new(None));
39    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
40    /// editor.attach_lsp(
41    ///     Box::new(RecordingClient(Rc::clone(&opened))),
42    ///     LspDocument::new("file:///tmp/main.rs", "rust"),
43    /// );
44    ///
45    /// // Attaching opens the document with the buffer's current contents.
46    /// assert_eq!(opened.borrow().as_deref(), Some("fn main() {}"));
47    /// ```
48    pub fn attach_lsp(
49        &mut self,
50        mut client: Box<dyn lsp::LspClient>,
51        document: lsp::LspDocument,
52    ) {
53        if !self.lsp_enabled {
54            return;
55        }
56        let (document, text) =
57            open_lsp_document(client.as_mut(), &self.buffer, document);
58        self.lsp_client = Some(client);
59        self.lsp_document = Some(document);
60        self.reset_lsp_shadow_state(text);
61    }
62
63    /// Opens a new document on the attached LSP client.
64    ///
65    /// If a document is already open, this will close it before opening the new
66    /// one and reset pending change tracking. Use this when the same editor
67    /// widget is reused for a different file, so the server is told about the
68    /// swap rather than seeing the old document mutate into the new one.
69    ///
70    /// Does nothing when no client is attached.
71    ///
72    /// # Arguments
73    ///
74    /// * `document` - Document metadata describing the buffer
75    ///
76    /// # Example
77    ///
78    /// ```
79    /// use std::cell::RefCell;
80    /// use std::rc::Rc;
81    ///
82    /// use iced_code_editor::{CodeEditor, LspClient, LspDocument};
83    ///
84    /// /// Records the URIs the editor closed.
85    /// struct ClosingClient(Rc<RefCell<Vec<String>>>);
86    ///
87    /// impl LspClient for ClosingClient {
88    ///     fn did_close(&mut self, document: &LspDocument) {
89    ///         self.0.borrow_mut().push(document.uri.clone());
90    ///     }
91    /// }
92    ///
93    /// let closed = Rc::new(RefCell::new(Vec::new()));
94    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
95    /// editor.attach_lsp(
96    ///     Box::new(ClosingClient(Rc::clone(&closed))),
97    ///     LspDocument::new("file:///tmp/first.rs", "rust"),
98    /// );
99    ///
100    /// // Switching files closes the previous document first.
101    /// editor.lsp_open_document(LspDocument::new("file:///tmp/second.rs", "rust"));
102    /// assert_eq!(closed.borrow().as_slice(), ["file:///tmp/first.rs"]);
103    /// ```
104    pub fn lsp_open_document(&mut self, document: lsp::LspDocument) {
105        let Some(client) = self.lsp_client.as_mut() else { return };
106        if let Some(current) = self.lsp_document.as_ref() {
107            client.did_close(current);
108        }
109        let (document, text) =
110            open_lsp_document(client.as_mut(), &self.buffer, document);
111        self.lsp_document = Some(document);
112        self.reset_lsp_shadow_state(text);
113    }
114
115    /// Resets LSP shadow-sync bookkeeping after (re)opening a document whose
116    /// buffer contents are `text`.
117    fn reset_lsp_shadow_state(&mut self, text: String) {
118        self.lsp_shadow_text = text;
119        self.lsp_shadow_is_current = true;
120        self.update_lsp_synced_extent();
121        self.lsp_edit_snapshot = None;
122        self.lsp_pending_changes.clear();
123    }
124
125    /// Runs `f` with the attached LSP client and document, if both are
126    /// present. Returns `None` (without calling `f`) if either is absent.
127    ///
128    /// `f` receives only `client`/`document`, not `&mut self`, so callers
129    /// needing other `self` state (e.g. `self.buffer`) must compute it
130    /// before calling this helper and move it into the closure.
131    fn with_lsp<R>(
132        &mut self,
133        f: impl FnOnce(&mut dyn lsp::LspClient, &lsp::LspDocument) -> R,
134    ) -> Option<R> {
135        let client = self.lsp_client.as_deref_mut()?;
136        let document = self.lsp_document.as_ref()?;
137        Some(f(client, document))
138    }
139
140    /// Like [`Self::with_lsp`], but gives `f` a mutable reference to the
141    /// document (needed to bump `document.version`).
142    fn with_lsp_mut_document<R>(
143        &mut self,
144        f: impl FnOnce(&mut dyn lsp::LspClient, &mut lsp::LspDocument) -> R,
145    ) -> Option<R> {
146        let client = self.lsp_client.as_deref_mut()?;
147        let document = self.lsp_document.as_mut()?;
148        Some(f(client, document))
149    }
150
151    /// Detaches the current LSP client and closes any open document.
152    ///
153    /// This clears all LSP-related state on the editor instance, including any
154    /// changes queued but not yet flushed. Safe to call when nothing is
155    /// attached.
156    ///
157    /// # Example
158    ///
159    /// ```
160    /// use std::cell::RefCell;
161    /// use std::rc::Rc;
162    ///
163    /// use iced_code_editor::{CodeEditor, LspClient, LspDocument};
164    ///
165    /// /// Records whether the document was closed.
166    /// struct ClosingClient(Rc<RefCell<bool>>);
167    ///
168    /// impl LspClient for ClosingClient {
169    ///     fn did_close(&mut self, _document: &LspDocument) {
170    ///         *self.0.borrow_mut() = true;
171    ///     }
172    /// }
173    ///
174    /// let closed = Rc::new(RefCell::new(false));
175    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
176    /// editor.attach_lsp(
177    ///     Box::new(ClosingClient(Rc::clone(&closed))),
178    ///     LspDocument::new("file:///tmp/main.rs", "rust"),
179    /// );
180    ///
181    /// editor.detach_lsp();
182    /// assert!(*closed.borrow());
183    ///
184    /// // Detaching again is harmless.
185    /// editor.detach_lsp();
186    /// ```
187    pub fn detach_lsp(&mut self) {
188        self.with_lsp(|client, document| client.did_close(document));
189        self.lsp_client = None;
190        self.lsp_document = None;
191        self.lsp_shadow_text = String::new();
192        self.lsp_shadow_is_current = true;
193        self.lsp_synced_line_count = 1;
194        self.lsp_synced_last_line_len = 0;
195        self.lsp_edit_snapshot = None;
196        self.lsp_pending_changes.clear();
197    }
198
199    /// Sends a `did_save` notification with the current buffer contents.
200    ///
201    /// Call this after the host application has written the file to disk, so
202    /// servers that re-run diagnostics or formatting on save see the new state.
203    /// Does nothing when no client and document are attached.
204    ///
205    /// # Example
206    ///
207    /// ```
208    /// use std::cell::RefCell;
209    /// use std::rc::Rc;
210    ///
211    /// use iced_code_editor::{CodeEditor, LspClient, LspDocument};
212    ///
213    /// /// Records the text sent on save.
214    /// struct SavingClient(Rc<RefCell<Option<String>>>);
215    ///
216    /// impl LspClient for SavingClient {
217    ///     fn did_save(&mut self, _document: &LspDocument, text: &str) {
218    ///         *self.0.borrow_mut() = Some(text.to_string());
219    ///     }
220    /// }
221    ///
222    /// let saved = Rc::new(RefCell::new(None));
223    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
224    /// editor.attach_lsp(
225    ///     Box::new(SavingClient(Rc::clone(&saved))),
226    ///     LspDocument::new("file:///tmp/main.rs", "rust"),
227    /// );
228    ///
229    /// editor.lsp_did_save();
230    /// assert_eq!(saved.borrow().as_deref(), Some("fn main() {}"));
231    /// ```
232    pub fn lsp_did_save(&mut self) {
233        // Skip serializing the whole buffer when no client/document is
234        // attached: `with_lsp` would just discard the closure unused, but the
235        // full-document `to_string()` allocation would still happen on every
236        // save for hosts that never enable LSP.
237        if self.lsp_client.is_none() || self.lsp_document.is_none() {
238            return;
239        }
240        let text = self.buffer.to_string();
241        self.with_lsp(|client, document| client.did_save(document, &text));
242    }
243
244    /// Requests hover information at the current cursor position.
245    ///
246    /// The request is fire-and-forget: the reply reaches the host through
247    /// whatever channel the [`LspClient`] implementation uses, not through a
248    /// return value. Does nothing when no client is attached.
249    ///
250    /// [`LspClient`]: crate::LspClient
251    ///
252    /// # Example
253    ///
254    /// ```
255    /// use std::cell::RefCell;
256    /// use std::rc::Rc;
257    ///
258    /// use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspPosition};
259    ///
260    /// /// Records the position each hover request asked about.
261    /// struct HoverClient(Rc<RefCell<Vec<LspPosition>>>);
262    ///
263    /// impl LspClient for HoverClient {
264    ///     fn request_hover(&mut self, _document: &LspDocument, position: LspPosition) {
265    ///         self.0.borrow_mut().push(position);
266    ///     }
267    /// }
268    ///
269    /// let hovers = Rc::new(RefCell::new(Vec::new()));
270    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
271    /// editor.attach_lsp(
272    ///     Box::new(HoverClient(Rc::clone(&hovers))),
273    ///     LspDocument::new("file:///tmp/main.rs", "rust"),
274    /// );
275    ///
276    /// editor.lsp_request_hover();
277    /// // The cursor starts at the top of the document.
278    /// assert_eq!(hovers.borrow().as_slice(), [LspPosition { line: 0, character: 0 }]);
279    /// ```
280    pub fn lsp_request_hover(&mut self) {
281        let position = self.lsp_position_from_cursor();
282        self.with_lsp(|client, document| {
283            client.request_hover(document, position);
284        });
285    }
286
287    /// Requests hover information at a canvas point.
288    ///
289    /// Use this to drive hover-on-mouse-move; [`Self::lsp_position_at_point`]
290    /// resolves the point first, so a point over the gutter sends nothing.
291    ///
292    /// # Arguments
293    ///
294    /// * `point` - The position in canvas coordinates
295    ///
296    /// # Returns
297    ///
298    /// `true` if the point maps to a valid buffer position and the request was
299    /// sent; `false` if it does not, or if no client is attached
300    ///
301    /// # Example
302    ///
303    /// ```
304    /// use iced::Point;
305    /// use iced_code_editor::CodeEditor;
306    ///
307    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
308    ///
309    /// // With no client attached there is nothing to send.
310    /// assert!(!editor.lsp_request_hover_at(Point::new(50.0, 5.0)));
311    /// ```
312    pub fn lsp_request_hover_at(&mut self, point: iced::Point) -> bool {
313        let Some(position) = self.lsp_position_from_point(point) else {
314            return false;
315        };
316        self.with_lsp(|client, document| {
317            client.request_hover(document, position);
318        })
319        .is_some()
320    }
321
322    /// Requests hover information at an explicit LSP position.
323    ///
324    /// Unlike [`Self::lsp_request_hover_at`], this skips point-to-position
325    /// resolution — pair it with a position previously obtained from
326    /// [`Self::lsp_hover_anchor_at_point`] so a hover that lingers stays
327    /// anchored to the word rather than following the mouse.
328    ///
329    /// # Arguments
330    ///
331    /// * `position` - The zero-based document position to query
332    ///
333    /// # Returns
334    ///
335    /// `true` if a client is attached and the request was sent, `false` otherwise
336    ///
337    /// # Example
338    ///
339    /// ```
340    /// use iced_code_editor::{CodeEditor, LspPosition};
341    ///
342    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
343    /// let position = LspPosition { line: 0, character: 3 };
344    ///
345    /// // With no client attached there is nothing to send.
346    /// assert!(!editor.lsp_request_hover_at_position(position));
347    /// ```
348    pub fn lsp_request_hover_at_position(
349        &mut self,
350        position: lsp::LspPosition,
351    ) -> bool {
352        self.with_lsp(|client, document| {
353            client.request_hover(document, position);
354        })
355        .is_some()
356    }
357
358    /// Converts a canvas point to an LSP position, if possible.
359    ///
360    /// Requires no attached client — this is pure hit-testing against the
361    /// editor's current layout.
362    ///
363    /// # Arguments
364    ///
365    /// * `point` - The position in canvas coordinates
366    ///
367    /// # Returns
368    ///
369    /// `Some(position)` when the point falls on text, `None` when it lands in
370    /// the gutter
371    ///
372    /// # Example
373    ///
374    /// ```
375    /// use iced::Point;
376    /// use iced_code_editor::CodeEditor;
377    ///
378    /// let editor = CodeEditor::new("fn main() {}", "rs");
379    ///
380    /// // The origin sits in the line-number gutter, which maps to nothing.
381    /// assert!(editor.lsp_position_at_point(Point::ORIGIN).is_none());
382    ///
383    /// // A point past the end of the document clamps to its last position.
384    /// let position = editor
385    ///     .lsp_position_at_point(Point::new(5_000.0, 5_000.0))
386    ///     .expect("a point past the text clamps rather than failing");
387    /// assert_eq!(position.line, 0);
388    /// assert_eq!(position.character, 12);
389    /// ```
390    pub fn lsp_position_at_point(
391        &self,
392        point: iced::Point,
393    ) -> Option<lsp::LspPosition> {
394        self.lsp_position_from_point(point)
395    }
396
397    /// Returns the hover anchor position and its canvas point for a given
398    /// cursor location.
399    ///
400    /// The anchor is the start of the word under the cursor. Anchoring to the
401    /// word start rather than the exact mouse position keeps a hover popup from
402    /// jittering as the pointer moves within one identifier, and gives the host
403    /// a stable canvas point to position the popup against.
404    ///
405    /// # Arguments
406    ///
407    /// * `point` - The position in canvas coordinates
408    ///
409    /// # Returns
410    ///
411    /// `Some((position, anchor_point))` when the point falls on text, `None`
412    /// when it lands in the gutter
413    ///
414    /// # Example
415    ///
416    /// ```
417    /// use iced::Point;
418    /// use iced_code_editor::CodeEditor;
419    ///
420    /// let editor = CodeEditor::new("fn main() {}", "rs");
421    ///
422    /// // A gutter point has no word to anchor to.
423    /// assert!(editor.lsp_hover_anchor_at_point(Point::ORIGIN).is_none());
424    /// ```
425    pub fn lsp_hover_anchor_at_point(
426        &self,
427        point: iced::Point,
428    ) -> Option<(lsp::LspPosition, iced::Point)> {
429        let (line, col) = self.calculate_cursor_from_point(point)?;
430        let line_content = self.buffer.line(line);
431        let anchor_col = Self::word_start_in_line(line_content, col);
432        let anchor_point =
433            self.point_from_position(line, anchor_col).unwrap_or(point);
434        let line = u32::try_from(line).unwrap_or(u32::MAX);
435        let character = u32::try_from(anchor_col).unwrap_or(u32::MAX);
436        Some((lsp::LspPosition { line, character }, anchor_point))
437    }
438
439    /// Requests completion items at the current cursor position.
440    ///
441    /// Like the hover requests, this is fire-and-forget; the items arrive
442    /// through the [`LspClient`] implementation. Does nothing when no client is
443    /// attached.
444    ///
445    /// [`LspClient`]: crate::LspClient
446    ///
447    /// # Example
448    ///
449    /// ```
450    /// use std::cell::RefCell;
451    /// use std::rc::Rc;
452    ///
453    /// use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspPosition};
454    ///
455    /// /// Counts completion requests.
456    /// struct CompletionClient(Rc<RefCell<usize>>);
457    ///
458    /// impl LspClient for CompletionClient {
459    ///     fn request_completion(&mut self, _document: &LspDocument, _position: LspPosition) {
460    ///         *self.0.borrow_mut() += 1;
461    ///     }
462    /// }
463    ///
464    /// let requests = Rc::new(RefCell::new(0));
465    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
466    /// editor.attach_lsp(
467    ///     Box::new(CompletionClient(Rc::clone(&requests))),
468    ///     LspDocument::new("file:///tmp/main.rs", "rust"),
469    /// );
470    ///
471    /// editor.lsp_request_completion();
472    /// assert_eq!(*requests.borrow(), 1);
473    /// ```
474    pub fn lsp_request_completion(&mut self) {
475        let position = self.lsp_position_from_cursor();
476        self.with_lsp(|client, document| {
477            client.request_completion(document, position);
478        });
479    }
480
481    /// Flushes pending LSP text changes to the attached client.
482    ///
483    /// This increments the document version and sends `did_change` with all
484    /// queued changes. Changes stay queued while no client is attached, so a
485    /// client attached later still receives a consistent document.
486    ///
487    /// Only needed when automatic flushing is off; see
488    /// [`Self::set_lsp_auto_flush`].
489    ///
490    /// # Example
491    ///
492    /// ```
493    /// use std::cell::RefCell;
494    /// use std::rc::Rc;
495    ///
496    /// use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspTextChange};
497    ///
498    /// /// Records how many changes each batch carried.
499    /// struct BatchClient(Rc<RefCell<Vec<usize>>>);
500    ///
501    /// impl LspClient for BatchClient {
502    ///     fn did_change(&mut self, _document: &LspDocument, changes: &[LspTextChange]) {
503    ///         self.0.borrow_mut().push(changes.len());
504    ///     }
505    /// }
506    ///
507    /// let batches = Rc::new(RefCell::new(Vec::new()));
508    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
509    ///
510    /// // Take over flushing, then drive it from a debounce timer.
511    /// editor.set_lsp_auto_flush(false);
512    /// editor.attach_lsp(
513    ///     Box::new(BatchClient(Rc::clone(&batches))),
514    ///     LspDocument::new("file:///tmp/main.rs", "rust"),
515    /// );
516    ///
517    /// // Flushing an empty queue is a no-op, so a timer can call this
518    /// // unconditionally without sending empty notifications.
519    /// editor.lsp_flush_pending_changes();
520    /// assert!(batches.borrow().is_empty());
521    /// ```
522    pub fn lsp_flush_pending_changes(&mut self) {
523        if self.lsp_pending_changes.is_empty() {
524            return;
525        }
526        // Only drain the queue once a client and document are confirmed
527        // attached — otherwise the changes must stay queued for a future
528        // `attach_lsp`/`lsp_open_document` flush.
529        if self.lsp_client.is_none() || self.lsp_document.is_none() {
530            return;
531        }
532
533        let changes = std::mem::take(&mut self.lsp_pending_changes);
534        self.with_lsp_mut_document(|client, document| {
535            document.version = document.version.saturating_add(1);
536            client.did_change(document, &changes);
537        });
538    }
539
540    /// Sets whether LSP changes are flushed automatically after edits.
541    ///
542    /// On by default, which is what most hosts want. Turn it off to batch
543    /// rapid typing behind a debounce timer and call
544    /// [`Self::lsp_flush_pending_changes`] yourself, so a chatty server isn't
545    /// sent one notification per keystroke.
546    ///
547    /// # Arguments
548    ///
549    /// * `auto_flush` - `true` to flush after every edit, `false` to flush manually
550    ///
551    /// # Example
552    ///
553    /// ```
554    /// use iced_code_editor::CodeEditor;
555    ///
556    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
557    ///
558    /// // Take over flushing so edits can be debounced by the host.
559    /// editor.set_lsp_auto_flush(false);
560    /// ```
561    pub fn set_lsp_auto_flush(&mut self, auto_flush: bool) {
562        self.lsp_auto_flush = auto_flush;
563    }
564
565    /// Converts the current cursor position into an LSP position.
566    fn lsp_position_from_cursor(&self) -> lsp::LspPosition {
567        let pos = self.cursors.primary_position();
568        let line = u32::try_from(pos.0).unwrap_or(u32::MAX);
569        let character = u32::try_from(pos.1).unwrap_or(u32::MAX);
570        lsp::LspPosition { line, character }
571    }
572
573    /// Converts a canvas point into an LSP position, if it hits the buffer.
574    fn lsp_position_from_point(
575        &self,
576        point: iced::Point,
577    ) -> Option<lsp::LspPosition> {
578        let (line, col) = self.calculate_cursor_from_point(point)?;
579        let line = u32::try_from(line).unwrap_or(u32::MAX);
580        let character = u32::try_from(col).unwrap_or(u32::MAX);
581        Some(lsp::LspPosition { line, character })
582    }
583
584    /// Computes and queues the latest LSP text change for the buffer.
585    ///
586    /// When auto-flush is enabled, this immediately sends changes.
587    pub(crate) fn enqueue_lsp_change(&mut self) {
588        if self.lsp_document.is_none() {
589            return;
590        }
591
592        let new_text = self.buffer.to_string();
593        let change = if self.lsp_shadow_is_current {
594            lsp::compute_text_change(&self.lsp_shadow_text, &new_text)
595        } else {
596            let end_line = self.lsp_synced_line_count.saturating_sub(1);
597            Some(lsp::LspTextChange {
598                range: lsp::LspRange {
599                    start: lsp::LspPosition { line: 0, character: 0 },
600                    end: lsp::LspPosition {
601                        line: u32::try_from(end_line).unwrap_or(u32::MAX),
602                        character: u32::try_from(self.lsp_synced_last_line_len)
603                            .unwrap_or(u32::MAX),
604                    },
605                },
606                text: new_text.clone(),
607            })
608        };
609        if let Some(change) = change {
610            self.lsp_pending_changes.push(change);
611        }
612        self.lsp_shadow_text = new_text;
613        self.lsp_shadow_is_current = true;
614        self.update_lsp_synced_extent();
615        if self.lsp_auto_flush {
616            self.lsp_flush_pending_changes();
617        }
618    }
619
620    /// Queues the bounded range replacement captured before a normal editor
621    /// command. Unlike `enqueue_lsp_change`, this never serializes or diffs the
622    /// complete document.
623    pub(crate) fn enqueue_incremental_lsp_change(&mut self) {
624        if self.lsp_document.is_none() {
625            self.lsp_edit_snapshot = None;
626            return;
627        }
628
629        let Some(snapshot) = self.lsp_edit_snapshot.take() else {
630            self.enqueue_lsp_change();
631            return;
632        };
633
634        let new_line_count = self.buffer.line_count();
635        let start_line =
636            snapshot.start_line.min(new_line_count.saturating_sub(1));
637        let new_end_exclusive = if new_line_count >= snapshot.old_line_count {
638            snapshot
639                .old_end_exclusive
640                .saturating_add(new_line_count - snapshot.old_line_count)
641                .min(new_line_count)
642        } else {
643            snapshot
644                .old_end_exclusive
645                .saturating_sub(snapshot.old_line_count - new_line_count)
646                .max(start_line.saturating_add(1))
647                .min(new_line_count)
648        };
649        let text =
650            self.buffer.line_range_to_string(start_line, new_end_exclusive);
651        self.lsp_pending_changes.push(lsp::LspTextChange {
652            range: lsp::LspRange {
653                start: lsp::LspPosition {
654                    line: u32::try_from(snapshot.start_line)
655                        .unwrap_or(u32::MAX),
656                    character: 0,
657                },
658                end: snapshot.old_end,
659            },
660            text,
661        });
662
663        // The shadow string is intentionally not rewritten here: doing so
664        // would reintroduce an O(document size) copy. The compact extent below
665        // is sufficient for a rare future full-document fallback.
666        self.lsp_shadow_text = String::new();
667        self.lsp_shadow_is_current = false;
668        self.update_lsp_synced_extent();
669        if self.lsp_auto_flush {
670            self.lsp_flush_pending_changes();
671        }
672    }
673
674    /// Updates the compact extent of the document state represented by queued
675    /// and already-flushed LSP changes.
676    fn update_lsp_synced_extent(&mut self) {
677        self.lsp_synced_line_count = self.buffer.line_count();
678        self.lsp_synced_last_line_len =
679            self.buffer.line_len(self.lsp_synced_line_count.saturating_sub(1));
680    }
681
682    /// Sets whether LSP support is enabled.
683    ///
684    /// When set to `false`, any attached LSP client is detached automatically.
685    /// Calling [`attach_lsp`] while disabled is a no-op.
686    ///
687    /// # Example
688    ///
689    /// ```
690    /// use iced_code_editor::CodeEditor;
691    ///
692    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
693    /// editor.set_lsp_enabled(false);
694    /// ```
695    ///
696    /// [`attach_lsp`]: CodeEditor::attach_lsp
697    pub fn set_lsp_enabled(&mut self, enabled: bool) {
698        self.lsp_enabled = enabled;
699        if !enabled {
700            self.detach_lsp();
701        }
702    }
703
704    /// Returns whether LSP support is enabled.
705    ///
706    /// # Returns
707    ///
708    /// `true` if LSP is enabled, `false` otherwise
709    ///
710    /// # Example
711    ///
712    /// ```
713    /// use iced_code_editor::CodeEditor;
714    ///
715    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
716    /// // Enabled by default, though no client is attached until you attach one.
717    /// assert!(editor.lsp_enabled());
718    ///
719    /// editor.set_lsp_enabled(false);
720    /// assert!(!editor.lsp_enabled());
721    /// ```
722    pub fn lsp_enabled(&self) -> bool {
723        self.lsp_enabled
724    }
725
726    /// Initiates a "Go to Definition" request for the symbol at the current cursor position.
727    ///
728    /// This method converts the current cursor coordinates into an LSP-compatible position
729    /// and delegates the request to the active `LspClient`, if one is attached.
730    ///
731    /// Fire-and-forget: the resolved location arrives through the client
732    /// implementation, and the host decides whether to follow it.
733    ///
734    /// # Example
735    ///
736    /// ```
737    /// use std::cell::RefCell;
738    /// use std::rc::Rc;
739    ///
740    /// use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspPosition};
741    ///
742    /// /// Records the position each definition request asked about.
743    /// struct DefinitionClient(Rc<RefCell<Vec<LspPosition>>>);
744    ///
745    /// impl LspClient for DefinitionClient {
746    ///     fn request_definition(&mut self, _document: &LspDocument, position: LspPosition) {
747    ///         self.0.borrow_mut().push(position);
748    ///     }
749    /// }
750    ///
751    /// let requests = Rc::new(RefCell::new(Vec::new()));
752    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
753    /// editor.attach_lsp(
754    ///     Box::new(DefinitionClient(Rc::clone(&requests))),
755    ///     LspDocument::new("file:///tmp/main.rs", "rust"),
756    /// );
757    ///
758    /// editor.lsp_request_definition();
759    /// assert_eq!(requests.borrow().len(), 1);
760    /// ```
761    pub fn lsp_request_definition(&mut self) {
762        let position = self.lsp_position_from_cursor();
763        self.with_lsp(|client, document| {
764            client.request_definition(document, position);
765        });
766    }
767
768    /// Initiates a "Go to Definition" request for the symbol at the specified screen coordinates.
769    ///
770    /// This is typically used for mouse interactions (e.g., Ctrl+Click). It first resolves
771    /// the screen coordinates to a text position and then sends the request.
772    ///
773    /// # Arguments
774    ///
775    /// * `point` - The click position in canvas coordinates
776    ///
777    /// # Returns
778    ///
779    /// `true` if the request was successfully sent (i.e., a valid position was found and an LSP client is active),
780    /// `false` otherwise.
781    ///
782    /// # Example
783    ///
784    /// ```
785    /// use iced::Point;
786    /// use iced_code_editor::CodeEditor;
787    ///
788    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
789    ///
790    /// // With no client attached there is nothing to send.
791    /// assert!(!editor.lsp_request_definition_at(Point::new(50.0, 5.0)));
792    /// ```
793    pub fn lsp_request_definition_at(&mut self, point: iced::Point) -> bool {
794        let Some(position) = self.lsp_position_from_point(point) else {
795            return false;
796        };
797        self.with_lsp(|client, document| {
798            client.request_definition(document, position);
799        })
800        .is_some()
801    }
802}
803
804/// Sends `did_open` for `document` (after stamping `version = 1`) on
805/// `client`, using `buffer`'s current contents.
806///
807/// Returns the stamped document and the serialized buffer text, both needed
808/// by the caller to update its LSP shadow-sync bookkeeping.
809///
810/// Free function (not a method) so callers can hold a mutable borrow of
811/// `self.lsp_client` while still passing `&self.buffer` — a method taking
812/// `&mut self` here would conflict with that borrow in `lsp_open_document`.
813fn open_lsp_document(
814    client: &mut dyn lsp::LspClient,
815    buffer: &TextBuffer,
816    mut document: lsp::LspDocument,
817) -> (lsp::LspDocument, String) {
818    document.version = 1;
819    let text = buffer.to_string();
820    client.did_open(&document, &text);
821    (document, text)
822}
823
824#[cfg(test)]
825mod tests {
826    use std::cell::RefCell;
827    use std::rc::Rc;
828
829    use crate::canvas_editor::Message;
830
831    use super::*;
832
833    #[derive(Default)]
834    struct TestLspClient {
835        changes: Rc<RefCell<Vec<Vec<lsp::LspTextChange>>>>,
836    }
837
838    impl lsp::LspClient for TestLspClient {
839        fn did_change(
840            &mut self,
841            _document: &lsp::LspDocument,
842            changes: &[lsp::LspTextChange],
843        ) {
844            self.changes.borrow_mut().push(changes.to_vec());
845        }
846    }
847
848    /// Records every [`lsp::LspClient`] method invoked on it, by name.
849    #[derive(Default)]
850    struct RecordingLspClient {
851        calls: Rc<RefCell<Vec<String>>>,
852    }
853
854    impl lsp::LspClient for RecordingLspClient {
855        fn did_open(&mut self, _document: &lsp::LspDocument, _text: &str) {
856            self.calls.borrow_mut().push("did_open".to_string());
857        }
858        fn did_close(&mut self, _document: &lsp::LspDocument) {
859            self.calls.borrow_mut().push("did_close".to_string());
860        }
861        fn did_save(&mut self, _document: &lsp::LspDocument, _text: &str) {
862            self.calls.borrow_mut().push("did_save".to_string());
863        }
864        fn request_hover(
865            &mut self,
866            _document: &lsp::LspDocument,
867            _position: lsp::LspPosition,
868        ) {
869            self.calls.borrow_mut().push("request_hover".to_string());
870        }
871        fn did_change(
872            &mut self,
873            _document: &lsp::LspDocument,
874            _changes: &[lsp::LspTextChange],
875        ) {
876            self.calls.borrow_mut().push("did_change".to_string());
877        }
878    }
879
880    #[test]
881    fn test_enqueue_lsp_change_auto_flush() {
882        let changes = Rc::new(RefCell::new(Vec::new()));
883        let client = TestLspClient { changes: Rc::clone(&changes) };
884        let mut editor = CodeEditor::new("hello", "rs");
885        editor.attach_lsp(
886            Box::new(client),
887            lsp::LspDocument::new("file:///test.rs", "rust"),
888        );
889        editor.set_lsp_auto_flush(true);
890
891        editor.buffer.insert_char(0, 5, '!');
892        editor.enqueue_lsp_change();
893
894        let changes = changes.borrow();
895        assert_eq!(changes.len(), 1);
896        assert_eq!(changes[0].len(), 1);
897        let change = &changes[0][0];
898        assert_eq!(change.text, "!");
899        assert_eq!(change.range.start.line, 0);
900        assert_eq!(change.range.start.character, 5);
901        assert_eq!(change.range.end.line, 0);
902        assert_eq!(change.range.end.character, 5);
903    }
904
905    #[test]
906    fn test_editor_update_sends_bounded_incremental_lsp_change() {
907        let changes = Rc::new(RefCell::new(Vec::new()));
908        let client = TestLspClient { changes: Rc::clone(&changes) };
909        let content = (0..10)
910            .map(|line| format!("line{line}"))
911            .collect::<Vec<_>>()
912            .join("\n");
913        let mut editor = CodeEditor::new(&content, "rs");
914        editor.attach_lsp(
915            Box::new(client),
916            lsp::LspDocument::new("file:///large.rs", "rust"),
917        );
918        editor.request_focus();
919        editor.has_canvas_focus = true;
920        editor.focus_locked = false;
921        editor.cursors.primary_mut().position = (5, 2);
922
923        let _ = editor.update(&Message::CharacterInput('X'));
924
925        let changes = changes.borrow();
926        assert_eq!(changes.len(), 1);
927        assert_eq!(changes[0].len(), 1);
928        let change = &changes[0][0];
929        assert_eq!(change.range.start.line, 4);
930        assert_eq!(change.range.start.character, 0);
931        assert_eq!(change.range.end.line, 7);
932        assert_eq!(change.range.end.character, 0);
933        assert_eq!(change.text, "line4\nliXne5\nline6\n");
934        assert!(!editor.lsp_shadow_is_current);
935        assert!(editor.lsp_shadow_text.is_empty());
936    }
937
938    #[test]
939    fn test_open_lsp_document_stamps_version_and_sends_did_open() {
940        let calls = Rc::new(RefCell::new(Vec::new()));
941        let mut client = RecordingLspClient { calls: Rc::clone(&calls) };
942        let buffer = TextBuffer::new("hello");
943        let document = lsp::LspDocument::new("file:///test.rs", "rust");
944
945        let (document, text) =
946            open_lsp_document(&mut client, &buffer, document);
947
948        assert_eq!(document.version, 1);
949        assert_eq!(text, "hello");
950        assert_eq!(calls.borrow().as_slice(), ["did_open"]);
951    }
952
953    #[test]
954    fn test_with_lsp_runs_closure_when_client_and_document_present() {
955        let calls = Rc::new(RefCell::new(Vec::new()));
956        let client = RecordingLspClient { calls: Rc::clone(&calls) };
957        let mut editor = CodeEditor::new("hello", "rs");
958        editor.attach_lsp(
959            Box::new(client),
960            lsp::LspDocument::new("file:///test.rs", "rust"),
961        );
962        calls.borrow_mut().clear(); // attach_lsp itself already logged did_open
963
964        let ran = editor.with_lsp(|client, document| {
965            client.did_save(document, "hello");
966        });
967
968        assert!(ran.is_some());
969        assert_eq!(calls.borrow().as_slice(), ["did_save"]);
970    }
971
972    #[test]
973    fn test_with_lsp_returns_none_when_client_absent() {
974        let mut editor = CodeEditor::new("hello", "rs");
975        let ran = editor.with_lsp(|_client, _document| {});
976        assert!(ran.is_none());
977    }
978
979    #[test]
980    fn test_lsp_did_save_sends_current_buffer_contents() {
981        let calls = Rc::new(RefCell::new(Vec::new()));
982        let client = RecordingLspClient { calls: Rc::clone(&calls) };
983        let mut editor = CodeEditor::new("hello", "rs");
984        editor.attach_lsp(
985            Box::new(client),
986            lsp::LspDocument::new("file:///test.rs", "rust"),
987        );
988        calls.borrow_mut().clear(); // attach_lsp itself already logged did_open
989
990        editor.lsp_did_save();
991
992        assert_eq!(calls.borrow().as_slice(), ["did_save"]);
993    }
994
995    #[test]
996    fn test_lsp_did_save_is_a_noop_without_an_attached_client() {
997        // Regression: this used to serialize the whole buffer via
998        // `to_string()` even with no client/document attached.
999        let mut editor = CodeEditor::new("hello", "rs");
1000        editor.lsp_did_save(); // must not panic
1001    }
1002
1003    #[test]
1004    fn test_with_lsp_returns_none_when_document_absent() {
1005        let calls = Rc::new(RefCell::new(Vec::new()));
1006        let client = RecordingLspClient { calls: Rc::clone(&calls) };
1007        let mut editor = CodeEditor::new("hello", "rs");
1008        editor.attach_lsp(
1009            Box::new(client),
1010            lsp::LspDocument::new("file:///test.rs", "rust"),
1011        );
1012        editor.lsp_document = None;
1013
1014        let ran = editor.with_lsp(|_client, _document| {});
1015        assert!(ran.is_none());
1016    }
1017
1018    #[test]
1019    #[allow(clippy::unwrap_used)]
1020    fn test_with_lsp_mut_document_allows_version_bump() {
1021        let calls = Rc::new(RefCell::new(Vec::new()));
1022        let client = RecordingLspClient { calls: Rc::clone(&calls) };
1023        let mut editor = CodeEditor::new("hello", "rs");
1024        editor.attach_lsp(
1025            Box::new(client),
1026            lsp::LspDocument::new("file:///test.rs", "rust"),
1027        );
1028
1029        editor.with_lsp_mut_document(|_client, document| {
1030            document.version = document.version.saturating_add(1);
1031        });
1032
1033        assert_eq!(editor.lsp_document.as_ref().unwrap().version, 2);
1034    }
1035
1036    #[test]
1037    fn test_lsp_flush_pending_changes_preserves_queue_when_no_client_attached()
1038    {
1039        let mut editor = CodeEditor::new("hello", "rs");
1040        editor.lsp_pending_changes.push(lsp::LspTextChange {
1041            range: lsp::LspRange {
1042                start: lsp::LspPosition { line: 0, character: 0 },
1043                end: lsp::LspPosition { line: 0, character: 0 },
1044            },
1045            text: "x".to_string(),
1046        });
1047
1048        editor.lsp_flush_pending_changes();
1049
1050        assert_eq!(editor.lsp_pending_changes.len(), 1);
1051    }
1052}