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/formatting 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 /// Requests formatting edits for the whole document.
804 ///
805 /// The formatting options are derived from the editor's own
806 /// [`IndentStyle`], so the server formats the way this editor indents.
807 /// Queued changes are flushed first: the server formats the document it
808 /// has, so an unflushed keystroke would come back reformatted away.
809 ///
810 /// Like every other request this is fire-and-forget. The reply is a batch
811 /// of edits, which the host applies with
812 /// [`Self::apply_lsp_text_edits`].
813 ///
814 /// # Returns
815 ///
816 /// `true` if the request was sent; `false` when no client and document are
817 /// attached
818 ///
819 /// [`IndentStyle`]: crate::IndentStyle
820 ///
821 /// # Example
822 ///
823 /// ```
824 /// use std::cell::RefCell;
825 /// use std::rc::Rc;
826 ///
827 /// use iced_code_editor::{
828 /// CodeEditor, IndentStyle, LspClient, LspDocument, LspFormattingOptions,
829 /// };
830 ///
831 /// /// Records the options each formatting request carried.
832 /// struct FormattingClient(Rc<RefCell<Vec<LspFormattingOptions>>>);
833 ///
834 /// impl LspClient for FormattingClient {
835 /// fn request_formatting(
836 /// &mut self,
837 /// _document: &LspDocument,
838 /// options: LspFormattingOptions,
839 /// ) {
840 /// self.0.borrow_mut().push(options);
841 /// }
842 /// }
843 ///
844 /// let requests = Rc::new(RefCell::new(Vec::new()));
845 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
846 ///
847 /// // Nothing is attached yet, so there is nobody to ask.
848 /// assert!(!editor.lsp_request_formatting());
849 ///
850 /// editor.set_indent_style(IndentStyle::Spaces(2));
851 /// editor.attach_lsp(
852 /// Box::new(FormattingClient(Rc::clone(&requests))),
853 /// LspDocument::new("file:///tmp/main.rs", "rust"),
854 /// );
855 ///
856 /// assert!(editor.lsp_request_formatting());
857 /// assert_eq!(requests.borrow()[0].tab_size, 2);
858 /// ```
859 pub fn lsp_request_formatting(&mut self) -> bool {
860 self.lsp_flush_pending_changes();
861 let options = lsp::LspFormattingOptions::from(self.indent_style());
862 self.with_lsp(|client, document| {
863 client.request_formatting(document, options);
864 })
865 .is_some()
866 }
867}
868
869/// Sends `did_open` for `document` (after stamping `version = 1`) on
870/// `client`, using `buffer`'s current contents.
871///
872/// Returns the stamped document and the serialized buffer text, both needed
873/// by the caller to update its LSP shadow-sync bookkeeping.
874///
875/// Free function (not a method) so callers can hold a mutable borrow of
876/// `self.lsp_client` while still passing `&self.buffer` — a method taking
877/// `&mut self` here would conflict with that borrow in `lsp_open_document`.
878fn open_lsp_document(
879 client: &mut dyn lsp::LspClient,
880 buffer: &TextBuffer,
881 mut document: lsp::LspDocument,
882) -> (lsp::LspDocument, String) {
883 document.version = 1;
884 let text = buffer.to_string();
885 client.did_open(&document, &text);
886 (document, text)
887}
888
889#[cfg(test)]
890mod tests {
891 use std::cell::RefCell;
892 use std::rc::Rc;
893
894 use crate::canvas_editor::Message;
895
896 use super::*;
897
898 #[derive(Default)]
899 struct TestLspClient {
900 changes: Rc<RefCell<Vec<Vec<lsp::LspTextChange>>>>,
901 }
902
903 impl lsp::LspClient for TestLspClient {
904 fn did_change(
905 &mut self,
906 _document: &lsp::LspDocument,
907 changes: &[lsp::LspTextChange],
908 ) {
909 self.changes.borrow_mut().push(changes.to_vec());
910 }
911 }
912
913 /// Records every [`lsp::LspClient`] method invoked on it, by name.
914 #[derive(Default)]
915 struct RecordingLspClient {
916 calls: Rc<RefCell<Vec<String>>>,
917 }
918
919 impl lsp::LspClient for RecordingLspClient {
920 fn did_open(&mut self, _document: &lsp::LspDocument, _text: &str) {
921 self.calls.borrow_mut().push("did_open".to_string());
922 }
923 fn did_close(&mut self, _document: &lsp::LspDocument) {
924 self.calls.borrow_mut().push("did_close".to_string());
925 }
926 fn did_save(&mut self, _document: &lsp::LspDocument, _text: &str) {
927 self.calls.borrow_mut().push("did_save".to_string());
928 }
929 fn request_hover(
930 &mut self,
931 _document: &lsp::LspDocument,
932 _position: lsp::LspPosition,
933 ) {
934 self.calls.borrow_mut().push("request_hover".to_string());
935 }
936 fn did_change(
937 &mut self,
938 _document: &lsp::LspDocument,
939 _changes: &[lsp::LspTextChange],
940 ) {
941 self.calls.borrow_mut().push("did_change".to_string());
942 }
943 fn request_formatting(
944 &mut self,
945 _document: &lsp::LspDocument,
946 _options: lsp::LspFormattingOptions,
947 ) {
948 self.calls.borrow_mut().push("request_formatting".to_string());
949 }
950 }
951
952 #[test]
953 fn test_enqueue_lsp_change_auto_flush() {
954 let changes = Rc::new(RefCell::new(Vec::new()));
955 let client = TestLspClient { changes: Rc::clone(&changes) };
956 let mut editor = CodeEditor::new("hello", "rs");
957 editor.attach_lsp(
958 Box::new(client),
959 lsp::LspDocument::new("file:///test.rs", "rust"),
960 );
961 editor.set_lsp_auto_flush(true);
962
963 editor.buffer.insert_char(0, 5, '!');
964 editor.enqueue_lsp_change();
965
966 let changes = changes.borrow();
967 assert_eq!(changes.len(), 1);
968 assert_eq!(changes[0].len(), 1);
969 let change = &changes[0][0];
970 assert_eq!(change.text, "!");
971 assert_eq!(change.range.start.line, 0);
972 assert_eq!(change.range.start.character, 5);
973 assert_eq!(change.range.end.line, 0);
974 assert_eq!(change.range.end.character, 5);
975 }
976
977 #[test]
978 fn test_editor_update_sends_bounded_incremental_lsp_change() {
979 let changes = Rc::new(RefCell::new(Vec::new()));
980 let client = TestLspClient { changes: Rc::clone(&changes) };
981 let content = (0..10)
982 .map(|line| format!("line{line}"))
983 .collect::<Vec<_>>()
984 .join("\n");
985 let mut editor = CodeEditor::new(&content, "rs");
986 editor.attach_lsp(
987 Box::new(client),
988 lsp::LspDocument::new("file:///large.rs", "rust"),
989 );
990 editor.request_focus();
991 editor.has_canvas_focus = true;
992 editor.focus_locked = false;
993 editor.cursors.primary_mut().position = (5, 2);
994
995 let _ = editor.update(&Message::CharacterInput('X'));
996
997 let changes = changes.borrow();
998 assert_eq!(changes.len(), 1);
999 assert_eq!(changes[0].len(), 1);
1000 let change = &changes[0][0];
1001 assert_eq!(change.range.start.line, 4);
1002 assert_eq!(change.range.start.character, 0);
1003 assert_eq!(change.range.end.line, 7);
1004 assert_eq!(change.range.end.character, 0);
1005 assert_eq!(change.text, "line4\nliXne5\nline6\n");
1006 assert!(!editor.lsp_shadow_is_current);
1007 assert!(editor.lsp_shadow_text.is_empty());
1008 }
1009
1010 #[test]
1011 fn test_open_lsp_document_stamps_version_and_sends_did_open() {
1012 let calls = Rc::new(RefCell::new(Vec::new()));
1013 let mut client = RecordingLspClient { calls: Rc::clone(&calls) };
1014 let buffer = TextBuffer::new("hello");
1015 let document = lsp::LspDocument::new("file:///test.rs", "rust");
1016
1017 let (document, text) =
1018 open_lsp_document(&mut client, &buffer, document);
1019
1020 assert_eq!(document.version, 1);
1021 assert_eq!(text, "hello");
1022 assert_eq!(calls.borrow().as_slice(), ["did_open"]);
1023 }
1024
1025 #[test]
1026 fn test_with_lsp_runs_closure_when_client_and_document_present() {
1027 let calls = Rc::new(RefCell::new(Vec::new()));
1028 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1029 let mut editor = CodeEditor::new("hello", "rs");
1030 editor.attach_lsp(
1031 Box::new(client),
1032 lsp::LspDocument::new("file:///test.rs", "rust"),
1033 );
1034 calls.borrow_mut().clear(); // attach_lsp itself already logged did_open
1035
1036 let ran = editor.with_lsp(|client, document| {
1037 client.did_save(document, "hello");
1038 });
1039
1040 assert!(ran.is_some());
1041 assert_eq!(calls.borrow().as_slice(), ["did_save"]);
1042 }
1043
1044 #[test]
1045 fn test_with_lsp_returns_none_when_client_absent() {
1046 let mut editor = CodeEditor::new("hello", "rs");
1047 let ran = editor.with_lsp(|_client, _document| {});
1048 assert!(ran.is_none());
1049 }
1050
1051 #[test]
1052 fn test_lsp_did_save_sends_current_buffer_contents() {
1053 let calls = Rc::new(RefCell::new(Vec::new()));
1054 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1055 let mut editor = CodeEditor::new("hello", "rs");
1056 editor.attach_lsp(
1057 Box::new(client),
1058 lsp::LspDocument::new("file:///test.rs", "rust"),
1059 );
1060 calls.borrow_mut().clear(); // attach_lsp itself already logged did_open
1061
1062 editor.lsp_did_save();
1063
1064 assert_eq!(calls.borrow().as_slice(), ["did_save"]);
1065 }
1066
1067 #[test]
1068 fn test_lsp_did_save_is_a_noop_without_an_attached_client() {
1069 // Regression: this used to serialize the whole buffer via
1070 // `to_string()` even with no client/document attached.
1071 let mut editor = CodeEditor::new("hello", "rs");
1072 editor.lsp_did_save(); // must not panic
1073 }
1074
1075 #[test]
1076 fn test_with_lsp_returns_none_when_document_absent() {
1077 let calls = Rc::new(RefCell::new(Vec::new()));
1078 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1079 let mut editor = CodeEditor::new("hello", "rs");
1080 editor.attach_lsp(
1081 Box::new(client),
1082 lsp::LspDocument::new("file:///test.rs", "rust"),
1083 );
1084 editor.lsp_document = None;
1085
1086 let ran = editor.with_lsp(|_client, _document| {});
1087 assert!(ran.is_none());
1088 }
1089
1090 #[test]
1091 #[allow(clippy::unwrap_used)]
1092 fn test_with_lsp_mut_document_allows_version_bump() {
1093 let calls = Rc::new(RefCell::new(Vec::new()));
1094 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1095 let mut editor = CodeEditor::new("hello", "rs");
1096 editor.attach_lsp(
1097 Box::new(client),
1098 lsp::LspDocument::new("file:///test.rs", "rust"),
1099 );
1100
1101 editor.with_lsp_mut_document(|_client, document| {
1102 document.version = document.version.saturating_add(1);
1103 });
1104
1105 assert_eq!(editor.lsp_document.as_ref().unwrap().version, 2);
1106 }
1107
1108 #[test]
1109 fn test_lsp_flush_pending_changes_preserves_queue_when_no_client_attached()
1110 {
1111 let mut editor = CodeEditor::new("hello", "rs");
1112 editor.lsp_pending_changes.push(lsp::LspTextChange {
1113 range: lsp::LspRange {
1114 start: lsp::LspPosition { line: 0, character: 0 },
1115 end: lsp::LspPosition { line: 0, character: 0 },
1116 },
1117 text: "x".to_string(),
1118 });
1119
1120 editor.lsp_flush_pending_changes();
1121
1122 assert_eq!(editor.lsp_pending_changes.len(), 1);
1123 }
1124
1125 #[test]
1126 fn test_lsp_request_formatting_flushes_queued_changes_first() {
1127 // The server formats the document it holds, so a keystroke still
1128 // sitting in the queue has to reach it before the request does.
1129 let calls = Rc::new(RefCell::new(Vec::new()));
1130 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1131 let mut editor = CodeEditor::new("hello", "rs");
1132 editor.set_lsp_auto_flush(false);
1133 editor.attach_lsp(
1134 Box::new(client),
1135 lsp::LspDocument::new("file:///test.rs", "rust"),
1136 );
1137
1138 editor.buffer.insert_char(0, 5, '!');
1139 editor.enqueue_lsp_change();
1140 assert!(editor.lsp_request_formatting());
1141
1142 assert_eq!(
1143 calls.borrow().as_slice(),
1144 ["did_open", "did_change", "request_formatting"]
1145 );
1146 }
1147
1148 #[test]
1149 fn test_lsp_request_formatting_is_a_noop_without_an_attached_client() {
1150 let mut editor = CodeEditor::new("hello", "rs");
1151 assert!(!editor.lsp_request_formatting());
1152 }
1153}