Skip to main content

iced_code_editor/canvas_editor/
diagnostics.rs

1//! Diagnostic ranges and their placement on visual lines.
2
3use crate::canvas_editor::CodeEditor;
4use crate::canvas_editor::lsp::{Diagnostic, LspPosition};
5use crate::canvas_editor::render::wrapping::VisualLine;
6
7impl CodeEditor {
8    /// Replaces the diagnostic ranges underlined by the editor.
9    ///
10    /// Columns count characters, not UTF-16 code units, and the end is
11    /// exclusive. The ranges are not moved when the text is edited: pass a new
12    /// list whenever the diagnostics change. An empty list clears them.
13    ///
14    /// # Example
15    ///
16    /// ```
17    /// use iced_code_editor::{
18    ///     CodeEditor, Diagnostic, DiagnosticSeverity, LspPosition, LspRange,
19    /// };
20    ///
21    /// let mut editor = CodeEditor::new("let answer = 42;", "rs");
22    /// let diagnostic = Diagnostic::new(
23    ///     LspRange {
24    ///         start: LspPosition { line: 0, character: 4 },
25    ///         end: LspPosition { line: 0, character: 10 },
26    ///     },
27    ///     DiagnosticSeverity::Warning,
28    ///     "unused variable",
29    /// );
30    /// editor.set_diagnostics(vec![diagnostic.clone()]);
31    /// assert_eq!(editor.diagnostics(), &[diagnostic]);
32    /// ```
33    pub fn set_diagnostics(&mut self, diagnostics: Vec<Diagnostic>) {
34        if self.diagnostics == diagnostics {
35            return;
36        }
37        self.diagnostics = diagnostics;
38        self.overlay_cache.clear();
39    }
40
41    /// The diagnostic ranges currently underlined by the editor.
42    ///
43    /// # Example
44    ///
45    /// ```
46    /// use iced_code_editor::CodeEditor;
47    ///
48    /// let editor = CodeEditor::new("fn main() {}", "rs");
49    /// assert!(editor.diagnostics().is_empty());
50    /// ```
51    pub fn diagnostics(&self) -> &[Diagnostic] {
52        &self.diagnostics
53    }
54
55    /// The diagnostics covering `position`, in the order they were set.
56    ///
57    /// Always empty while diagnostics are disabled
58    /// ([`CodeEditor::set_diagnostics_enabled`]).
59    ///
60    /// `position` is in logical lines and character columns, as returned by
61    /// [`CodeEditor::lsp_position_at_point`]. Hosts use it to show the
62    /// messages of the diagnostics under the pointer.
63    ///
64    /// # Example
65    ///
66    /// ```
67    /// use iced_code_editor::{
68    ///     CodeEditor, Diagnostic, DiagnosticSeverity, LspPosition, LspRange,
69    /// };
70    ///
71    /// let mut editor = CodeEditor::new("let answer = 42;", "rs");
72    /// editor.set_diagnostics(vec![Diagnostic::new(
73    ///     LspRange {
74    ///         start: LspPosition { line: 0, character: 4 },
75    ///         end: LspPosition { line: 0, character: 10 },
76    ///     },
77    ///     DiagnosticSeverity::Warning,
78    ///     "unused variable",
79    /// )]);
80    ///
81    /// let hovered = editor.diagnostics_at(LspPosition { line: 0, character: 6 });
82    /// assert_eq!(hovered.len(), 1);
83    /// assert_eq!(hovered[0].message, "unused variable");
84    /// assert!(editor.diagnostics_at(LspPosition { line: 0, character: 0 }).is_empty());
85    /// ```
86    pub fn diagnostics_at(&self, position: LspPosition) -> Vec<&Diagnostic> {
87        if !self.diagnostics_enabled {
88            return Vec::new();
89        }
90        self.diagnostics
91            .iter()
92            .filter(|diagnostic| diagnostic.contains(position))
93            .collect()
94    }
95}
96
97/// Intersects a diagnostic with one visual line, in logical character columns.
98pub(super) fn diagnostic_segment(
99    visual_line: &VisualLine,
100    diagnostic: &Diagnostic,
101) -> Option<(usize, usize)> {
102    let start = diagnostic.range.start;
103    let end = diagnostic.range.end;
104    if (start.line, start.character) > (end.line, end.character) {
105        return None;
106    }
107
108    if start == end {
109        let col = start.character as usize;
110        return (visual_line.logical_line == start.line as usize
111            && visual_line.start_col <= col
112            && (col < visual_line.end_col
113                || (visual_line.start_col == visual_line.end_col
114                    && col == visual_line.start_col)))
115            .then_some((col, col + 1));
116    }
117
118    let line = visual_line.logical_line as u32;
119    let start_col = if line == start.line {
120        start.character as usize
121    } else {
122        visual_line.start_col
123    };
124    let end_col = if line == end.line {
125        end.character as usize
126    } else {
127        visual_line.end_col
128    };
129    let start_col = start_col.max(visual_line.start_col);
130    let end_col = end_col.min(visual_line.end_col);
131
132    (line >= start.line && line <= end.line && start_col < end_col)
133        .then_some((start_col, end_col))
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139    use crate::canvas_editor::lsp::{
140        DiagnosticSeverity, LspPosition, LspRange,
141    };
142
143    fn diagnostic(start: (u32, u32), end: (u32, u32)) -> Diagnostic {
144        Diagnostic::new(
145            LspRange {
146                start: LspPosition { line: start.0, character: start.1 },
147                end: LspPosition { line: end.0, character: end.1 },
148            },
149            DiagnosticSeverity::Error,
150            "error",
151        )
152    }
153
154    fn at(line: u32, character: u32) -> LspPosition {
155        LspPosition { line, character }
156    }
157
158    #[test]
159    fn disabling_diagnostics_hides_them_but_keeps_the_list() {
160        let mut editor = CodeEditor::new("let answer = 42;\n", "rs");
161        let error = diagnostic((0, 4), (0, 10));
162        editor.set_diagnostics_enabled(false);
163        // Set while disabled: stored, not reported.
164        editor.set_diagnostics(vec![error.clone()]);
165        assert!(editor.diagnostics_at(at(0, 5)).is_empty());
166        assert_eq!(editor.diagnostics(), std::slice::from_ref(&error));
167
168        editor.set_diagnostics_enabled(true);
169        assert_eq!(editor.diagnostics_at(at(0, 5)), vec![&error]);
170    }
171
172    #[test]
173    fn diagnostic_contains_spans_lines_with_exclusive_end() {
174        let multi = diagnostic((0, 8), (2, 3));
175        assert!(!multi.contains(at(0, 7)));
176        assert!(multi.contains(at(0, 8)));
177        assert!(multi.contains(at(1, 0)));
178        assert!(multi.contains(at(2, 2)));
179        assert!(!multi.contains(at(2, 3)));
180    }
181
182    #[test]
183    fn diagnostic_contains_empty_and_reversed_ranges() {
184        let empty = diagnostic((1, 4), (1, 4));
185        assert!(empty.contains(at(1, 4)));
186        assert!(!empty.contains(at(1, 5)));
187
188        let reversed = diagnostic((1, 6), (1, 2));
189        assert!(!reversed.contains(at(1, 4)));
190    }
191
192    #[test]
193    fn diagnostics_at_returns_every_covering_diagnostic_in_order() {
194        let mut editor = CodeEditor::new("let answer = 42;\n", "rs");
195        let outer = diagnostic((0, 0), (0, 16));
196        let inner = diagnostic((0, 4), (0, 10));
197        let elsewhere = diagnostic((0, 13), (0, 15));
198        editor.set_diagnostics(vec![
199            outer.clone(),
200            inner.clone(),
201            elsewhere.clone(),
202        ]);
203
204        assert_eq!(editor.diagnostics_at(at(0, 5)), vec![&outer, &inner]);
205        assert_eq!(editor.diagnostics_at(at(0, 14)), vec![&outer, &elsewhere]);
206        assert!(editor.diagnostics_at(at(1, 0)).is_empty());
207    }
208
209    #[test]
210    fn diagnostics_are_replaced_and_cleared() {
211        let mut editor = CodeEditor::new("let answer = 42;\n", "rs");
212        let diagnostic = diagnostic((0, 4), (0, 10));
213        editor.set_diagnostics(vec![diagnostic.clone()]);
214        assert_eq!(editor.diagnostics(), &[diagnostic]);
215        editor.set_diagnostics(Vec::new());
216        assert!(editor.diagnostics().is_empty());
217    }
218
219    #[test]
220    fn diagnostic_segments_follow_wrapping_and_multiple_lines() {
221        let wrapped = VisualLine::new(0, 1, 10, 20);
222        assert_eq!(
223            diagnostic_segment(&wrapped, &diagnostic((0, 8), (0, 15))),
224            Some((10, 15))
225        );
226        assert_eq!(
227            diagnostic_segment(&wrapped, &diagnostic((0, 20), (0, 25))),
228            None
229        );
230
231        let middle = VisualLine::new(1, 0, 0, 12);
232        assert_eq!(
233            diagnostic_segment(&middle, &diagnostic((0, 8), (2, 3))),
234            Some((0, 12))
235        );
236
237        let empty = VisualLine::new(0, 0, 0, 10);
238        assert_eq!(
239            diagnostic_segment(&empty, &diagnostic((0, 4), (0, 4))),
240            Some((4, 5))
241        );
242        let empty_line = VisualLine::new(2, 0, 0, 0);
243        assert_eq!(
244            diagnostic_segment(&empty_line, &diagnostic((2, 0), (2, 0))),
245            Some((0, 1))
246        );
247    }
248}