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, PartialEq, Eq)]
103pub struct LspRange {
104    /// Range start (inclusive).
105    pub start: LspPosition,
106    /// Range end (exclusive).
107    pub end: LspPosition,
108}
109
110/// Severity of a diagnostic underline.
111///
112/// It selects the underline color among the `Style::diagnostic_*_color`
113/// fields.
114///
115/// # Example
116///
117/// ```
118/// use iced_code_editor::DiagnosticSeverity;
119///
120/// let severity = DiagnosticSeverity::Hint;
121/// assert_ne!(severity, DiagnosticSeverity::Error);
122/// ```
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum DiagnosticSeverity {
125    /// An error that usually prevents the code from compiling or running.
126    Error,
127    /// A potential problem that does not necessarily stop execution.
128    Warning,
129    /// Additional information about the code.
130    Information,
131    /// A suggestion that is less prominent than a warning.
132    Hint,
133}
134
135/// A diagnostic range to underline in the editor.
136///
137/// Passed to `CodeEditor::set_diagnostics`. The range uses logical lines and
138/// character columns (not UTF-16 offsets). The message is what a host shows
139/// when the pointer hovers the range (see `CodeEditor::diagnostics_at`).
140///
141/// # Example
142///
143/// ```
144/// use iced_code_editor::{Diagnostic, DiagnosticSeverity, LspPosition, LspRange};
145///
146/// let diagnostic = Diagnostic::new(
147///     LspRange {
148///         start: LspPosition { line: 2, character: 0 },
149///         end: LspPosition { line: 2, character: 5 },
150///     },
151///     DiagnosticSeverity::Error,
152///     "mismatched types",
153/// );
154/// assert_eq!(diagnostic.range.end.character, 5);
155/// assert_eq!(diagnostic.message, "mismatched types");
156/// ```
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Diagnostic {
159    /// Range to underline, with an inclusive start and exclusive end.
160    pub range: LspRange,
161    /// Severity that determines the underline color.
162    pub severity: DiagnosticSeverity,
163    /// Human-readable description of the problem. May be empty.
164    pub message: String,
165    /// Tool that produced the diagnostic, such as `rustc` or `clippy`.
166    /// `None` when the source did not say.
167    pub source: Option<String>,
168}
169
170impl Diagnostic {
171    /// Creates a diagnostic from its range, severity and message.
172    ///
173    /// # Example
174    ///
175    /// ```
176    /// use iced_code_editor::{Diagnostic, DiagnosticSeverity, LspPosition, LspRange};
177    ///
178    /// let at = LspPosition { line: 0, character: 3 };
179    /// let diagnostic = Diagnostic::new(
180    ///     LspRange { start: at, end: at },
181    ///     DiagnosticSeverity::Hint,
182    ///     "consider a shorter name",
183    /// );
184    /// assert_eq!(diagnostic.severity, DiagnosticSeverity::Hint);
185    /// ```
186    pub fn new(
187        range: LspRange,
188        severity: DiagnosticSeverity,
189        message: impl Into<String>,
190    ) -> Self {
191        Self { range, severity, message: message.into(), source: None }
192    }
193
194    /// Sets the tool that produced the diagnostic, such as `rustc` or
195    /// `clippy`.
196    ///
197    /// # Example
198    ///
199    /// ```
200    /// use iced_code_editor::{Diagnostic, DiagnosticSeverity, LspPosition, LspRange};
201    ///
202    /// let at = LspPosition { line: 0, character: 0 };
203    /// let diagnostic = Diagnostic::new(
204    ///     LspRange { start: at, end: at },
205    ///     DiagnosticSeverity::Warning,
206    ///     "redundant clone",
207    /// )
208    /// .with_source("clippy");
209    /// assert_eq!(diagnostic.source.as_deref(), Some("clippy"));
210    /// ```
211    #[must_use]
212    pub fn with_source(mut self, source: impl Into<String>) -> Self {
213        self.source = Some(source.into());
214        self
215    }
216
217    /// Whether `position` lies on the characters this diagnostic underlines.
218    ///
219    /// The end is exclusive. An empty range covers the one character at its
220    /// start, which is the character the editor underlines for it. A reversed
221    /// range covers nothing.
222    ///
223    /// # Example
224    ///
225    /// ```
226    /// use iced_code_editor::{Diagnostic, DiagnosticSeverity, LspPosition, LspRange};
227    ///
228    /// let diagnostic = Diagnostic::new(
229    ///     LspRange {
230    ///         start: LspPosition { line: 0, character: 4 },
231    ///         end: LspPosition { line: 0, character: 8 },
232    ///     },
233    ///     DiagnosticSeverity::Error,
234    ///     "unknown name",
235    /// );
236    /// assert!(diagnostic.contains(LspPosition { line: 0, character: 4 }));
237    /// assert!(!diagnostic.contains(LspPosition { line: 0, character: 8 }));
238    /// ```
239    pub fn contains(&self, position: LspPosition) -> bool {
240        let key = |p: LspPosition| (p.line, p.character);
241        let (start, end, at) =
242            (key(self.range.start), key(self.range.end), key(position));
243        if start == end { at == start } else { start <= at && at < end }
244    }
245}
246
247/// A text change described by a range replacement.
248///
249/// An insertion is an empty `range` with non-empty `text`; a deletion is a
250/// non-empty `range` with empty `text`.
251///
252/// # Example
253///
254/// ```
255/// use iced_code_editor::{LspPosition, LspRange, LspTextChange};
256///
257/// // Insert "hi" at the start of the document: an empty range.
258/// let insertion = LspTextChange {
259///     range: LspRange {
260///         start: LspPosition { line: 0, character: 0 },
261///         end: LspPosition { line: 0, character: 0 },
262///     },
263///     text: "hi".to_string(),
264/// };
265/// assert_eq!(insertion.range.start, insertion.range.end);
266/// ```
267#[derive(Debug, Clone)]
268pub struct LspTextChange {
269    /// Range replaced by the change.
270    pub range: LspRange,
271    /// Inserted text.
272    pub text: String,
273}
274
275/// Formatting options sent with a document-formatting request.
276///
277/// Mirrors the two fields of LSP's `FormattingOptions` that every server
278/// requires. Build one from the editor's own indentation setting with the
279/// `From<IndentStyle>` implementation rather than hardcoding values, so the
280/// server formats the way the editor indents.
281///
282/// # Example
283///
284/// ```
285/// use iced_code_editor::{IndentStyle, LspFormattingOptions};
286///
287/// let options = LspFormattingOptions::from(IndentStyle::Spaces(2));
288/// assert_eq!(options.tab_size, 2);
289/// assert!(options.insert_spaces);
290/// ```
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub struct LspFormattingOptions {
293    /// Number of columns a single indentation level spans.
294    pub tab_size: u32,
295    /// `true` to indent with spaces, `false` to indent with tab characters.
296    pub insert_spaces: bool,
297}
298
299impl From<IndentStyle> for LspFormattingOptions {
300    /// Derives formatting options from the editor's indentation style.
301    ///
302    /// [`IndentStyle::Tab`] reports the editor's own rendered tab width, which
303    /// is what the server needs to lay out alignment inside a tab-indented
304    /// file. A zero-width spaces style — which no built-in preset produces —
305    /// is raised to 1, since `tabSize: 0` is not a value any server can act on.
306    ///
307    /// # Example
308    ///
309    /// ```
310    /// use iced_code_editor::{IndentStyle, LspFormattingOptions};
311    ///
312    /// let options = LspFormattingOptions::from(IndentStyle::Tab);
313    /// assert!(!options.insert_spaces);
314    /// ```
315    fn from(style: IndentStyle) -> Self {
316        match style {
317            IndentStyle::Spaces(width) => {
318                Self { tab_size: u32::from(width).max(1), insert_spaces: true }
319            }
320            IndentStyle::Tab => {
321                Self { tab_size: TAB_WIDTH as u32, insert_spaces: false }
322            }
323        }
324    }
325}
326
327/// LSP client hooks invoked by the editor.
328///
329/// Every method has a no-op default, so an implementation only overrides the
330/// notifications and requests it actually cares about. Attach one with
331/// [`CodeEditor::attach_lsp`]; the editor never blocks on a response, so
332/// request results come back through whatever channel the implementation
333/// chooses.
334///
335/// # Example
336///
337/// ```
338/// use std::cell::RefCell;
339/// use std::rc::Rc;
340///
341/// use iced_code_editor::{CodeEditor, LspClient, LspDocument, LspTextChange};
342///
343/// /// A client that only records how many change batches it received.
344/// struct CountingClient(Rc<RefCell<usize>>);
345///
346/// impl LspClient for CountingClient {
347///     fn did_change(&mut self, _document: &LspDocument, changes: &[LspTextChange]) {
348///         *self.0.borrow_mut() += changes.len();
349///     }
350/// }
351///
352/// let changes = Rc::new(RefCell::new(0));
353/// let mut editor = CodeEditor::new("fn main() {}", "rs");
354/// editor.attach_lsp(
355///     Box::new(CountingClient(Rc::clone(&changes))),
356///     LspDocument::new("file:///tmp/main.rs", "rust"),
357/// );
358///
359/// // `did_open` fired, but no change has been flushed yet.
360/// assert_eq!(*changes.borrow(), 0);
361/// ```
362///
363/// [`CodeEditor::attach_lsp`]: crate::CodeEditor::attach_lsp
364pub trait LspClient {
365    /// Notifies the client that a document was opened.
366    fn did_open(&mut self, _document: &LspDocument, _text: &str) {}
367    /// Notifies the client that the document changed.
368    fn did_change(
369        &mut self,
370        _document: &LspDocument,
371        _changes: &[LspTextChange],
372    ) {
373    }
374    /// Notifies the client that the document was saved.
375    fn did_save(&mut self, _document: &LspDocument, _text: &str) {}
376    /// Notifies the client that the document was closed.
377    fn did_close(&mut self, _document: &LspDocument) {}
378    /// Requests hover information at the given position.
379    fn request_hover(
380        &mut self,
381        _document: &LspDocument,
382        _position: LspPosition,
383    ) {
384    }
385    /// Requests completion items at the given position.
386    fn request_completion(
387        &mut self,
388        _document: &LspDocument,
389        _position: LspPosition,
390    ) {
391    }
392    /// Requests the definition location(s) for the symbol at the given position.
393    ///
394    /// This method is called when the user triggers a "Go to Definition" action
395    /// (e.g., via Ctrl+Click or a context menu). The client implementation should
396    /// send a `textDocument/definition` request to the LSP server.
397    fn request_definition(
398        &mut self,
399        _document: &LspDocument,
400        _position: LspPosition,
401    ) {
402    }
403    /// Requests formatting edits for the whole document.
404    ///
405    /// This method is called when the user triggers a "Format Document"
406    /// action, or when the host formats before saving. The client
407    /// implementation should send a `textDocument/formatting` request to the
408    /// LSP server; the resulting edits come back through whatever channel the
409    /// implementation uses, and the host applies them with
410    /// [`CodeEditor::apply_lsp_text_edits`].
411    ///
412    /// [`CodeEditor::apply_lsp_text_edits`]: crate::CodeEditor::apply_lsp_text_edits
413    fn request_formatting(
414        &mut self,
415        _document: &LspDocument,
416        _options: LspFormattingOptions,
417    ) {
418    }
419}
420
421/// Computes a minimal text change between two snapshots.
422///
423/// The change is narrowed by trimming the common prefix and suffix, so a
424/// one-character edit in a large document produces a one-character change
425/// rather than a whole-document replacement. This is what lets the editor send
426/// incremental `didChange` notifications instead of resending the buffer.
427///
428/// # Arguments
429///
430/// * `old` - The previous document contents
431/// * `new` - The current document contents
432///
433/// # Returns
434///
435/// `Some(change)` describing the edit, or `None` when the snapshots are identical
436///
437/// # Example
438///
439/// ```
440/// use iced_code_editor::compute_text_change;
441///
442/// // Identical snapshots produce no change at all.
443/// assert!(compute_text_change("fn main() {}", "fn main() {}").is_none());
444///
445/// // Only the differing region is reported, not the whole line.
446/// let change = compute_text_change("let x = 1;", "let x = 42;")
447///     .expect("the snapshots differ");
448/// assert_eq!(change.text, "42");
449/// assert_eq!(change.range.start.character, 8);
450/// assert_eq!(change.range.end.character, 9);
451/// ```
452pub fn compute_text_change(old: &str, new: &str) -> Option<LspTextChange> {
453    if old == new {
454        return None;
455    }
456
457    let old_chars: Vec<char> = old.chars().collect();
458    let new_chars: Vec<char> = new.chars().collect();
459    let old_len = old_chars.len();
460    let new_len = new_chars.len();
461
462    let mut prefix = 0;
463    while prefix < old_len
464        && prefix < new_len
465        && old_chars[prefix] == new_chars[prefix]
466    {
467        prefix += 1;
468    }
469
470    let mut suffix = 0;
471    while suffix < old_len.saturating_sub(prefix)
472        && suffix < new_len.saturating_sub(prefix)
473        && old_chars[old_len - 1 - suffix] == new_chars[new_len - 1 - suffix]
474    {
475        suffix += 1;
476    }
477
478    let removed_len = old_len.saturating_sub(prefix + suffix);
479    let inserted: String =
480        new_chars[prefix..new_len.saturating_sub(suffix)].iter().collect();
481
482    let start = position_for_char_index(old, prefix);
483    let end = position_for_char_index(old, prefix + removed_len);
484
485    Some(LspTextChange { range: LspRange { start, end }, text: inserted })
486}
487
488/// Converts a character index into a line/character position.
489fn position_for_char_index(text: &str, target_index: usize) -> LspPosition {
490    let mut line: u32 = 0;
491    let mut character: u32 = 0;
492    for (index, ch) in text.chars().enumerate() {
493        if index == target_index {
494            return LspPosition { line, character };
495        }
496        if ch == '\n' {
497            line = line.saturating_add(1);
498            character = 0;
499        } else {
500            character = character.saturating_add(1);
501        }
502    }
503
504    LspPosition { line, character }
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510
511    #[test]
512    fn test_compute_text_change_none_when_equal() {
513        let change = compute_text_change("abc", "abc");
514        assert!(change.is_none());
515    }
516
517    #[test]
518    fn test_compute_text_change_insertion() {
519        let change = compute_text_change("abc", "abXc");
520        assert!(change.is_some());
521        if let Some(change) = change {
522            assert_eq!(change.text, "X");
523            assert_eq!(
524                change.range.start,
525                LspPosition { line: 0, character: 2 }
526            );
527            assert_eq!(change.range.end, LspPosition { line: 0, character: 2 });
528        }
529    }
530
531    #[test]
532    fn test_compute_text_change_deletion_across_lines() {
533        let change = compute_text_change("a\nbc", "a\nc");
534        assert!(change.is_some());
535        if let Some(change) = change {
536            assert_eq!(change.text, "");
537            assert_eq!(
538                change.range.start,
539                LspPosition { line: 1, character: 0 }
540            );
541            assert_eq!(change.range.end, LspPosition { line: 1, character: 1 });
542        }
543    }
544
545    #[test]
546    fn test_position_for_char_index_end_of_text() {
547        let pos = position_for_char_index("a\nb", 3);
548        assert_eq!(pos, LspPosition { line: 1, character: 1 });
549    }
550
551    #[test]
552    fn test_formatting_options_from_spaces_indent_style() {
553        let options = LspFormattingOptions::from(IndentStyle::Spaces(2));
554        assert_eq!(
555            options,
556            LspFormattingOptions { tab_size: 2, insert_spaces: true }
557        );
558    }
559
560    #[test]
561    fn test_formatting_options_from_tab_indent_style() {
562        let options = LspFormattingOptions::from(IndentStyle::Tab);
563        assert_eq!(
564            options,
565            LspFormattingOptions {
566                tab_size: TAB_WIDTH as u32,
567                insert_spaces: false,
568            }
569        );
570    }
571
572    #[test]
573    fn test_formatting_options_never_report_a_zero_tab_size() {
574        // `tabSize: 0` is not a value a server can lay text out with.
575        assert_eq!(
576            LspFormattingOptions::from(IndentStyle::Spaces(0)).tab_size,
577            1
578        );
579    }
580}