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 { uri: uri.into(), language_id: language_id.into(), version: 0 }
78    }
79}
80
81/// A text range in an LSP document.
82///
83/// `start` is inclusive and `end` is exclusive, so an empty range (a pure
84/// insertion point) has `start == end`.
85///
86/// # Example
87///
88/// ```
89/// use iced_code_editor::{LspPosition, LspRange};
90///
91/// // The first four characters of the first line.
92/// let range = LspRange {
93///     start: LspPosition { line: 0, character: 0 },
94///     end: LspPosition { line: 0, character: 4 },
95/// };
96/// assert_eq!(range.end.character - range.start.character, 4);
97/// ```
98#[derive(Debug, Clone, Copy)]
99pub struct LspRange {
100    /// Range start (inclusive).
101    pub start: LspPosition,
102    /// Range end (exclusive).
103    pub end: LspPosition,
104}
105
106/// A text change described by a range replacement.
107///
108/// An insertion is an empty `range` with non-empty `text`; a deletion is a
109/// non-empty `range` with empty `text`.
110///
111/// # Example
112///
113/// ```
114/// use iced_code_editor::{LspPosition, LspRange, LspTextChange};
115///
116/// // Insert "hi" at the start of the document: an empty range.
117/// let insertion = LspTextChange {
118///     range: LspRange {
119///         start: LspPosition { line: 0, character: 0 },
120///         end: LspPosition { line: 0, character: 0 },
121///     },
122///     text: "hi".to_string(),
123/// };
124/// assert_eq!(insertion.range.start, insertion.range.end);
125/// ```
126#[derive(Debug, Clone)]
127pub struct LspTextChange {
128    /// Range replaced by the change.
129    pub range: LspRange,
130    /// Inserted text.
131    pub text: String,
132}
133
134/// LSP client hooks invoked by the editor.
135///
136/// Every method has a no-op default, so an implementation only overrides the
137/// notifications and requests it actually cares about. Attach one with
138/// [`CodeEditor::attach_lsp`]; the editor never blocks on a response, so
139/// request results come back through whatever channel the implementation
140/// chooses.
141///
142/// # Example
143///
144/// ```
145/// use std::cell::RefCell;
146/// use std::rc::Rc;
147///
148/// use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspTextChange};
149///
150/// /// A client that only records how many change batches it received.
151/// struct CountingClient(Rc<RefCell<usize>>);
152///
153/// impl LspClient for CountingClient {
154///     fn did_change(&mut self, _document: &LspDocument, changes: &[LspTextChange]) {
155///         *self.0.borrow_mut() += changes.len();
156///     }
157/// }
158///
159/// let changes = Rc::new(RefCell::new(0));
160/// let mut editor = CodeEditor::new("fn main() {}", "rs");
161/// editor.attach_lsp(
162///     Box::new(CountingClient(Rc::clone(&changes))),
163///     LspDocument::new("file:///tmp/main.rs", "rust"),
164/// );
165///
166/// // `did_open` fired, but no change has been flushed yet.
167/// assert_eq!(*changes.borrow(), 0);
168/// ```
169///
170/// [`CodeEditor::attach_lsp`]: crate::CodeEditor::attach_lsp
171pub trait LspClient {
172    /// Notifies the client that a document was opened.
173    fn did_open(&mut self, _document: &LspDocument, _text: &str) {}
174    /// Notifies the client that the document changed.
175    fn did_change(
176        &mut self,
177        _document: &LspDocument,
178        _changes: &[LspTextChange],
179    ) {
180    }
181    /// Notifies the client that the document was saved.
182    fn did_save(&mut self, _document: &LspDocument, _text: &str) {}
183    /// Notifies the client that the document was closed.
184    fn did_close(&mut self, _document: &LspDocument) {}
185    /// Requests hover information at the given position.
186    fn request_hover(
187        &mut self,
188        _document: &LspDocument,
189        _position: LspPosition,
190    ) {
191    }
192    /// Requests completion items at the given position.
193    fn request_completion(
194        &mut self,
195        _document: &LspDocument,
196        _position: LspPosition,
197    ) {
198    }
199    /// Requests the definition location(s) for the symbol at the given position.
200    ///
201    /// This method is called when the user triggers a "Go to Definition" action
202    /// (e.g., via Ctrl+Click or a context menu). The client implementation should
203    /// send a `textDocument/definition` request to the LSP server.
204    fn request_definition(
205        &mut self,
206        _document: &LspDocument,
207        _position: LspPosition,
208    ) {
209    }
210}
211
212/// Computes a minimal text change between two snapshots.
213///
214/// The change is narrowed by trimming the common prefix and suffix, so a
215/// one-character edit in a large document produces a one-character change
216/// rather than a whole-document replacement. This is what lets the editor send
217/// incremental `didChange` notifications instead of resending the buffer.
218///
219/// # Arguments
220///
221/// * `old` - The previous document contents
222/// * `new` - The current document contents
223///
224/// # Returns
225///
226/// `Some(change)` describing the edit, or `None` when the snapshots are identical
227///
228/// # Example
229///
230/// ```
231/// use iced_code_editor::compute_text_change;
232///
233/// // Identical snapshots produce no change at all.
234/// assert!(compute_text_change("fn main() {}", "fn main() {}").is_none());
235///
236/// // Only the differing region is reported, not the whole line.
237/// let change = compute_text_change("let x = 1;", "let x = 42;")
238///     .expect("the snapshots differ");
239/// assert_eq!(change.text, "42");
240/// assert_eq!(change.range.start.character, 8);
241/// assert_eq!(change.range.end.character, 9);
242/// ```
243pub fn compute_text_change(old: &str, new: &str) -> Option<LspTextChange> {
244    if old == new {
245        return None;
246    }
247
248    let old_chars: Vec<char> = old.chars().collect();
249    let new_chars: Vec<char> = new.chars().collect();
250    let old_len = old_chars.len();
251    let new_len = new_chars.len();
252
253    let mut prefix = 0;
254    while prefix < old_len
255        && prefix < new_len
256        && old_chars[prefix] == new_chars[prefix]
257    {
258        prefix += 1;
259    }
260
261    let mut suffix = 0;
262    while suffix < old_len.saturating_sub(prefix)
263        && suffix < new_len.saturating_sub(prefix)
264        && old_chars[old_len - 1 - suffix] == new_chars[new_len - 1 - suffix]
265    {
266        suffix += 1;
267    }
268
269    let removed_len = old_len.saturating_sub(prefix + suffix);
270    let inserted: String =
271        new_chars[prefix..new_len.saturating_sub(suffix)].iter().collect();
272
273    let start = position_for_char_index(old, prefix);
274    let end = position_for_char_index(old, prefix + removed_len);
275
276    Some(LspTextChange { range: LspRange { start, end }, text: inserted })
277}
278
279/// Converts a character index into a line/character position.
280fn position_for_char_index(text: &str, target_index: usize) -> LspPosition {
281    let mut line: u32 = 0;
282    let mut character: u32 = 0;
283    for (index, ch) in text.chars().enumerate() {
284        if index == target_index {
285            return LspPosition { line, character };
286        }
287        if ch == '\n' {
288            line = line.saturating_add(1);
289            character = 0;
290        } else {
291            character = character.saturating_add(1);
292        }
293    }
294
295    LspPosition { line, character }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn test_compute_text_change_none_when_equal() {
304        let change = compute_text_change("abc", "abc");
305        assert!(change.is_none());
306    }
307
308    #[test]
309    fn test_compute_text_change_insertion() {
310        let change = compute_text_change("abc", "abXc");
311        assert!(change.is_some());
312        if let Some(change) = change {
313            assert_eq!(change.text, "X");
314            assert_eq!(
315                change.range.start,
316                LspPosition { line: 0, character: 2 }
317            );
318            assert_eq!(change.range.end, LspPosition { line: 0, character: 2 });
319        }
320    }
321
322    #[test]
323    fn test_compute_text_change_deletion_across_lines() {
324        let change = compute_text_change("a\nbc", "a\nc");
325        assert!(change.is_some());
326        if let Some(change) = change {
327            assert_eq!(change.text, "");
328            assert_eq!(
329                change.range.start,
330                LspPosition { line: 1, character: 0 }
331            );
332            assert_eq!(change.range.end, LspPosition { line: 1, character: 1 });
333        }
334    }
335
336    #[test]
337    fn test_position_for_char_index_end_of_text() {
338        let pos = position_for_char_index("a\nb", 3);
339        assert_eq!(pos, LspPosition { line: 1, character: 1 });
340    }
341}