iced_code_editor/canvas_editor/lsp/
sync.rs1use crate::buffer::TextBuffer;
6use crate::canvas_editor::CodeEditor;
7use crate::canvas_editor::lsp;
8
9impl CodeEditor {
10 pub fn attach_lsp(
20 &mut self,
21 mut client: Box<dyn lsp::LspClient>,
22 document: lsp::LspDocument,
23 ) {
24 if !self.lsp_enabled {
25 return;
26 }
27 let (document, text) =
28 open_lsp_document(client.as_mut(), &self.buffer, document);
29 self.lsp_client = Some(client);
30 self.lsp_document = Some(document);
31 self.reset_lsp_shadow_state(text);
32 }
33
34 pub fn lsp_open_document(&mut self, document: lsp::LspDocument) {
43 let Some(client) = self.lsp_client.as_mut() else { return };
44 if let Some(current) = self.lsp_document.as_ref() {
45 client.did_close(current);
46 }
47 let (document, text) =
48 open_lsp_document(client.as_mut(), &self.buffer, document);
49 self.lsp_document = Some(document);
50 self.reset_lsp_shadow_state(text);
51 }
52
53 fn reset_lsp_shadow_state(&mut self, text: String) {
56 self.lsp_shadow_text = text;
57 self.lsp_shadow_is_current = true;
58 self.update_lsp_synced_extent();
59 self.lsp_edit_snapshot = None;
60 self.lsp_pending_changes.clear();
61 }
62
63 fn with_lsp<R>(
70 &mut self,
71 f: impl FnOnce(&mut dyn lsp::LspClient, &lsp::LspDocument) -> R,
72 ) -> Option<R> {
73 let client = self.lsp_client.as_deref_mut()?;
74 let document = self.lsp_document.as_ref()?;
75 Some(f(client, document))
76 }
77
78 fn with_lsp_mut_document<R>(
81 &mut self,
82 f: impl FnOnce(&mut dyn lsp::LspClient, &mut lsp::LspDocument) -> R,
83 ) -> Option<R> {
84 let client = self.lsp_client.as_deref_mut()?;
85 let document = self.lsp_document.as_mut()?;
86 Some(f(client, document))
87 }
88
89 pub fn detach_lsp(&mut self) {
93 self.with_lsp(|client, document| client.did_close(document));
94 self.lsp_client = None;
95 self.lsp_document = None;
96 self.lsp_shadow_text = String::new();
97 self.lsp_shadow_is_current = true;
98 self.lsp_synced_line_count = 1;
99 self.lsp_synced_last_line_len = 0;
100 self.lsp_edit_snapshot = None;
101 self.lsp_pending_changes.clear();
102 }
103
104 pub fn lsp_did_save(&mut self) {
106 if self.lsp_client.is_none() || self.lsp_document.is_none() {
111 return;
112 }
113 let text = self.buffer.to_string();
114 self.with_lsp(|client, document| client.did_save(document, &text));
115 }
116
117 pub fn lsp_request_hover(&mut self) {
119 let position = self.lsp_position_from_cursor();
120 self.with_lsp(|client, document| {
121 client.request_hover(document, position);
122 });
123 }
124
125 pub fn lsp_request_hover_at(&mut self, point: iced::Point) -> bool {
130 let Some(position) = self.lsp_position_from_point(point) else {
131 return false;
132 };
133 self.with_lsp(|client, document| {
134 client.request_hover(document, position);
135 })
136 .is_some()
137 }
138
139 pub fn lsp_request_hover_at_position(
143 &mut self,
144 position: lsp::LspPosition,
145 ) -> bool {
146 self.with_lsp(|client, document| {
147 client.request_hover(document, position);
148 })
149 .is_some()
150 }
151
152 pub fn lsp_position_at_point(
154 &self,
155 point: iced::Point,
156 ) -> Option<lsp::LspPosition> {
157 self.lsp_position_from_point(point)
158 }
159
160 pub fn lsp_hover_anchor_at_point(
166 &self,
167 point: iced::Point,
168 ) -> Option<(lsp::LspPosition, iced::Point)> {
169 let (line, col) = self.calculate_cursor_from_point(point)?;
170 let line_content = self.buffer.line(line);
171 let anchor_col = Self::word_start_in_line(line_content, col);
172 let anchor_point =
173 self.point_from_position(line, anchor_col).unwrap_or(point);
174 let line = u32::try_from(line).unwrap_or(u32::MAX);
175 let character = u32::try_from(anchor_col).unwrap_or(u32::MAX);
176 Some((lsp::LspPosition { line, character }, anchor_point))
177 }
178
179 pub fn lsp_request_completion(&mut self) {
181 let position = self.lsp_position_from_cursor();
182 self.with_lsp(|client, document| {
183 client.request_completion(document, position);
184 });
185 }
186
187 pub fn lsp_flush_pending_changes(&mut self) {
192 if self.lsp_pending_changes.is_empty() {
193 return;
194 }
195 if self.lsp_client.is_none() || self.lsp_document.is_none() {
199 return;
200 }
201
202 let changes = std::mem::take(&mut self.lsp_pending_changes);
203 self.with_lsp_mut_document(|client, document| {
204 document.version = document.version.saturating_add(1);
205 client.did_change(document, &changes);
206 });
207 }
208
209 pub fn set_lsp_auto_flush(&mut self, auto_flush: bool) {
211 self.lsp_auto_flush = auto_flush;
212 }
213
214 fn lsp_position_from_cursor(&self) -> lsp::LspPosition {
216 let pos = self.cursors.primary_position();
217 let line = u32::try_from(pos.0).unwrap_or(u32::MAX);
218 let character = u32::try_from(pos.1).unwrap_or(u32::MAX);
219 lsp::LspPosition { line, character }
220 }
221
222 fn lsp_position_from_point(
224 &self,
225 point: iced::Point,
226 ) -> Option<lsp::LspPosition> {
227 let (line, col) = self.calculate_cursor_from_point(point)?;
228 let line = u32::try_from(line).unwrap_or(u32::MAX);
229 let character = u32::try_from(col).unwrap_or(u32::MAX);
230 Some(lsp::LspPosition { line, character })
231 }
232
233 pub(crate) fn enqueue_lsp_change(&mut self) {
237 if self.lsp_document.is_none() {
238 return;
239 }
240
241 let new_text = self.buffer.to_string();
242 let change = if self.lsp_shadow_is_current {
243 lsp::compute_text_change(&self.lsp_shadow_text, &new_text)
244 } else {
245 let end_line = self.lsp_synced_line_count.saturating_sub(1);
246 Some(lsp::LspTextChange {
247 range: lsp::LspRange {
248 start: lsp::LspPosition { line: 0, character: 0 },
249 end: lsp::LspPosition {
250 line: u32::try_from(end_line).unwrap_or(u32::MAX),
251 character: u32::try_from(self.lsp_synced_last_line_len)
252 .unwrap_or(u32::MAX),
253 },
254 },
255 text: new_text.clone(),
256 })
257 };
258 if let Some(change) = change {
259 self.lsp_pending_changes.push(change);
260 }
261 self.lsp_shadow_text = new_text;
262 self.lsp_shadow_is_current = true;
263 self.update_lsp_synced_extent();
264 if self.lsp_auto_flush {
265 self.lsp_flush_pending_changes();
266 }
267 }
268
269 pub(crate) fn enqueue_incremental_lsp_change(&mut self) {
273 if self.lsp_document.is_none() {
274 self.lsp_edit_snapshot = None;
275 return;
276 }
277
278 let Some(snapshot) = self.lsp_edit_snapshot.take() else {
279 self.enqueue_lsp_change();
280 return;
281 };
282
283 let new_line_count = self.buffer.line_count();
284 let start_line =
285 snapshot.start_line.min(new_line_count.saturating_sub(1));
286 let new_end_exclusive = if new_line_count >= snapshot.old_line_count {
287 snapshot
288 .old_end_exclusive
289 .saturating_add(new_line_count - snapshot.old_line_count)
290 .min(new_line_count)
291 } else {
292 snapshot
293 .old_end_exclusive
294 .saturating_sub(snapshot.old_line_count - new_line_count)
295 .max(start_line.saturating_add(1))
296 .min(new_line_count)
297 };
298 let text =
299 self.buffer.line_range_to_string(start_line, new_end_exclusive);
300 self.lsp_pending_changes.push(lsp::LspTextChange {
301 range: lsp::LspRange {
302 start: lsp::LspPosition {
303 line: u32::try_from(snapshot.start_line)
304 .unwrap_or(u32::MAX),
305 character: 0,
306 },
307 end: snapshot.old_end,
308 },
309 text,
310 });
311
312 self.lsp_shadow_text = String::new();
316 self.lsp_shadow_is_current = false;
317 self.update_lsp_synced_extent();
318 if self.lsp_auto_flush {
319 self.lsp_flush_pending_changes();
320 }
321 }
322
323 fn update_lsp_synced_extent(&mut self) {
326 self.lsp_synced_line_count = self.buffer.line_count();
327 self.lsp_synced_last_line_len =
328 self.buffer.line_len(self.lsp_synced_line_count.saturating_sub(1));
329 }
330
331 pub fn set_lsp_enabled(&mut self, enabled: bool) {
347 self.lsp_enabled = enabled;
348 if !enabled {
349 self.detach_lsp();
350 }
351 }
352
353 pub fn lsp_enabled(&self) -> bool {
357 self.lsp_enabled
358 }
359
360 pub fn lsp_request_definition(&mut self) {
365 let position = self.lsp_position_from_cursor();
366 self.with_lsp(|client, document| {
367 client.request_definition(document, position);
368 });
369 }
370
371 pub fn lsp_request_definition_at(&mut self, point: iced::Point) -> bool {
381 let Some(position) = self.lsp_position_from_point(point) else {
382 return false;
383 };
384 self.with_lsp(|client, document| {
385 client.request_definition(document, position);
386 })
387 .is_some()
388 }
389}
390
391fn open_lsp_document(
401 client: &mut dyn lsp::LspClient,
402 buffer: &TextBuffer,
403 mut document: lsp::LspDocument,
404) -> (lsp::LspDocument, String) {
405 document.version = 1;
406 let text = buffer.to_string();
407 client.did_open(&document, &text);
408 (document, text)
409}
410
411#[cfg(test)]
412mod tests {
413 use std::cell::RefCell;
414 use std::rc::Rc;
415
416 use crate::canvas_editor::Message;
417
418 use super::*;
419
420 #[derive(Default)]
421 struct TestLspClient {
422 changes: Rc<RefCell<Vec<Vec<lsp::LspTextChange>>>>,
423 }
424
425 impl lsp::LspClient for TestLspClient {
426 fn did_change(
427 &mut self,
428 _document: &lsp::LspDocument,
429 changes: &[lsp::LspTextChange],
430 ) {
431 self.changes.borrow_mut().push(changes.to_vec());
432 }
433 }
434
435 #[derive(Default)]
437 struct RecordingLspClient {
438 calls: Rc<RefCell<Vec<String>>>,
439 }
440
441 impl lsp::LspClient for RecordingLspClient {
442 fn did_open(&mut self, _document: &lsp::LspDocument, _text: &str) {
443 self.calls.borrow_mut().push("did_open".to_string());
444 }
445 fn did_close(&mut self, _document: &lsp::LspDocument) {
446 self.calls.borrow_mut().push("did_close".to_string());
447 }
448 fn did_save(&mut self, _document: &lsp::LspDocument, _text: &str) {
449 self.calls.borrow_mut().push("did_save".to_string());
450 }
451 fn request_hover(
452 &mut self,
453 _document: &lsp::LspDocument,
454 _position: lsp::LspPosition,
455 ) {
456 self.calls.borrow_mut().push("request_hover".to_string());
457 }
458 fn did_change(
459 &mut self,
460 _document: &lsp::LspDocument,
461 _changes: &[lsp::LspTextChange],
462 ) {
463 self.calls.borrow_mut().push("did_change".to_string());
464 }
465 }
466
467 #[test]
468 fn test_enqueue_lsp_change_auto_flush() {
469 let changes = Rc::new(RefCell::new(Vec::new()));
470 let client = TestLspClient { changes: Rc::clone(&changes) };
471 let mut editor = CodeEditor::new("hello", "rs");
472 editor.attach_lsp(
473 Box::new(client),
474 lsp::LspDocument::new("file:///test.rs", "rust"),
475 );
476 editor.set_lsp_auto_flush(true);
477
478 editor.buffer.insert_char(0, 5, '!');
479 editor.enqueue_lsp_change();
480
481 let changes = changes.borrow();
482 assert_eq!(changes.len(), 1);
483 assert_eq!(changes[0].len(), 1);
484 let change = &changes[0][0];
485 assert_eq!(change.text, "!");
486 assert_eq!(change.range.start.line, 0);
487 assert_eq!(change.range.start.character, 5);
488 assert_eq!(change.range.end.line, 0);
489 assert_eq!(change.range.end.character, 5);
490 }
491
492 #[test]
493 fn test_editor_update_sends_bounded_incremental_lsp_change() {
494 let changes = Rc::new(RefCell::new(Vec::new()));
495 let client = TestLspClient { changes: Rc::clone(&changes) };
496 let content = (0..10)
497 .map(|line| format!("line{line}"))
498 .collect::<Vec<_>>()
499 .join("\n");
500 let mut editor = CodeEditor::new(&content, "rs");
501 editor.attach_lsp(
502 Box::new(client),
503 lsp::LspDocument::new("file:///large.rs", "rust"),
504 );
505 editor.request_focus();
506 editor.has_canvas_focus = true;
507 editor.focus_locked = false;
508 editor.cursors.primary_mut().position = (5, 2);
509
510 let _ = editor.update(&Message::CharacterInput('X'));
511
512 let changes = changes.borrow();
513 assert_eq!(changes.len(), 1);
514 assert_eq!(changes[0].len(), 1);
515 let change = &changes[0][0];
516 assert_eq!(change.range.start.line, 4);
517 assert_eq!(change.range.start.character, 0);
518 assert_eq!(change.range.end.line, 7);
519 assert_eq!(change.range.end.character, 0);
520 assert_eq!(change.text, "line4\nliXne5\nline6\n");
521 assert!(!editor.lsp_shadow_is_current);
522 assert!(editor.lsp_shadow_text.is_empty());
523 }
524
525 #[test]
526 fn test_open_lsp_document_stamps_version_and_sends_did_open() {
527 let calls = Rc::new(RefCell::new(Vec::new()));
528 let mut client = RecordingLspClient { calls: Rc::clone(&calls) };
529 let buffer = TextBuffer::new("hello");
530 let document = lsp::LspDocument::new("file:///test.rs", "rust");
531
532 let (document, text) =
533 open_lsp_document(&mut client, &buffer, document);
534
535 assert_eq!(document.version, 1);
536 assert_eq!(text, "hello");
537 assert_eq!(calls.borrow().as_slice(), ["did_open"]);
538 }
539
540 #[test]
541 fn test_with_lsp_runs_closure_when_client_and_document_present() {
542 let calls = Rc::new(RefCell::new(Vec::new()));
543 let client = RecordingLspClient { calls: Rc::clone(&calls) };
544 let mut editor = CodeEditor::new("hello", "rs");
545 editor.attach_lsp(
546 Box::new(client),
547 lsp::LspDocument::new("file:///test.rs", "rust"),
548 );
549 calls.borrow_mut().clear(); let ran = editor.with_lsp(|client, document| {
552 client.did_save(document, "hello");
553 });
554
555 assert!(ran.is_some());
556 assert_eq!(calls.borrow().as_slice(), ["did_save"]);
557 }
558
559 #[test]
560 fn test_with_lsp_returns_none_when_client_absent() {
561 let mut editor = CodeEditor::new("hello", "rs");
562 let ran = editor.with_lsp(|_client, _document| {});
563 assert!(ran.is_none());
564 }
565
566 #[test]
567 fn test_lsp_did_save_sends_current_buffer_contents() {
568 let calls = Rc::new(RefCell::new(Vec::new()));
569 let client = RecordingLspClient { calls: Rc::clone(&calls) };
570 let mut editor = CodeEditor::new("hello", "rs");
571 editor.attach_lsp(
572 Box::new(client),
573 lsp::LspDocument::new("file:///test.rs", "rust"),
574 );
575 calls.borrow_mut().clear(); editor.lsp_did_save();
578
579 assert_eq!(calls.borrow().as_slice(), ["did_save"]);
580 }
581
582 #[test]
583 fn test_lsp_did_save_is_a_noop_without_an_attached_client() {
584 let mut editor = CodeEditor::new("hello", "rs");
587 editor.lsp_did_save(); }
589
590 #[test]
591 fn test_with_lsp_returns_none_when_document_absent() {
592 let calls = Rc::new(RefCell::new(Vec::new()));
593 let client = RecordingLspClient { calls: Rc::clone(&calls) };
594 let mut editor = CodeEditor::new("hello", "rs");
595 editor.attach_lsp(
596 Box::new(client),
597 lsp::LspDocument::new("file:///test.rs", "rust"),
598 );
599 editor.lsp_document = None;
600
601 let ran = editor.with_lsp(|_client, _document| {});
602 assert!(ran.is_none());
603 }
604
605 #[test]
606 #[allow(clippy::unwrap_used)]
607 fn test_with_lsp_mut_document_allows_version_bump() {
608 let calls = Rc::new(RefCell::new(Vec::new()));
609 let client = RecordingLspClient { calls: Rc::clone(&calls) };
610 let mut editor = CodeEditor::new("hello", "rs");
611 editor.attach_lsp(
612 Box::new(client),
613 lsp::LspDocument::new("file:///test.rs", "rust"),
614 );
615
616 editor.with_lsp_mut_document(|_client, document| {
617 document.version = document.version.saturating_add(1);
618 });
619
620 assert_eq!(editor.lsp_document.as_ref().unwrap().version, 2);
621 }
622
623 #[test]
624 fn test_lsp_flush_pending_changes_preserves_queue_when_no_client_attached()
625 {
626 let mut editor = CodeEditor::new("hello", "rs");
627 editor.lsp_pending_changes.push(lsp::LspTextChange {
628 range: lsp::LspRange {
629 start: lsp::LspPosition { line: 0, character: 0 },
630 end: lsp::LspPosition { line: 0, character: 0 },
631 },
632 text: "x".to_string(),
633 });
634
635 editor.lsp_flush_pending_changes();
636
637 assert_eq!(editor.lsp_pending_changes.len(), 1);
638 }
639}