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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct LspPosition {
11    /// Zero-based line index.
12    pub line: u32,
13    /// Zero-based character index on the line.
14    pub character: u32,
15}
16
17/// Metadata describing the currently edited document.
18#[derive(Debug, Clone)]
19pub struct LspDocument {
20    /// Document URI.
21    pub uri: String,
22    /// Language identifier for syntax services.
23    pub language_id: String,
24    /// Version number used for LSP change notifications.
25    pub version: i32,
26}
27
28impl LspDocument {
29    /// Creates a new LSP document descriptor with version set to 0.
30    pub fn new(uri: impl Into<String>, language_id: impl Into<String>) -> Self {
31        Self { uri: uri.into(), language_id: language_id.into(), version: 0 }
32    }
33}
34
35/// A text range in an LSP document.
36#[derive(Debug, Clone, Copy)]
37pub struct LspRange {
38    /// Range start (inclusive).
39    pub start: LspPosition,
40    /// Range end (exclusive).
41    pub end: LspPosition,
42}
43
44/// A text change described by a range replacement.
45#[derive(Debug, Clone)]
46pub struct LspTextChange {
47    /// Range replaced by the change.
48    pub range: LspRange,
49    /// Inserted text.
50    pub text: String,
51}
52
53/// LSP client hooks invoked by the editor.
54pub trait LspClient {
55    /// Notifies the client that a document was opened.
56    fn did_open(&mut self, _document: &LspDocument, _text: &str) {}
57    /// Notifies the client that the document changed.
58    fn did_change(
59        &mut self,
60        _document: &LspDocument,
61        _changes: &[LspTextChange],
62    ) {
63    }
64    /// Notifies the client that the document was saved.
65    fn did_save(&mut self, _document: &LspDocument, _text: &str) {}
66    /// Notifies the client that the document was closed.
67    fn did_close(&mut self, _document: &LspDocument) {}
68    /// Requests hover information at the given position.
69    fn request_hover(
70        &mut self,
71        _document: &LspDocument,
72        _position: LspPosition,
73    ) {
74    }
75    /// Requests completion items at the given position.
76    fn request_completion(
77        &mut self,
78        _document: &LspDocument,
79        _position: LspPosition,
80    ) {
81    }
82    /// Requests the definition location(s) for the symbol at the given position.
83    ///
84    /// This method is called when the user triggers a "Go to Definition" action
85    /// (e.g., via Ctrl+Click or a context menu). The client implementation should
86    /// send a `textDocument/definition` request to the LSP server.
87    fn request_definition(
88        &mut self,
89        _document: &LspDocument,
90        _position: LspPosition,
91    ) {
92    }
93}
94
95/// Computes a minimal text change between two snapshots.
96///
97/// Returns `None` when the input strings are identical.
98pub fn compute_text_change(old: &str, new: &str) -> Option<LspTextChange> {
99    if old == new {
100        return None;
101    }
102
103    let old_chars: Vec<char> = old.chars().collect();
104    let new_chars: Vec<char> = new.chars().collect();
105    let old_len = old_chars.len();
106    let new_len = new_chars.len();
107
108    let mut prefix = 0;
109    while prefix < old_len
110        && prefix < new_len
111        && old_chars[prefix] == new_chars[prefix]
112    {
113        prefix += 1;
114    }
115
116    let mut suffix = 0;
117    while suffix < old_len.saturating_sub(prefix)
118        && suffix < new_len.saturating_sub(prefix)
119        && old_chars[old_len - 1 - suffix] == new_chars[new_len - 1 - suffix]
120    {
121        suffix += 1;
122    }
123
124    let removed_len = old_len.saturating_sub(prefix + suffix);
125    let inserted: String =
126        new_chars[prefix..new_len.saturating_sub(suffix)].iter().collect();
127
128    let start = position_for_char_index(old, prefix);
129    let end = position_for_char_index(old, prefix + removed_len);
130
131    Some(LspTextChange { range: LspRange { start, end }, text: inserted })
132}
133
134/// Converts a character index into a line/character position.
135fn position_for_char_index(text: &str, target_index: usize) -> LspPosition {
136    let mut line: u32 = 0;
137    let mut character: u32 = 0;
138    for (index, ch) in text.chars().enumerate() {
139        if index == target_index {
140            return LspPosition { line, character };
141        }
142        if ch == '\n' {
143            line = line.saturating_add(1);
144            character = 0;
145        } else {
146            character = character.saturating_add(1);
147        }
148    }
149
150    LspPosition { line, character }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn test_compute_text_change_none_when_equal() {
159        let change = compute_text_change("abc", "abc");
160        assert!(change.is_none());
161    }
162
163    #[test]
164    fn test_compute_text_change_insertion() {
165        let change = compute_text_change("abc", "abXc");
166        assert!(change.is_some());
167        if let Some(change) = change {
168            assert_eq!(change.text, "X");
169            assert_eq!(
170                change.range.start,
171                LspPosition { line: 0, character: 2 }
172            );
173            assert_eq!(change.range.end, LspPosition { line: 0, character: 2 });
174        }
175    }
176
177    #[test]
178    fn test_compute_text_change_deletion_across_lines() {
179        let change = compute_text_change("a\nbc", "a\nc");
180        assert!(change.is_some());
181        if let Some(change) = change {
182            assert_eq!(change.text, "");
183            assert_eq!(
184                change.range.start,
185                LspPosition { line: 1, character: 0 }
186            );
187            assert_eq!(change.range.end, LspPosition { line: 1, character: 1 });
188        }
189    }
190
191    #[test]
192    fn test_position_for_char_index_end_of_text() {
193        let pos = position_for_char_index("a\nb", 3);
194        assert_eq!(pos, LspPosition { line: 1, character: 1 });
195    }
196}