Skip to main content

iced_code_editor/canvas_editor/
range_style.rs

1//! Colors given to ranges of the text, such as LSP semantic tokens
2//! (`parameter`, `mutable variable`) drawn over the syntax highlighting.
3//!
4//! A range style only changes the color of characters that are already
5//! there: it never changes a width, so the cursor, selection, hit testing and
6//! wrapping are untouched.
7
8use std::collections::{BTreeMap, HashMap};
9
10use iced::Color;
11
12use crate::canvas_editor::CodeEditor;
13
14/// The color of one range of a line, see [`CodeEditor::set_range_styles`].
15#[derive(Debug, Clone, PartialEq)]
16pub struct RangeStyle {
17    /// Logical line (0-based).
18    pub line: usize,
19    /// First character column of the range.
20    pub start: usize,
21    /// Character column after the range (exclusive).
22    pub end: usize,
23    /// Text color, instead of the syntax highlighting's.
24    pub color: Color,
25}
26
27/// The range styles of every layer, and the same styles by line for drawing.
28#[derive(Debug, Default)]
29pub(crate) struct RangeStyleLayers {
30    layers: BTreeMap<String, Vec<RangeStyle>>,
31    /// Every style, by line, in the order they are painted: layers in name
32    /// order, and styles in the order they were given. Later ones win.
33    by_line: HashMap<usize, Vec<RangeStyle>>,
34}
35
36impl RangeStyleLayers {
37    fn rebuild(&mut self) {
38        self.by_line.clear();
39        for style in self.layers.values().flatten() {
40            if style.start < style.end {
41                self.by_line.entry(style.line).or_default().push(style.clone());
42            }
43        }
44    }
45
46    pub(crate) fn on_line(&self, line: usize) -> &[RangeStyle] {
47        self.by_line.get(&line).map_or(&[], Vec::as_slice)
48    }
49}
50
51/// Recolors the `(start, end, color)` pieces of a line with `styles`, in
52/// order, splitting a piece where a style starts or ends inside it. The
53/// pieces keep their columns; only colors change.
54pub(crate) fn apply_range_styles(
55    mut pieces: Vec<(usize, usize, Color)>,
56    styles: &[RangeStyle],
57) -> Vec<(usize, usize, Color)> {
58    for style in styles {
59        let mut next = Vec::with_capacity(pieces.len() + 2);
60        for (start, end, color) in pieces {
61            let from = style.start.max(start);
62            let to = style.end.min(end);
63            if from >= to {
64                next.push((start, end, color));
65                continue;
66            }
67            if start < from {
68                next.push((start, from, color));
69            }
70            next.push((from, to, style.color));
71            if to < end {
72                next.push((to, end, color));
73            }
74        }
75        pieces = next;
76    }
77    pieces
78}
79
80impl CodeEditor {
81    /// Replaces the range styles of one layer (for example
82    /// `"semantic-tokens"`), leaving the other layers alone. An empty list
83    /// removes the layer.
84    ///
85    /// Where styles overlap, layers later in name order win, and within a
86    /// layer the later style wins. Positions are not moved when the buffer
87    /// changes: the owner of a layer replaces it after an edit. Until then,
88    /// a range past the end of its line is cut there.
89    pub fn set_range_styles(
90        &mut self,
91        layer: impl Into<String>,
92        styles: Vec<RangeStyle>,
93    ) {
94        let layer = layer.into();
95        let current = self.range_styles.layers.get(&layer);
96        if current.map_or(styles.is_empty(), |current| *current == styles) {
97            return;
98        }
99        if styles.is_empty() {
100            self.range_styles.layers.remove(&layer);
101        } else {
102            self.range_styles.layers.insert(layer, styles);
103        }
104        self.range_styles.rebuild();
105        self.content_cache.clear();
106    }
107
108    /// Removes the range styles of one layer.
109    pub fn clear_range_styles(&mut self, layer: &str) {
110        self.set_range_styles(layer, Vec::new());
111    }
112
113    /// The range styles of one layer, as last given.
114    pub fn range_styles(&self, layer: &str) -> &[RangeStyle] {
115        self.range_styles.layers.get(layer).map_or(&[], Vec::as_slice)
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    const RED: Color = Color::from_rgb(1.0, 0.0, 0.0);
124    const GREEN: Color = Color::from_rgb(0.0, 1.0, 0.0);
125    const BLUE: Color = Color::from_rgb(0.0, 0.0, 1.0);
126
127    fn style(start: usize, end: usize, color: Color) -> RangeStyle {
128        RangeStyle { line: 0, start, end, color }
129    }
130
131    #[test]
132    fn test_style_inside_a_piece_splits_it() {
133        let pieces = vec![(0, 10, RED)];
134        assert_eq!(
135            apply_range_styles(pieces, &[style(3, 6, GREEN)]),
136            vec![(0, 3, RED), (3, 6, GREEN), (6, 10, RED)]
137        );
138    }
139
140    #[test]
141    fn test_style_across_pieces_and_past_the_end() {
142        let pieces = vec![(0, 4, RED), (4, 8, BLUE)];
143        assert_eq!(
144            apply_range_styles(pieces, &[style(2, 20, GREEN)]),
145            vec![(0, 2, RED), (2, 4, GREEN), (4, 8, GREEN)]
146        );
147    }
148
149    #[test]
150    fn test_later_style_wins() {
151        let pieces = vec![(0, 6, RED)];
152        assert_eq!(
153            apply_range_styles(
154                pieces,
155                &[style(0, 6, GREEN), style(2, 4, BLUE)]
156            ),
157            vec![(0, 2, GREEN), (2, 4, BLUE), (4, 6, GREEN)]
158        );
159    }
160
161    #[test]
162    fn test_layers_by_line_in_name_order() {
163        let mut editor = CodeEditor::new("let x = 1;\nlet y = 2;", "rs");
164        editor.set_range_styles("b", vec![style(4, 5, BLUE)]);
165        editor.set_range_styles(
166            "a",
167            vec![
168                style(4, 5, GREEN),
169                RangeStyle { line: 1, ..style(4, 5, RED) },
170            ],
171        );
172        let colors: Vec<_> =
173            editor.range_styles.on_line(0).iter().map(|s| s.color).collect();
174        assert_eq!(colors, vec![GREEN, BLUE], "layer \"b\" is painted last");
175        assert_eq!(editor.range_styles.on_line(1).len(), 1);
176        assert_eq!(editor.range_styles("a").len(), 2);
177
178        editor.clear_range_styles("a");
179        assert_eq!(editor.range_styles.on_line(0).len(), 1);
180        assert!(editor.range_styles.on_line(1).is_empty());
181        assert!(editor.range_styles("a").is_empty());
182    }
183
184    #[test]
185    fn test_scope_color_follows_the_theme_and_token_colors() {
186        let mut editor = CodeEditor::new("fn main() {}", "rs");
187        let function = editor.scope_color("entity.name.function");
188        assert!(function.is_some());
189        assert_ne!(function, editor.scope_color("keyword"));
190        assert_eq!(editor.scope_color("not a scope!"), None);
191
192        let mut style = editor.style;
193        style.token_colors.string = Some(RED);
194        editor.set_theme(style);
195        assert_eq!(editor.scope_color("string.quoted.double"), Some(RED));
196    }
197
198    #[test]
199    fn test_empty_ranges_are_ignored() {
200        let mut editor = CodeEditor::new("abc", "txt");
201        editor.set_range_styles("a", vec![style(2, 2, RED), style(3, 1, RED)]);
202        assert!(editor.range_styles.on_line(0).is_empty());
203    }
204}