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 ///
677 /// The extent is the document the server holds, which is
678 /// [`crate::buffer::TextBuffer::to_string`]: with a trailing newline, that
679 /// text has one more, empty line after the buffer's last one. A
680 /// full-document replacement that stopped before it would leave the old
681 /// newline after the new text.
682 fn update_lsp_synced_extent(&mut self) {
683 let line_count = self.buffer.line_count();
684 if self.buffer.has_trailing_newline() {
685 self.lsp_synced_line_count = line_count.saturating_add(1);
686 self.lsp_synced_last_line_len = 0;
687 } else {
688 self.lsp_synced_line_count = line_count;
689 self.lsp_synced_last_line_len =
690 self.buffer.line_len(line_count.saturating_sub(1));
691 }
692 }
693
694 /// Sets whether LSP support is enabled.
695 ///
696 /// When set to `false`, any attached LSP client is detached automatically.
697 /// Calling [`attach_lsp`] while disabled is a no-op.
698 ///
699 /// # Example
700 ///
701 /// ```
702 /// use iced_code_editor::CodeEditor;
703 ///
704 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
705 /// editor.set_lsp_enabled(false);
706 /// ```
707 ///
708 /// [`attach_lsp`]: CodeEditor::attach_lsp
709 pub fn set_lsp_enabled(&mut self, enabled: bool) {
710 self.lsp_enabled = enabled;
711 if !enabled {
712 self.detach_lsp();
713 }
714 }
715
716 /// Returns whether LSP support is enabled.
717 ///
718 /// # Returns
719 ///
720 /// `true` if LSP is enabled, `false` otherwise
721 ///
722 /// # Example
723 ///
724 /// ```
725 /// use iced_code_editor::CodeEditor;
726 ///
727 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
728 /// // Enabled by default, though no client is attached until you attach one.
729 /// assert!(editor.lsp_enabled());
730 ///
731 /// editor.set_lsp_enabled(false);
732 /// assert!(!editor.lsp_enabled());
733 /// ```
734 pub fn lsp_enabled(&self) -> bool {
735 self.lsp_enabled
736 }
737
738 /// URI of the document this editor has open with its LSP client.
739 ///
740 /// `None` until a document is attached or opened. Hosts use it to route
741 /// per-document server events, such as diagnostics, to the right editor.
742 ///
743 /// # Example
744 ///
745 /// ```
746 /// use iced_code_editor::CodeEditor;
747 ///
748 /// let editor = CodeEditor::new("fn main() {}", "rs");
749 /// assert_eq!(editor.lsp_document_uri(), None);
750 /// ```
751 pub fn lsp_document_uri(&self) -> Option<&str> {
752 self.lsp_document.as_ref().map(|document| document.uri.as_str())
753 }
754
755 /// Initiates a "Go to Definition" request for the symbol at the current cursor position.
756 ///
757 /// This method converts the current cursor coordinates into an LSP-compatible position
758 /// and delegates the request to the active `LspClient`, if one is attached.
759 ///
760 /// Fire-and-forget: the resolved location arrives through the client
761 /// implementation, and the host decides whether to follow it.
762 ///
763 /// # Example
764 ///
765 /// ```
766 /// use std::cell::RefCell;
767 /// use std::rc::Rc;
768 ///
769 /// use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspPosition};
770 ///
771 /// /// Records the position each definition request asked about.
772 /// struct DefinitionClient(Rc<RefCell<Vec<LspPosition>>>);
773 ///
774 /// impl LspClient for DefinitionClient {
775 /// fn request_definition(&mut self, _document: &LspDocument, position: LspPosition) {
776 /// self.0.borrow_mut().push(position);
777 /// }
778 /// }
779 ///
780 /// let requests = Rc::new(RefCell::new(Vec::new()));
781 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
782 /// editor.attach_lsp(
783 /// Box::new(DefinitionClient(Rc::clone(&requests))),
784 /// LspDocument::new("file:///tmp/main.rs", "rust"),
785 /// );
786 ///
787 /// editor.lsp_request_definition();
788 /// assert_eq!(requests.borrow().len(), 1);
789 /// ```
790 pub fn lsp_request_definition(&mut self) {
791 let position = self.lsp_position_from_cursor();
792 self.with_lsp(|client, document| {
793 client.request_definition(document, position);
794 });
795 }
796
797 /// Initiates a "Go to Definition" request for the symbol at the specified screen coordinates.
798 ///
799 /// This is typically used for mouse interactions (e.g., Ctrl+Click). It first resolves
800 /// the screen coordinates to a text position and then sends the request.
801 ///
802 /// # Arguments
803 ///
804 /// * `point` - The click position in canvas coordinates
805 ///
806 /// # Returns
807 ///
808 /// `true` if the request was successfully sent (i.e., a valid position was found and an LSP client is active),
809 /// `false` otherwise.
810 ///
811 /// # Example
812 ///
813 /// ```
814 /// use iced::Point;
815 /// use iced_code_editor::CodeEditor;
816 ///
817 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
818 ///
819 /// // With no client attached there is nothing to send.
820 /// assert!(!editor.lsp_request_definition_at(Point::new(50.0, 5.0)));
821 /// ```
822 pub fn lsp_request_definition_at(&mut self, point: iced::Point) -> bool {
823 let Some(position) = self.lsp_position_from_point(point) else {
824 return false;
825 };
826 self.with_lsp(|client, document| {
827 client.request_definition(document, position);
828 })
829 .is_some()
830 }
831
832 /// Requests formatting edits for the whole document.
833 ///
834 /// The formatting options are derived from the editor's own
835 /// [`IndentStyle`], so the server formats the way this editor indents.
836 /// Queued changes are flushed first: the server formats the document it
837 /// has, so an unflushed keystroke would come back reformatted away.
838 ///
839 /// Like every other request this is fire-and-forget. The reply is a batch
840 /// of edits, which the host applies with
841 /// [`Self::apply_lsp_text_edits`].
842 ///
843 /// # Returns
844 ///
845 /// `true` if the request was sent; `false` when no client and document are
846 /// attached
847 ///
848 /// [`IndentStyle`]: crate::IndentStyle
849 ///
850 /// # Example
851 ///
852 /// ```
853 /// use std::cell::RefCell;
854 /// use std::rc::Rc;
855 ///
856 /// use iced_code_editor::{
857 /// CodeEditor, IndentStyle, LspClient, LspDocument, LspFormattingOptions,
858 /// };
859 ///
860 /// /// Records the options each formatting request carried.
861 /// struct FormattingClient(Rc<RefCell<Vec<LspFormattingOptions>>>);
862 ///
863 /// impl LspClient for FormattingClient {
864 /// fn request_formatting(
865 /// &mut self,
866 /// _document: &LspDocument,
867 /// options: LspFormattingOptions,
868 /// ) {
869 /// self.0.borrow_mut().push(options);
870 /// }
871 /// }
872 ///
873 /// let requests = Rc::new(RefCell::new(Vec::new()));
874 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
875 ///
876 /// // Nothing is attached yet, so there is nobody to ask.
877 /// assert!(!editor.lsp_request_formatting());
878 ///
879 /// editor.set_indent_style(IndentStyle::Spaces(2));
880 /// editor.attach_lsp(
881 /// Box::new(FormattingClient(Rc::clone(&requests))),
882 /// LspDocument::new("file:///tmp/main.rs", "rust"),
883 /// );
884 ///
885 /// assert!(editor.lsp_request_formatting());
886 /// assert_eq!(requests.borrow()[0].tab_size, 2);
887 /// ```
888 pub fn lsp_request_formatting(&mut self) -> bool {
889 self.lsp_flush_pending_changes();
890 let options = lsp::LspFormattingOptions::from(self.indent_style());
891 self.with_lsp(|client, document| {
892 client.request_formatting(document, options);
893 })
894 .is_some()
895 }
896}
897
898/// Sends `did_open` for `document` (after stamping `version = 1`) on
899/// `client`, using `buffer`'s current contents.
900///
901/// Returns the stamped document and the serialized buffer text, both needed
902/// by the caller to update its LSP shadow-sync bookkeeping.
903///
904/// Free function (not a method) so callers can hold a mutable borrow of
905/// `self.lsp_client` while still passing `&self.buffer` — a method taking
906/// `&mut self` here would conflict with that borrow in `lsp_open_document`.
907fn open_lsp_document(
908 client: &mut dyn lsp::LspClient,
909 buffer: &TextBuffer,
910 mut document: lsp::LspDocument,
911) -> (lsp::LspDocument, String) {
912 document.version = 1;
913 let text = buffer.to_string();
914 client.did_open(&document, &text);
915 (document, text)
916}
917
918#[cfg(test)]
919mod tests {
920 use std::cell::RefCell;
921 use std::rc::Rc;
922
923 use crate::canvas_editor::Message;
924
925 use super::*;
926
927 #[derive(Default)]
928 struct TestLspClient {
929 changes: Rc<RefCell<Vec<Vec<lsp::LspTextChange>>>>,
930 }
931
932 impl lsp::LspClient for TestLspClient {
933 fn did_change(
934 &mut self,
935 _document: &lsp::LspDocument,
936 changes: &[lsp::LspTextChange],
937 ) {
938 self.changes.borrow_mut().push(changes.to_vec());
939 }
940 }
941
942 /// Records every [`lsp::LspClient`] method invoked on it, by name.
943 #[derive(Default)]
944 struct RecordingLspClient {
945 calls: Rc<RefCell<Vec<String>>>,
946 }
947
948 impl lsp::LspClient for RecordingLspClient {
949 fn did_open(&mut self, _document: &lsp::LspDocument, _text: &str) {
950 self.calls.borrow_mut().push("did_open".to_string());
951 }
952 fn did_close(&mut self, _document: &lsp::LspDocument) {
953 self.calls.borrow_mut().push("did_close".to_string());
954 }
955 fn did_save(&mut self, _document: &lsp::LspDocument, _text: &str) {
956 self.calls.borrow_mut().push("did_save".to_string());
957 }
958 fn request_hover(
959 &mut self,
960 _document: &lsp::LspDocument,
961 _position: lsp::LspPosition,
962 ) {
963 self.calls.borrow_mut().push("request_hover".to_string());
964 }
965 fn did_change(
966 &mut self,
967 _document: &lsp::LspDocument,
968 _changes: &[lsp::LspTextChange],
969 ) {
970 self.calls.borrow_mut().push("did_change".to_string());
971 }
972 fn request_formatting(
973 &mut self,
974 _document: &lsp::LspDocument,
975 _options: lsp::LspFormattingOptions,
976 ) {
977 self.calls.borrow_mut().push("request_formatting".to_string());
978 }
979 }
980
981 #[test]
982 fn test_enqueue_lsp_change_auto_flush() {
983 let changes = Rc::new(RefCell::new(Vec::new()));
984 let client = TestLspClient { changes: Rc::clone(&changes) };
985 let mut editor = CodeEditor::new("hello", "rs");
986 editor.attach_lsp(
987 Box::new(client),
988 lsp::LspDocument::new("file:///test.rs", "rust"),
989 );
990 editor.set_lsp_auto_flush(true);
991
992 editor.buffer.insert_char(0, 5, '!');
993 editor.enqueue_lsp_change();
994
995 let changes = changes.borrow();
996 assert_eq!(changes.len(), 1);
997 assert_eq!(changes[0].len(), 1);
998 let change = &changes[0][0];
999 assert_eq!(change.text, "!");
1000 assert_eq!(change.range.start.line, 0);
1001 assert_eq!(change.range.start.character, 5);
1002 assert_eq!(change.range.end.line, 0);
1003 assert_eq!(change.range.end.character, 5);
1004 }
1005
1006 #[test]
1007 fn test_editor_update_sends_bounded_incremental_lsp_change() {
1008 let changes = Rc::new(RefCell::new(Vec::new()));
1009 let client = TestLspClient { changes: Rc::clone(&changes) };
1010 let content = (0..10)
1011 .map(|line| format!("line{line}"))
1012 .collect::<Vec<_>>()
1013 .join("\n");
1014 let mut editor = CodeEditor::new(&content, "rs");
1015 editor.attach_lsp(
1016 Box::new(client),
1017 lsp::LspDocument::new("file:///large.rs", "rust"),
1018 );
1019 editor.request_focus();
1020 editor.has_canvas_focus = true;
1021 editor.focus_locked = false;
1022 editor.cursors.primary_mut().position = (5, 2);
1023
1024 let _ = editor.update(&Message::CharacterInput('X'));
1025
1026 let changes = changes.borrow();
1027 assert_eq!(changes.len(), 1);
1028 assert_eq!(changes[0].len(), 1);
1029 let change = &changes[0][0];
1030 assert_eq!(change.range.start.line, 4);
1031 assert_eq!(change.range.start.character, 0);
1032 assert_eq!(change.range.end.line, 7);
1033 assert_eq!(change.range.end.character, 0);
1034 assert_eq!(change.text, "line4\nliXne5\nline6\n");
1035 assert!(!editor.lsp_shadow_is_current);
1036 assert!(editor.lsp_shadow_text.is_empty());
1037 }
1038
1039 #[test]
1040 fn test_open_lsp_document_stamps_version_and_sends_did_open() {
1041 let calls = Rc::new(RefCell::new(Vec::new()));
1042 let mut client = RecordingLspClient { calls: Rc::clone(&calls) };
1043 let buffer = TextBuffer::new("hello");
1044 let document = lsp::LspDocument::new("file:///test.rs", "rust");
1045
1046 let (document, text) =
1047 open_lsp_document(&mut client, &buffer, document);
1048
1049 assert_eq!(document.version, 1);
1050 assert_eq!(text, "hello");
1051 assert_eq!(calls.borrow().as_slice(), ["did_open"]);
1052 }
1053
1054 #[test]
1055 fn test_lsp_document_uri_follows_attach_and_detach() {
1056 let calls = Rc::new(RefCell::new(Vec::new()));
1057 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1058 let mut editor = CodeEditor::new("hello", "rs");
1059 assert_eq!(editor.lsp_document_uri(), None);
1060
1061 editor.attach_lsp(
1062 Box::new(client),
1063 lsp::LspDocument::new("file:///test.rs", "rust"),
1064 );
1065 assert_eq!(editor.lsp_document_uri(), Some("file:///test.rs"));
1066
1067 editor.detach_lsp();
1068 assert_eq!(editor.lsp_document_uri(), None);
1069 }
1070
1071 #[test]
1072 fn test_with_lsp_runs_closure_when_client_and_document_present() {
1073 let calls = Rc::new(RefCell::new(Vec::new()));
1074 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1075 let mut editor = CodeEditor::new("hello", "rs");
1076 editor.attach_lsp(
1077 Box::new(client),
1078 lsp::LspDocument::new("file:///test.rs", "rust"),
1079 );
1080 calls.borrow_mut().clear(); // attach_lsp itself already logged did_open
1081
1082 let ran = editor.with_lsp(|client, document| {
1083 client.did_save(document, "hello");
1084 });
1085
1086 assert!(ran.is_some());
1087 assert_eq!(calls.borrow().as_slice(), ["did_save"]);
1088 }
1089
1090 #[test]
1091 fn test_with_lsp_returns_none_when_client_absent() {
1092 let mut editor = CodeEditor::new("hello", "rs");
1093 let ran = editor.with_lsp(|_client, _document| {});
1094 assert!(ran.is_none());
1095 }
1096
1097 #[test]
1098 fn test_lsp_did_save_sends_current_buffer_contents() {
1099 let calls = Rc::new(RefCell::new(Vec::new()));
1100 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1101 let mut editor = CodeEditor::new("hello", "rs");
1102 editor.attach_lsp(
1103 Box::new(client),
1104 lsp::LspDocument::new("file:///test.rs", "rust"),
1105 );
1106 calls.borrow_mut().clear(); // attach_lsp itself already logged did_open
1107
1108 editor.lsp_did_save();
1109
1110 assert_eq!(calls.borrow().as_slice(), ["did_save"]);
1111 }
1112
1113 #[test]
1114 fn test_lsp_did_save_is_a_noop_without_an_attached_client() {
1115 // Regression: this used to serialize the whole buffer via
1116 // `to_string()` even with no client/document attached.
1117 let mut editor = CodeEditor::new("hello", "rs");
1118 editor.lsp_did_save(); // must not panic
1119 }
1120
1121 #[test]
1122 fn test_with_lsp_returns_none_when_document_absent() {
1123 let calls = Rc::new(RefCell::new(Vec::new()));
1124 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1125 let mut editor = CodeEditor::new("hello", "rs");
1126 editor.attach_lsp(
1127 Box::new(client),
1128 lsp::LspDocument::new("file:///test.rs", "rust"),
1129 );
1130 editor.lsp_document = None;
1131
1132 let ran = editor.with_lsp(|_client, _document| {});
1133 assert!(ran.is_none());
1134 }
1135
1136 #[test]
1137 #[allow(clippy::unwrap_used)]
1138 fn test_with_lsp_mut_document_allows_version_bump() {
1139 let calls = Rc::new(RefCell::new(Vec::new()));
1140 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1141 let mut editor = CodeEditor::new("hello", "rs");
1142 editor.attach_lsp(
1143 Box::new(client),
1144 lsp::LspDocument::new("file:///test.rs", "rust"),
1145 );
1146
1147 editor.with_lsp_mut_document(|_client, document| {
1148 document.version = document.version.saturating_add(1);
1149 });
1150
1151 assert_eq!(editor.lsp_document.as_ref().unwrap().version, 2);
1152 }
1153
1154 #[test]
1155 fn test_lsp_flush_pending_changes_preserves_queue_when_no_client_attached()
1156 {
1157 let mut editor = CodeEditor::new("hello", "rs");
1158 editor.lsp_pending_changes.push(lsp::LspTextChange {
1159 range: lsp::LspRange {
1160 start: lsp::LspPosition { line: 0, character: 0 },
1161 end: lsp::LspPosition { line: 0, character: 0 },
1162 },
1163 text: "x".to_string(),
1164 });
1165
1166 editor.lsp_flush_pending_changes();
1167
1168 assert_eq!(editor.lsp_pending_changes.len(), 1);
1169 }
1170
1171 #[test]
1172 fn test_lsp_request_formatting_flushes_queued_changes_first() {
1173 // The server formats the document it holds, so a keystroke still
1174 // sitting in the queue has to reach it before the request does.
1175 let calls = Rc::new(RefCell::new(Vec::new()));
1176 let client = RecordingLspClient { calls: Rc::clone(&calls) };
1177 let mut editor = CodeEditor::new("hello", "rs");
1178 editor.set_lsp_auto_flush(false);
1179 editor.attach_lsp(
1180 Box::new(client),
1181 lsp::LspDocument::new("file:///test.rs", "rust"),
1182 );
1183
1184 editor.buffer.insert_char(0, 5, '!');
1185 editor.enqueue_lsp_change();
1186 assert!(editor.lsp_request_formatting());
1187
1188 assert_eq!(
1189 calls.borrow().as_slice(),
1190 ["did_open", "did_change", "request_formatting"]
1191 );
1192 }
1193
1194 #[test]
1195 fn test_lsp_request_formatting_is_a_noop_without_an_attached_client() {
1196 let mut editor = CodeEditor::new("hello", "rs");
1197 assert!(!editor.lsp_request_formatting());
1198 }
1199
1200 /// Mirrors the document the way a server does: the text from
1201 /// `did_open`, with every `did_change` applied to it.
1202 #[derive(Default)]
1203 struct MirrorLspClient {
1204 text: Rc<RefCell<String>>,
1205 }
1206
1207 /// Byte offset of an LSP position (ASCII text, so characters are bytes).
1208 fn mirror_offset(text: &str, position: lsp::LspPosition) -> usize {
1209 let mut offset = 0;
1210 for (index, line) in text.split('\n').enumerate() {
1211 if index == position.line as usize {
1212 return offset + (position.character as usize).min(line.len());
1213 }
1214 offset += line.len() + 1;
1215 }
1216 text.len()
1217 }
1218
1219 impl lsp::LspClient for MirrorLspClient {
1220 fn did_open(&mut self, _document: &lsp::LspDocument, text: &str) {
1221 *self.text.borrow_mut() = text.to_string();
1222 }
1223 fn did_change(
1224 &mut self,
1225 _document: &lsp::LspDocument,
1226 changes: &[lsp::LspTextChange],
1227 ) {
1228 let mut text = self.text.borrow_mut();
1229 for change in changes {
1230 let start = mirror_offset(&text, change.range.start);
1231 let end = mirror_offset(&text, change.range.end).max(start);
1232 text.replace_range(start..end, &change.text);
1233 }
1234 }
1235 }
1236
1237 #[test]
1238 fn test_full_document_change_keeps_the_trailing_newline_once() {
1239 // Enter goes out as an incremental change, which leaves the
1240 // shadow text stale; the edit applied afterwards then falls back to
1241 // replacing the whole document. Its range must reach the end of the
1242 // document as the server holds it, past the trailing newline, or the
1243 // server ends up with the newline twice.
1244 for source in ["fn main() {\n let t = 1;\n}\n", "fn main() {}"] {
1245 let mirror = Rc::new(RefCell::new(String::new()));
1246 let client = MirrorLspClient { text: Rc::clone(&mirror) };
1247 let mut editor = CodeEditor::new(source, "rs");
1248 editor.request_focus();
1249 editor.attach_lsp(
1250 Box::new(client),
1251 lsp::LspDocument::new("file:///test.rs", "rust"),
1252 );
1253 assert_eq!(*mirror.borrow(), source);
1254
1255 let _ = editor.update(&Message::Enter);
1256 assert_eq!(*mirror.borrow(), editor.buffer.to_string());
1257 assert!(!editor.lsp_shadow_is_current, "{source:?}");
1258
1259 let applied = editor.apply_lsp_text_edits(&[lsp::LspTextChange {
1260 range: lsp::LspRange {
1261 start: lsp::LspPosition { line: 0, character: 0 },
1262 end: lsp::LspPosition { line: 0, character: 0 },
1263 },
1264 text: "use std::fmt;\n\n".to_string(),
1265 }]);
1266 assert!(applied);
1267 assert_eq!(
1268 *mirror.borrow(),
1269 editor.buffer.to_string(),
1270 "{source:?}"
1271 );
1272 }
1273 }
1274}