Skip to main content

iced_code_editor/canvas_editor/lsp/
mod.rs

1//! Minimal LSP types and helpers used by the editor.
2
3pub(crate) mod sync;
4
5#[cfg(all(feature = "lsp-process", not(target_arch = "wasm32")))]
6pub mod process;
7
8/// A zero-based position in an LSP document.
9///
10/// Both fields are zero-based, unlike the one-based line numbers shown in the
11/// editor's gutter.
12///
13/// # Example
14///
15/// ```
16/// use iced_code_editor::LspPosition;
17///
18/// // The gutter's "line 3, column 1" is this position.
19/// let position = LspPosition { line: 2, character: 0 };
20/// assert_eq!(position.line, 2);
21/// ```
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct LspPosition {
24    /// Zero-based line index.
25    pub line: u32,
26    /// Zero-based character index on the line.
27    pub character: u32,
28}
29
30/// Metadata describing the currently edited document.
31///
32/// The editor stamps `version` itself: [`CodeEditor::attach_lsp`] sets it to 1
33/// on open, and each flushed batch of changes increments it.
34///
35/// # Example
36///
37/// ```
38/// use iced_code_editor::LspDocument;
39///
40/// let document = LspDocument::new("file:///tmp/main.rs", "rust");
41/// assert_eq!(document.uri, "file:///tmp/main.rs");
42/// assert_eq!(document.language_id, "rust");
43/// ```
44///
45/// [`CodeEditor::attach_lsp`]: crate::CodeEditor::attach_lsp
46#[derive(Debug, Clone)]
47pub struct LspDocument {
48    /// Document URI.
49    pub uri: String,
50    /// Language identifier for syntax services.
51    pub language_id: String,
52    /// Version number used for LSP change notifications.
53    pub version: i32,
54}
55
56impl LspDocument {
57    /// Creates a new LSP document descriptor with version set to 0.
58    ///
59    /// # Arguments
60    ///
61    /// * `uri` - The document URI, e.g. `file:///path/to/main.rs`
62    /// * `language_id` - The LSP language identifier, e.g. `rust`
63    ///
64    /// # Returns
65    ///
66    /// A descriptor at version 0; the editor stamps version 1 on open
67    ///
68    /// # Example
69    ///
70    /// ```
71    /// use iced_code_editor::LspDocument;
72    ///
73    /// let document = LspDocument::new("file:///tmp/main.rs", "rust");
74    /// assert_eq!(document.version, 0);
75    /// ```
76    pub fn new(uri: impl Into<String>, language_id: impl Into<String>) -> Self {
77        Self {
78            uri: uri.into(),
79            language_id: language_id.into(),
80            version: 0,
81        }
82    }
83}
84
85/// A text range in an LSP document.
86///
87/// `start` is inclusive and `end` is exclusive, so an empty range (a pure
88/// insertion point) has `start == end`.
89///
90/// # Example
91///
92/// ```
93/// use iced_code_editor::{LspPosition, LspRange};
94///
95/// // The first four characters of the first line.
96/// let range = LspRange {
97///     start: LspPosition { line: 0, character: 0 },
98///     end: LspPosition { line: 0, character: 4 },
99/// };
100/// assert_eq!(range.end.character - range.start.character, 4);
101/// ```
102#[derive(Debug, Clone, Copy)]
103pub struct LspRange {
104    /// Range start (inclusive).
105    pub start: LspPosition,
106    /// Range end (exclusive).
107    pub end: LspPosition,
108}
109
110/// A text change described by a range replacement.
111///
112/// An insertion is an empty `range` with non-empty `text`; a deletion is a
113/// non-empty `range` with empty `text`.
114///
115/// # Example
116///
117/// ```
118/// use iced_code_editor::{LspPosition, LspRange, LspTextChange};
119///
120/// // Insert "hi" at the start of the document: an empty range.
121/// let insertion = LspTextChange {
122///     range: LspRange {
123///         start: LspPosition { line: 0, character: 0 },
124///         end: LspPosition { line: 0, character: 0 },
125///     },
126///     text: "hi".to_string(),
127/// };
128/// assert_eq!(insertion.range.start, insertion.range.end);
129/// ```
130#[derive(Debug, Clone)]
131pub struct LspTextChange {
132    /// Range replaced by the change.
133    pub range: LspRange,
134    /// Inserted text.
135    pub text: String,
136}
137
138/// A symbol in a document's outline, as reported by `textDocument/documentSymbol`.
139///
140/// Symbols form a tree: a method sits in the `children` of its type, which
141/// sits in the `children` of its module. Servers that only return a flat list
142/// are nested by range containment when the response is parsed.
143///
144/// # Example
145///
146/// ```
147/// use iced_code_editor::{LspPosition, LspRange, LspSymbol};
148///
149/// let symbol = LspSymbol {
150///     name: "main".to_string(),
151///     range: LspRange {
152///         start: LspPosition { line: 0, character: 0 },
153///         end: LspPosition { line: 2, character: 1 },
154///     },
155///     children: Vec::new(),
156/// };
157/// assert!(symbol.contains_line(1));
158/// assert!(!symbol.contains_line(3));
159/// ```
160#[derive(Debug, Clone)]
161pub struct LspSymbol {
162    /// Name shown for the symbol, such as a function or type name.
163    pub name: String,
164    /// Full range of the symbol, including its body.
165    pub range: LspRange,
166    /// Symbols declared inside this one.
167    pub children: Vec<LspSymbol>,
168}
169
170impl LspSymbol {
171    /// Returns `true` if the zero-based `line` falls inside this symbol's range.
172    ///
173    /// # Arguments
174    ///
175    /// * `line` - Zero-based line number to test
176    ///
177    /// # Returns
178    ///
179    /// `true` when `line` is between the range's start and end lines, inclusive
180    pub fn contains_line(&self, line: u32) -> bool {
181        self.range.start.line <= line && line <= self.range.end.line
182    }
183}
184
185/// Returns the names of the symbols enclosing `line`, outermost first.
186///
187/// At each level the first symbol whose range contains `line` is entered, so
188/// the result reads like a breadcrumb trail: `["Editor", "render"]` for a
189/// line inside the `render` method of `Editor`.
190///
191/// # Arguments
192///
193/// * `symbols` - Top-level symbols of the document
194/// * `line` - Zero-based line number
195///
196/// # Returns
197///
198/// The chain of enclosing symbol names, empty when `line` is outside every symbol
199///
200/// # Example
201///
202/// ```
203/// use iced_code_editor::{LspPosition, LspRange, LspSymbol, symbol_path_at};
204///
205/// let range = |start, end| LspRange {
206///     start: LspPosition { line: start, character: 0 },
207///     end: LspPosition { line: end, character: 0 },
208/// };
209/// let symbols = vec![LspSymbol {
210///     name: "Editor".to_string(),
211///     range: range(0, 10),
212///     children: vec![LspSymbol {
213///         name: "render".to_string(),
214///         range: range(2, 5),
215///         children: Vec::new(),
216///     }],
217/// }];
218///
219/// assert_eq!(symbol_path_at(&symbols, 3), ["Editor", "render"]);
220/// assert_eq!(symbol_path_at(&symbols, 8), ["Editor"]);
221/// assert!(symbol_path_at(&symbols, 11).is_empty());
222/// ```
223pub fn symbol_path_at(symbols: &[LspSymbol], line: u32) -> Vec<String> {
224    let mut path = Vec::new();
225    let mut level = symbols;
226    while let Some(symbol) = level.iter().find(|symbol| symbol.contains_line(line)) {
227        path.push(symbol.name.clone());
228        level = &symbol.children;
229    }
230    path
231}
232
233/// LSP client hooks invoked by the editor.
234///
235/// Every method has a no-op default, so an implementation only overrides the
236/// notifications and requests it actually cares about. Attach one with
237/// [`CodeEditor::attach_lsp`]; the editor never blocks on a response, so
238/// request results come back through whatever channel the implementation
239/// chooses.
240///
241/// # Example
242///
243/// ```
244/// use std::cell::RefCell;
245/// use std::rc::Rc;
246///
247/// use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspTextChange};
248///
249/// /// A client that only records how many change batches it received.
250/// struct CountingClient(Rc<RefCell<usize>>);
251///
252/// impl LspClient for CountingClient {
253///     fn did_change(&mut self, _document: &LspDocument, changes: &[LspTextChange]) {
254///         *self.0.borrow_mut() += changes.len();
255///     }
256/// }
257///
258/// let changes = Rc::new(RefCell::new(0));
259/// let mut editor = CodeEditor::new("fn main() {}", "rs");
260/// editor.attach_lsp(
261///     Box::new(CountingClient(Rc::clone(&changes))),
262///     LspDocument::new("file:///tmp/main.rs", "rust"),
263/// );
264///
265/// // `did_open` fired, but no change has been flushed yet.
266/// assert_eq!(*changes.borrow(), 0);
267/// ```
268///
269/// [`CodeEditor::attach_lsp`]: crate::CodeEditor::attach_lsp
270pub trait LspClient {
271    /// Notifies the client that a document was opened.
272    fn did_open(&mut self, _document: &LspDocument, _text: &str) {}
273    /// Notifies the client that the document changed.
274    fn did_change(&mut self, _document: &LspDocument, _changes: &[LspTextChange]) {}
275    /// Notifies the client that the document was saved.
276    fn did_save(&mut self, _document: &LspDocument, _text: &str) {}
277    /// Notifies the client that the document was closed.
278    fn did_close(&mut self, _document: &LspDocument) {}
279    /// Requests hover information at the given position.
280    fn request_hover(&mut self, _document: &LspDocument, _position: LspPosition) {}
281    /// Requests completion items at the given position.
282    fn request_completion(&mut self, _document: &LspDocument, _position: LspPosition) {}
283    /// Requests the definition location(s) for the symbol at the given position.
284    ///
285    /// This method is called when the user triggers a "Go to Definition" action
286    /// (e.g., via Ctrl+Click or a context menu). The client implementation should
287    /// send a `textDocument/definition` request to the LSP server.
288    fn request_definition(&mut self, _document: &LspDocument, _position: LspPosition) {}
289    /// Requests the outline (`textDocument/documentSymbol`) of the document.
290    ///
291    /// The client implementation should send the request and report the
292    /// symbols back through its own channel, as with the other requests.
293    fn request_document_symbols(&mut self, _document: &LspDocument) {}
294}
295
296/// Computes a minimal text change between two snapshots.
297///
298/// The change is narrowed by trimming the common prefix and suffix, so a
299/// one-character edit in a large document produces a one-character change
300/// rather than a whole-document replacement. This is what lets the editor send
301/// incremental `didChange` notifications instead of resending the buffer.
302///
303/// # Arguments
304///
305/// * `old` - The previous document contents
306/// * `new` - The current document contents
307///
308/// # Returns
309///
310/// `Some(change)` describing the edit, or `None` when the snapshots are identical
311///
312/// # Example
313///
314/// ```
315/// use iced_code_editor::compute_text_change;
316///
317/// // Identical snapshots produce no change at all.
318/// assert!(compute_text_change("fn main() {}", "fn main() {}").is_none());
319///
320/// // Only the differing region is reported, not the whole line.
321/// let change = compute_text_change("let x = 1;", "let x = 42;")
322///     .expect("the snapshots differ");
323/// assert_eq!(change.text, "42");
324/// assert_eq!(change.range.start.character, 8);
325/// assert_eq!(change.range.end.character, 9);
326/// ```
327pub fn compute_text_change(old: &str, new: &str) -> Option<LspTextChange> {
328    if old == new {
329        return None;
330    }
331
332    let old_chars: Vec<char> = old.chars().collect();
333    let new_chars: Vec<char> = new.chars().collect();
334    let old_len = old_chars.len();
335    let new_len = new_chars.len();
336
337    let mut prefix = 0;
338    while prefix < old_len && prefix < new_len && old_chars[prefix] == new_chars[prefix] {
339        prefix += 1;
340    }
341
342    let mut suffix = 0;
343    while suffix < old_len.saturating_sub(prefix)
344        && suffix < new_len.saturating_sub(prefix)
345        && old_chars[old_len - 1 - suffix] == new_chars[new_len - 1 - suffix]
346    {
347        suffix += 1;
348    }
349
350    let removed_len = old_len.saturating_sub(prefix + suffix);
351    let inserted: String = new_chars[prefix..new_len.saturating_sub(suffix)].iter().collect();
352
353    let start = position_for_char_index(old, prefix);
354    let end = position_for_char_index(old, prefix + removed_len);
355
356    Some(LspTextChange {
357        range: LspRange { start, end },
358        text: inserted,
359    })
360}
361
362/// Converts a character index into a line/character position.
363fn position_for_char_index(text: &str, target_index: usize) -> LspPosition {
364    let mut line: u32 = 0;
365    let mut character: u32 = 0;
366    for (index, ch) in text.chars().enumerate() {
367        if index == target_index {
368            return LspPosition { line, character };
369        }
370        if ch == '\n' {
371            line = line.saturating_add(1);
372            character = 0;
373        } else {
374            character = character.saturating_add(1);
375        }
376    }
377
378    LspPosition { line, character }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    fn symbol(name: &str, start: u32, end: u32, children: Vec<LspSymbol>) -> LspSymbol {
386        LspSymbol {
387            name: name.to_string(),
388            range: LspRange {
389                start: LspPosition {
390                    line: start,
391                    character: 0,
392                },
393                end: LspPosition {
394                    line: end,
395                    character: 0,
396                },
397            },
398            children,
399        }
400    }
401
402    #[test]
403    fn test_symbol_path_at_picks_matching_sibling() {
404        let symbols = vec![
405            symbol("first", 0, 3, Vec::new()),
406            symbol("second", 5, 9, vec![symbol("inner", 6, 7, Vec::new())]),
407        ];
408        assert_eq!(symbol_path_at(&symbols, 6), ["second", "inner"]);
409        assert_eq!(symbol_path_at(&symbols, 9), ["second"]);
410        assert_eq!(symbol_path_at(&symbols, 2), ["first"]);
411    }
412
413    #[test]
414    fn test_symbol_path_at_between_symbols_is_empty() {
415        let symbols = vec![
416            symbol("first", 0, 3, Vec::new()),
417            symbol("second", 5, 9, Vec::new()),
418        ];
419        assert!(symbol_path_at(&symbols, 4).is_empty());
420        assert!(symbol_path_at(&[], 0).is_empty());
421    }
422
423    #[test]
424    fn test_compute_text_change_none_when_equal() {
425        let change = compute_text_change("abc", "abc");
426        assert!(change.is_none());
427    }
428
429    #[test]
430    fn test_compute_text_change_insertion() {
431        let change = compute_text_change("abc", "abXc");
432        assert!(change.is_some());
433        if let Some(change) = change {
434            assert_eq!(change.text, "X");
435            assert_eq!(
436                change.range.start,
437                LspPosition {
438                    line: 0,
439                    character: 2
440                }
441            );
442            assert_eq!(
443                change.range.end,
444                LspPosition {
445                    line: 0,
446                    character: 2
447                }
448            );
449        }
450    }
451
452    #[test]
453    fn test_compute_text_change_deletion_across_lines() {
454        let change = compute_text_change("a\nbc", "a\nc");
455        assert!(change.is_some());
456        if let Some(change) = change {
457            assert_eq!(change.text, "");
458            assert_eq!(
459                change.range.start,
460                LspPosition {
461                    line: 1,
462                    character: 0
463                }
464            );
465            assert_eq!(
466                change.range.end,
467                LspPosition {
468                    line: 1,
469                    character: 1
470                }
471            );
472        }
473    }
474
475    #[test]
476    fn test_position_for_char_index_end_of_text() {
477        let pos = position_for_char_index("a\nb", 3);
478        assert_eq!(
479            pos,
480            LspPosition {
481                line: 1,
482                character: 1
483            }
484        );
485    }
486}