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 edits;
4pub(crate) mod sync;
5
6use crate::canvas_editor::IndentStyle;
7use crate::canvas_editor::metrics::TAB_WIDTH;
8
9#[cfg(all(feature = "lsp-process", not(target_arch = "wasm32")))]
10pub mod process;
11
12/// A zero-based position in an LSP document.
13///
14/// Both fields are zero-based, unlike the one-based line numbers shown in the
15/// editor's gutter.
16///
17/// # Example
18///
19/// ```
20/// use iced_code_editor::LspPosition;
21///
22/// // The gutter's "line 3, column 1" is this position.
23/// let position = LspPosition { line: 2, character: 0 };
24/// assert_eq!(position.line, 2);
25/// ```
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct LspPosition {
28    /// Zero-based line index.
29    pub line: u32,
30    /// Zero-based character index on the line.
31    pub character: u32,
32}
33
34/// Metadata describing the currently edited document.
35///
36/// The editor stamps `version` itself: [`CodeEditor::attach_lsp`] sets it to 1
37/// on open, and each flushed batch of changes increments it.
38///
39/// # Example
40///
41/// ```
42/// use iced_code_editor::LspDocument;
43///
44/// let document = LspDocument::new("file:///tmp/main.rs", "rust");
45/// assert_eq!(document.uri, "file:///tmp/main.rs");
46/// assert_eq!(document.language_id, "rust");
47/// ```
48///
49/// [`CodeEditor::attach_lsp`]: crate::CodeEditor::attach_lsp
50#[derive(Debug, Clone)]
51pub struct LspDocument {
52    /// Document URI.
53    pub uri: String,
54    /// Language identifier for syntax services.
55    pub language_id: String,
56    /// Version number used for LSP change notifications.
57    pub version: i32,
58}
59
60impl LspDocument {
61    /// Creates a new LSP document descriptor with version set to 0.
62    ///
63    /// # Arguments
64    ///
65    /// * `uri` - The document URI, e.g. `file:///path/to/main.rs`
66    /// * `language_id` - The LSP language identifier, e.g. `rust`
67    ///
68    /// # Returns
69    ///
70    /// A descriptor at version 0; the editor stamps version 1 on open
71    ///
72    /// # Example
73    ///
74    /// ```
75    /// use iced_code_editor::LspDocument;
76    ///
77    /// let document = LspDocument::new("file:///tmp/main.rs", "rust");
78    /// assert_eq!(document.version, 0);
79    /// ```
80    pub fn new(uri: impl Into<String>, language_id: impl Into<String>) -> Self {
81        Self { uri: uri.into(), language_id: language_id.into(), version: 0 }
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/// Formatting options sent with a document-formatting request.
139///
140/// Mirrors the two fields of LSP's `FormattingOptions` that every server
141/// requires. Build one from the editor's own indentation setting with the
142/// `From<IndentStyle>` implementation rather than hardcoding values, so the
143/// server formats the way the editor indents.
144///
145/// # Example
146///
147/// ```
148/// use iced_code_editor::{IndentStyle, LspFormattingOptions};
149///
150/// let options = LspFormattingOptions::from(IndentStyle::Spaces(2));
151/// assert_eq!(options.tab_size, 2);
152/// assert!(options.insert_spaces);
153/// ```
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub struct LspFormattingOptions {
156    /// Number of columns a single indentation level spans.
157    pub tab_size: u32,
158    /// `true` to indent with spaces, `false` to indent with tab characters.
159    pub insert_spaces: bool,
160}
161
162impl From<IndentStyle> for LspFormattingOptions {
163    /// Derives formatting options from the editor's indentation style.
164    ///
165    /// [`IndentStyle::Tab`] reports the editor's own rendered tab width, which
166    /// is what the server needs to lay out alignment inside a tab-indented
167    /// file. A zero-width spaces style — which no built-in preset produces —
168    /// is raised to 1, since `tabSize: 0` is not a value any server can act on.
169    ///
170    /// # Example
171    ///
172    /// ```
173    /// use iced_code_editor::{IndentStyle, LspFormattingOptions};
174    ///
175    /// let options = LspFormattingOptions::from(IndentStyle::Tab);
176    /// assert!(!options.insert_spaces);
177    /// ```
178    fn from(style: IndentStyle) -> Self {
179        match style {
180            IndentStyle::Spaces(width) => {
181                Self { tab_size: u32::from(width).max(1), insert_spaces: true }
182            }
183            IndentStyle::Tab => {
184                Self { tab_size: TAB_WIDTH as u32, insert_spaces: false }
185            }
186        }
187    }
188}
189
190/// LSP client hooks invoked by the editor.
191///
192/// Every method has a no-op default, so an implementation only overrides the
193/// notifications and requests it actually cares about. Attach one with
194/// [`CodeEditor::attach_lsp`]; the editor never blocks on a response, so
195/// request results come back through whatever channel the implementation
196/// chooses.
197///
198/// # Example
199///
200/// ```
201/// use std::cell::RefCell;
202/// use std::rc::Rc;
203///
204/// use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspTextChange};
205///
206/// /// A client that only records how many change batches it received.
207/// struct CountingClient(Rc<RefCell<usize>>);
208///
209/// impl LspClient for CountingClient {
210///     fn did_change(&mut self, _document: &LspDocument, changes: &[LspTextChange]) {
211///         *self.0.borrow_mut() += changes.len();
212///     }
213/// }
214///
215/// let changes = Rc::new(RefCell::new(0));
216/// let mut editor = CodeEditor::new("fn main() {}", "rs");
217/// editor.attach_lsp(
218///     Box::new(CountingClient(Rc::clone(&changes))),
219///     LspDocument::new("file:///tmp/main.rs", "rust"),
220/// );
221///
222/// // `did_open` fired, but no change has been flushed yet.
223/// assert_eq!(*changes.borrow(), 0);
224/// ```
225///
226/// [`CodeEditor::attach_lsp`]: crate::CodeEditor::attach_lsp
227pub trait LspClient {
228    /// Notifies the client that a document was opened.
229    fn did_open(&mut self, _document: &LspDocument, _text: &str) {}
230    /// Notifies the client that the document changed.
231    fn did_change(
232        &mut self,
233        _document: &LspDocument,
234        _changes: &[LspTextChange],
235    ) {
236    }
237    /// Notifies the client that the document was saved.
238    fn did_save(&mut self, _document: &LspDocument, _text: &str) {}
239    /// Notifies the client that the document was closed.
240    fn did_close(&mut self, _document: &LspDocument) {}
241    /// Requests hover information at the given position.
242    fn request_hover(
243        &mut self,
244        _document: &LspDocument,
245        _position: LspPosition,
246    ) {
247    }
248    /// Requests completion items at the given position.
249    fn request_completion(
250        &mut self,
251        _document: &LspDocument,
252        _position: LspPosition,
253    ) {
254    }
255    /// Requests the definition location(s) for the symbol at the given position.
256    ///
257    /// This method is called when the user triggers a "Go to Definition" action
258    /// (e.g., via Ctrl+Click or a context menu). The client implementation should
259    /// send a `textDocument/definition` request to the LSP server.
260    fn request_definition(
261        &mut self,
262        _document: &LspDocument,
263        _position: LspPosition,
264    ) {
265    }
266    /// Requests formatting edits for the whole document.
267    ///
268    /// This method is called when the user triggers a "Format Document"
269    /// action, or when the host formats before saving. The client
270    /// implementation should send a `textDocument/formatting` request to the
271    /// LSP server; the resulting edits come back through whatever channel the
272    /// implementation uses, and the host applies them with
273    /// [`CodeEditor::apply_lsp_text_edits`].
274    ///
275    /// [`CodeEditor::apply_lsp_text_edits`]: crate::CodeEditor::apply_lsp_text_edits
276    fn request_formatting(
277        &mut self,
278        _document: &LspDocument,
279        _options: LspFormattingOptions,
280    ) {
281    }
282}
283
284/// Computes a minimal text change between two snapshots.
285///
286/// The change is narrowed by trimming the common prefix and suffix, so a
287/// one-character edit in a large document produces a one-character change
288/// rather than a whole-document replacement. This is what lets the editor send
289/// incremental `didChange` notifications instead of resending the buffer.
290///
291/// # Arguments
292///
293/// * `old` - The previous document contents
294/// * `new` - The current document contents
295///
296/// # Returns
297///
298/// `Some(change)` describing the edit, or `None` when the snapshots are identical
299///
300/// # Example
301///
302/// ```
303/// use iced_code_editor::compute_text_change;
304///
305/// // Identical snapshots produce no change at all.
306/// assert!(compute_text_change("fn main() {}", "fn main() {}").is_none());
307///
308/// // Only the differing region is reported, not the whole line.
309/// let change = compute_text_change("let x = 1;", "let x = 42;")
310///     .expect("the snapshots differ");
311/// assert_eq!(change.text, "42");
312/// assert_eq!(change.range.start.character, 8);
313/// assert_eq!(change.range.end.character, 9);
314/// ```
315pub fn compute_text_change(old: &str, new: &str) -> Option<LspTextChange> {
316    if old == new {
317        return None;
318    }
319
320    let old_chars: Vec<char> = old.chars().collect();
321    let new_chars: Vec<char> = new.chars().collect();
322    let old_len = old_chars.len();
323    let new_len = new_chars.len();
324
325    let mut prefix = 0;
326    while prefix < old_len
327        && prefix < new_len
328        && old_chars[prefix] == new_chars[prefix]
329    {
330        prefix += 1;
331    }
332
333    let mut suffix = 0;
334    while suffix < old_len.saturating_sub(prefix)
335        && suffix < new_len.saturating_sub(prefix)
336        && old_chars[old_len - 1 - suffix] == new_chars[new_len - 1 - suffix]
337    {
338        suffix += 1;
339    }
340
341    let removed_len = old_len.saturating_sub(prefix + suffix);
342    let inserted: String =
343        new_chars[prefix..new_len.saturating_sub(suffix)].iter().collect();
344
345    let start = position_for_char_index(old, prefix);
346    let end = position_for_char_index(old, prefix + removed_len);
347
348    Some(LspTextChange { range: LspRange { start, end }, text: inserted })
349}
350
351/// Converts a character index into a line/character position.
352fn position_for_char_index(text: &str, target_index: usize) -> LspPosition {
353    let mut line: u32 = 0;
354    let mut character: u32 = 0;
355    for (index, ch) in text.chars().enumerate() {
356        if index == target_index {
357            return LspPosition { line, character };
358        }
359        if ch == '\n' {
360            line = line.saturating_add(1);
361            character = 0;
362        } else {
363            character = character.saturating_add(1);
364        }
365    }
366
367    LspPosition { line, character }
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    #[test]
375    fn test_compute_text_change_none_when_equal() {
376        let change = compute_text_change("abc", "abc");
377        assert!(change.is_none());
378    }
379
380    #[test]
381    fn test_compute_text_change_insertion() {
382        let change = compute_text_change("abc", "abXc");
383        assert!(change.is_some());
384        if let Some(change) = change {
385            assert_eq!(change.text, "X");
386            assert_eq!(
387                change.range.start,
388                LspPosition { line: 0, character: 2 }
389            );
390            assert_eq!(change.range.end, LspPosition { line: 0, character: 2 });
391        }
392    }
393
394    #[test]
395    fn test_compute_text_change_deletion_across_lines() {
396        let change = compute_text_change("a\nbc", "a\nc");
397        assert!(change.is_some());
398        if let Some(change) = change {
399            assert_eq!(change.text, "");
400            assert_eq!(
401                change.range.start,
402                LspPosition { line: 1, character: 0 }
403            );
404            assert_eq!(change.range.end, LspPosition { line: 1, character: 1 });
405        }
406    }
407
408    #[test]
409    fn test_position_for_char_index_end_of_text() {
410        let pos = position_for_char_index("a\nb", 3);
411        assert_eq!(pos, LspPosition { line: 1, character: 1 });
412    }
413
414    #[test]
415    fn test_formatting_options_from_spaces_indent_style() {
416        let options = LspFormattingOptions::from(IndentStyle::Spaces(2));
417        assert_eq!(
418            options,
419            LspFormattingOptions { tab_size: 2, insert_spaces: true }
420        );
421    }
422
423    #[test]
424    fn test_formatting_options_from_tab_indent_style() {
425        let options = LspFormattingOptions::from(IndentStyle::Tab);
426        assert_eq!(
427            options,
428            LspFormattingOptions {
429                tab_size: TAB_WIDTH as u32,
430                insert_spaces: false,
431            }
432        );
433    }
434
435    #[test]
436    fn test_formatting_options_never_report_a_zero_tab_size() {
437        // `tabSize: 0` is not a value a server can lay text out with.
438        assert_eq!(
439            LspFormattingOptions::from(IndentStyle::Spaces(0)).tab_size,
440            1
441        );
442    }
443}