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