Skip to main content

iced_code_editor/canvas_editor/
virtual_text.rs

1//! Text drawn inside the editor that is not part of the buffer, such as LSP
2//! inlay hints (`let total: u32`, `add(left: 1)`).
3//!
4//! Virtual text pushes the characters after it to the right, but it is never
5//! in the buffer: the cursor steps over it, it is never copied and it never
6//! reaches [`CodeEditor::content`] or the language server.
7
8use std::collections::{BTreeMap, HashMap};
9
10use iced::Color;
11
12use crate::canvas_editor::range_style::apply_range_styles;
13use crate::canvas_editor::render::text::calculate_segment_geometry;
14use crate::canvas_editor::render::wrapping::{VisualLine, WrappingCalculator};
15use crate::canvas_editor::{CodeEditor, measure_text_width};
16
17/// One piece of virtual text, see [`CodeEditor::set_virtual_text`].
18#[derive(Debug, Clone, PartialEq)]
19pub struct VirtualText {
20    /// Logical line (0-based).
21    pub line: usize,
22    /// Character column the text is drawn before; the line length (or more)
23    /// draws it after the last character.
24    pub column: usize,
25    /// What is drawn (one line; the owner replaces line breaks).
26    pub text: String,
27    /// Text color. Nothing is drawn behind it.
28    pub color: Color,
29}
30
31/// One run of a line as it is displayed, in drawing order.
32#[derive(Debug, Clone, PartialEq)]
33pub(crate) enum LineRun<'a> {
34    /// The buffer characters of the columns `start..end`, in one color.
35    Text {
36        /// First character column of the run.
37        start: usize,
38        /// Character column after the run (exclusive).
39        end: usize,
40        /// Color of the characters.
41        color: Color,
42    },
43    /// One piece of virtual text.
44    Virtual(&'a VirtualText),
45}
46
47/// Places `virtual_text` (sorted by column) between the colored `pieces` of
48/// the columns `cols` of a line.
49///
50/// Virtual text goes before the character at its column. The one at the end
51/// of the line goes after the last piece, on the segment reaching that end.
52fn merge_virtual_text<'a>(
53    pieces: Vec<(usize, usize, Color)>,
54    virtual_text: &'a [VirtualText],
55    line_len: usize,
56    cols: (usize, usize),
57) -> Vec<LineRun<'a>> {
58    let column = |item: &VirtualText| item.column.min(line_len);
59    let mut next = virtual_text.partition_point(|item| column(item) < cols.0);
60    let mut runs = Vec::with_capacity(pieces.len());
61    let push_text = |runs: &mut Vec<LineRun<'a>>, start, end, color| {
62        if start < end {
63            runs.push(LineRun::Text { start, end, color });
64        }
65    };
66    for (start, end, color) in pieces {
67        let mut pos = start;
68        while let Some(item) = virtual_text.get(next)
69            && column(item) < end
70        {
71            let at = column(item).max(pos);
72            push_text(&mut runs, pos, at, color);
73            runs.push(LineRun::Virtual(item));
74            pos = at;
75            next += 1;
76        }
77        push_text(&mut runs, pos, end, color);
78    }
79    if cols.1 >= line_len {
80        runs.extend(virtual_text[next..].iter().map(LineRun::Virtual));
81    }
82    runs
83}
84
85/// The virtual text of every layer, and the same items by line for drawing.
86#[derive(Debug, Default)]
87pub(crate) struct VirtualTextLayers {
88    layers: BTreeMap<String, Vec<VirtualText>>,
89    /// Every item, by line, sorted by column (a stable sort: on the same
90    /// column, layers in name order and items in the order they were given).
91    by_line: HashMap<usize, Vec<VirtualText>>,
92    /// Bumped whenever the displayed text changes, for the layout caches.
93    pub(crate) revision: u64,
94}
95
96impl VirtualTextLayers {
97    fn rebuild(&mut self) {
98        self.by_line.clear();
99        for item in self.layers.values().flatten() {
100            self.by_line.entry(item.line).or_default().push(item.clone());
101        }
102        for items in self.by_line.values_mut() {
103            items.sort_by_key(|item| item.column);
104        }
105    }
106
107    pub(crate) fn on_line(&self, line: usize) -> &[VirtualText] {
108        self.by_line.get(&line).map_or(&[], Vec::as_slice)
109    }
110}
111
112impl CodeEditor {
113    /// Replaces the virtual text of one layer (for example `"inlay-hints"`),
114    /// leaving the other layers alone. An empty list removes the layer.
115    ///
116    /// Positions are not moved when the buffer changes: the owner of a layer
117    /// replaces it after an edit. Until then, a column past the end of its
118    /// line draws at the end, and a line past the end of the buffer is not
119    /// drawn.
120    pub fn set_virtual_text(
121        &mut self,
122        layer: impl Into<String>,
123        items: Vec<VirtualText>,
124    ) {
125        let layer = layer.into();
126        let current = self.virtual_text.layers.get(&layer);
127        if current.map_or(items.is_empty(), |current| *current == items) {
128            return;
129        }
130        if items.is_empty() {
131            self.virtual_text.layers.remove(&layer);
132        } else {
133            self.virtual_text.layers.insert(layer, items);
134        }
135        self.virtual_text.rebuild();
136        self.invalidate_virtual_text_layout();
137    }
138
139    /// Drops everything computed from the displayed virtual text.
140    pub(crate) fn invalidate_virtual_text_layout(&mut self) {
141        self.virtual_text.revision = self.virtual_text.revision.wrapping_add(1);
142        *self.max_content_width_cache.borrow_mut() = None;
143        self.content_cache.clear();
144        self.overlay_cache.clear();
145    }
146
147    /// The virtual text displayed on `line`: none while it is hidden
148    /// ([`CodeEditor::set_virtual_text_enabled`]).
149    fn displayed_virtual_text(&self, line: usize) -> &[VirtualText] {
150        if self.virtual_text_enabled {
151            self.virtual_text.on_line(line)
152        } else {
153            &[]
154        }
155    }
156
157    /// Removes the virtual text of one layer.
158    pub fn clear_virtual_text(&mut self, layer: &str) {
159        self.set_virtual_text(layer, Vec::new());
160    }
161
162    /// The virtual text of one layer, as last given.
163    pub fn virtual_text(&self, layer: &str) -> &[VirtualText] {
164        self.virtual_text.layers.get(layer).map_or(&[], Vec::as_slice)
165    }
166
167    /// The runs displayed for the columns `cols` of `line`: the syntax `spans`
168    /// of the whole line (the plain text color without them), recolored by
169    /// the range styles, with the virtual text between them.
170    ///
171    /// The canvas and the sticky-scroll headers both draw these runs, so a
172    /// pinned header looks like the line it mirrors.
173    pub(crate) fn line_runs(
174        &self,
175        line: usize,
176        spans: Option<&[(Color, String)]>,
177        cols: (usize, usize),
178    ) -> Vec<LineRun<'_>> {
179        let mut pieces = Vec::new();
180        if let Some(spans) = spans {
181            let mut char_pos = 0;
182            for (color, text) in spans {
183                let text_end = char_pos + text.chars().count();
184                let start = char_pos.max(cols.0);
185                let end = text_end.min(cols.1);
186                if start < end {
187                    pieces.push((start, end, *color));
188                }
189                char_pos = text_end;
190            }
191        } else if cols.0 < cols.1 {
192            pieces.push((cols.0, cols.1, self.style.text_color));
193        }
194        merge_virtual_text(
195            apply_range_styles(pieces, self.range_styles.on_line(line)),
196            self.displayed_virtual_text(line),
197            self.buffer.line_len(line),
198            cols,
199        )
200    }
201
202    /// `(column, width)` of the virtual text on `line`, sorted by column, with
203    /// columns clamped to the line length.
204    pub(crate) fn virtual_text_widths(&self, line: usize) -> Vec<(usize, f32)> {
205        let items = self.displayed_virtual_text(line);
206        if items.is_empty() {
207            return Vec::new();
208        }
209        let len = self.buffer.line_len(line);
210        items
211            .iter()
212            .map(|item| {
213                (
214                    item.column.min(len),
215                    measure_text_width(
216                        &item.text,
217                        self.full_char_width,
218                        self.char_width,
219                    ),
220                )
221            })
222            .collect()
223    }
224
225    /// The wrapping calculator for the current settings and virtual text.
226    pub(crate) fn wrapping_calculator(&self) -> WrappingCalculator {
227        let virtual_text = self
228            .virtual_text
229            .by_line
230            .keys()
231            .map(|&line| (line, self.virtual_text_widths(line)))
232            .collect();
233        WrappingCalculator::new(
234            self.wrap_enabled,
235            self.wrap_column,
236            self.full_char_width,
237            self.char_width,
238        )
239        .with_virtual_text(virtual_text)
240    }
241
242    /// X of the cursor at `col` of `visual_line`, in content space (with the
243    /// gutter, without the horizontal scroll). The cursor stays before the
244    /// virtual text at its own column.
245    pub(crate) fn caret_content_x(
246        &self,
247        visual_line: &VisualLine,
248        col: usize,
249    ) -> f32 {
250        calculate_segment_geometry(
251            self.buffer.line(visual_line.logical_line),
252            visual_line.start_col,
253            col,
254            col,
255            self.gutter_width() + 5.0,
256            self.full_char_width,
257            self.char_width,
258            &self.virtual_text_widths(visual_line.logical_line),
259        )
260        .0
261    }
262
263    /// Width of the text of `line` plus its virtual text.
264    pub(crate) fn line_display_width(&self, line: usize) -> f32 {
265        measure_text_width(
266            self.buffer.line(line),
267            self.full_char_width,
268            self.char_width,
269        ) + self
270            .displayed_virtual_text(line)
271            .iter()
272            .map(|item| {
273                measure_text_width(
274                    &item.text,
275                    self.full_char_width,
276                    self.char_width,
277                )
278            })
279            .sum::<f32>()
280    }
281}
282
283/// Total width of the virtual text in `widths` whose column is in
284/// `from..to` (`to` inclusive when `inclusive`).
285pub(crate) fn width_between(
286    widths: &[(usize, f32)],
287    from: usize,
288    to: usize,
289    inclusive: bool,
290) -> f32 {
291    widths
292        .iter()
293        .filter(|(col, _)| {
294            *col >= from && (*col < to || (inclusive && *col == to))
295        })
296        .map(|(_, w)| w)
297        .sum()
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303    use crate::canvas_editor::render::text::calculate_segment_geometry;
304    use iced::Point;
305
306    const GRAY: Color = Color::from_rgb(0.5, 0.5, 0.5);
307
308    fn hint(line: usize, column: usize, text: &str) -> VirtualText {
309        VirtualText { line, column, text: text.to_string(), color: GRAY }
310    }
311
312    /// `let total = 1;` with `: u32` after `total` (column 9).
313    fn editor_with_type_hint() -> CodeEditor {
314        let mut editor = CodeEditor::new("let total = 1;\nx", "rs");
315        editor.set_virtual_text("hints", vec![hint(0, 9, ": u32")]);
316        editor
317    }
318
319    #[test]
320    fn layers_are_replaced_and_cleared_independently() {
321        let mut editor = CodeEditor::new("a\nb", "rs");
322        editor.set_virtual_text("types", vec![hint(0, 1, ": T")]);
323        editor.set_virtual_text("debug", vec![hint(0, 1, " = 3")]);
324        assert_eq!(editor.virtual_text.on_line(0).len(), 2);
325        // Same column: layers in name order.
326        assert_eq!(editor.virtual_text.on_line(0)[0].text, " = 3");
327
328        let revision = editor.virtual_text.revision;
329        editor.set_virtual_text("types", vec![hint(0, 1, ": T")]);
330        assert_eq!(editor.virtual_text.revision, revision, "no change");
331
332        editor.clear_virtual_text("debug");
333        assert_eq!(editor.virtual_text("types"), &[hint(0, 1, ": T")]);
334        assert!(editor.virtual_text("debug").is_empty());
335        editor.set_virtual_text("types", Vec::new());
336        assert!(editor.virtual_text.on_line(0).is_empty());
337        assert_eq!(editor.content(), "a\nb", "never part of the buffer");
338    }
339
340    #[test]
341    fn segments_and_the_cursor_around_virtual_text() {
342        // `(x, width)`, the width only when given.
343        let close = |(x, w): (f32, f32), (ex, ew): (f32, Option<f32>)| {
344            (x - ex).abs() < 0.01 && ew.is_none_or(|ew| (w - ew).abs() < 0.01)
345        };
346        let hints = [(2, 30.0)];
347        let geometry = |start, end| {
348            calculate_segment_geometry(
349                "abcd", 0, start, end, 0.0, 20.0, 10.0, &hints,
350            )
351        };
352        // The cursor at the hint's column stays before it, one column later
353        // it is after both.
354        assert!(close(geometry(2, 2), (20.0, None)));
355        assert!(close(geometry(3, 3), (60.0, None)));
356        // Text starting at the hint's column starts after it.
357        assert!(close(geometry(2, 3), (50.0, Some(10.0))));
358        // Text ending at the hint's column does not cover it; text around it
359        // does.
360        assert!(close(geometry(0, 2), (0.0, Some(20.0))));
361        assert!(close(geometry(1, 3), (10.0, Some(50.0))));
362        // Without virtual text, nothing changes.
363        assert!(close(
364            calculate_segment_geometry("abcd", 0, 1, 3, 0.0, 20.0, 10.0, &[]),
365            (10.0, Some(20.0))
366        ));
367    }
368
369    #[test]
370    fn the_cursor_x_and_clicks_skip_the_hint() {
371        let editor = editor_with_type_hint();
372        let visual_lines = editor.visual_lines_cached(800.0);
373        let row = &visual_lines[0];
374        let cw = editor.char_width;
375        let hint_w = measure_text_width(": u32", editor.full_char_width, cw);
376        let base = editor.gutter_width() + 5.0;
377        assert!(
378            (editor.caret_content_x(row, 9) - (base + 9.0 * cw)).abs() < 0.01
379        );
380        assert!(
381            (editor.caret_content_x(row, 10) - (base + 10.0 * cw + hint_w))
382                .abs()
383                < 0.01
384        );
385
386        let click = |x: f32| {
387            editor.calculate_cursor_from_point(Point::new(base + x, 5.0))
388        };
389        // On either half of the hint: the column before it.
390        assert_eq!(click(9.0 * cw + 1.0), Some((0, 9)));
391        assert_eq!(click(9.0 * cw + hint_w - 1.0), Some((0, 9)));
392        // On the right half of the space after the hint: one column later.
393        assert_eq!(click(9.0 * cw + hint_w + cw * 0.75), Some((0, 10)));
394        // Past the end of the line.
395        assert_eq!(click(40.0 * cw), Some((0, 14)));
396    }
397
398    #[test]
399    fn hints_widen_the_line_and_its_wrapping() {
400        let mut editor = CodeEditor::new("abcdefgh", "rs");
401        let plain = editor.max_content_width();
402        editor.set_virtual_text("hints", vec![hint(0, 8, " // end")]);
403        let hint_w = measure_text_width(
404            " // end",
405            editor.full_char_width,
406            editor.char_width,
407        );
408        assert!((editor.max_content_width() - plain - hint_w).abs() < 0.01);
409
410        // Wrap at 6 columns: "abc" + a 4-column hint before `d` makes `d`
411        // start the second row, with the hint in front of it.
412        editor.set_virtual_text("hints", vec![hint(0, 3, "1234")]);
413        editor.set_wrap_enabled(true);
414        editor.set_wrap_column(Some(6));
415        let rows = editor.visual_lines_cached(800.0);
416        let cols: Vec<_> =
417            rows.iter().map(|r| (r.start_col, r.end_col)).collect();
418        assert_eq!(cols, vec![(0, 3), (3, 5), (5, 8)]);
419    }
420
421    #[test]
422    fn a_hint_at_the_end_of_the_line_wraps_with_the_last_character() {
423        let mut editor = CodeEditor::new("abcde", "rs");
424        editor.set_wrap_enabled(true);
425        editor.set_wrap_column(Some(6));
426
427        // 5 columns of text + 4 of hint do not fit in 6: `e` moves to the
428        // second row and takes the hint with it.
429        editor.set_virtual_text("hints", vec![hint(0, 5, "1234")]);
430        let rows = editor.visual_lines_cached(800.0);
431        let cols: Vec<_> =
432            rows.iter().map(|r| (r.start_col, r.end_col)).collect();
433        assert_eq!(cols, vec![(0, 4), (4, 5)]);
434        // The cursor at the end of the line stays on the hint's row.
435        assert_eq!(WrappingCalculator::logical_to_visual(&rows, 0, 5), Some(1));
436
437        // A hint that fits changes nothing.
438        editor.set_virtual_text("hints", vec![hint(0, 5, "1")]);
439        let rows = editor.visual_lines_cached(800.0);
440        assert_eq!(rows.len(), 1);
441    }
442
443    #[test]
444    fn runs_place_virtual_text_between_the_colored_pieces() {
445        const RED: Color = Color::from_rgb(1.0, 0.0, 0.0);
446        let text = |start, end| LineRun::Text { start, end, color: RED };
447        let middle = hint(0, 2, "m");
448        let end = hint(0, 4, "e");
449        let items = [middle.clone(), end.clone()];
450        let pieces = vec![(0, 4, RED)];
451
452        assert_eq!(
453            merge_virtual_text(pieces, &items, 4, (0, 4)),
454            vec![
455                text(0, 2),
456                LineRun::Virtual(&middle),
457                text(2, 4),
458                LineRun::Virtual(&end),
459            ]
460        );
461        // A segment that stops before the end of the line leaves the last
462        // hint to the segment reaching it.
463        assert_eq!(
464            merge_virtual_text(vec![(0, 2, RED)], &items, 4, (0, 2)),
465            vec![text(0, 2)]
466        );
467        assert_eq!(
468            merge_virtual_text(vec![(2, 4, RED)], &items, 4, (2, 4)),
469            vec![LineRun::Virtual(&middle), text(2, 4), LineRun::Virtual(&end),]
470        );
471        // An empty line only has its hints.
472        assert_eq!(
473            merge_virtual_text(Vec::new(), &items[1..], 0, (0, 0)),
474            vec![LineRun::Virtual(&end)]
475        );
476    }
477
478    #[test]
479    fn line_runs_show_range_styles_and_virtual_text() {
480        const RED: Color = Color::from_rgb(1.0, 0.0, 0.0);
481        const BLUE: Color = Color::from_rgb(0.0, 0.0, 1.0);
482        let mut editor = CodeEditor::new("abcd", "rs");
483        let end = hint(0, 4, "!");
484        editor.set_virtual_text("hints", vec![end.clone()]);
485        editor.set_range_styles(
486            "semantic",
487            vec![crate::RangeStyle { line: 0, start: 1, end: 3, color: BLUE }],
488        );
489
490        let spans = vec![(RED, "abcd".to_string())];
491        assert_eq!(
492            editor.line_runs(0, Some(&spans), (0, 4)),
493            vec![
494                LineRun::Text { start: 0, end: 1, color: RED },
495                LineRun::Text { start: 1, end: 3, color: BLUE },
496                LineRun::Text { start: 3, end: 4, color: RED },
497                LineRun::Virtual(&end),
498            ]
499        );
500
501        // Without syntax spans, the plain text color is the base.
502        let plain = editor.style.text_color;
503        assert_eq!(
504            editor.line_runs(0, None, (0, 1)),
505            vec![LineRun::Text { start: 0, end: 1, color: plain }]
506        );
507    }
508
509    #[test]
510    fn hidden_virtual_text_takes_no_space_and_is_kept() {
511        let mut editor = CodeEditor::new("abcde", "rs");
512        editor.set_wrap_enabled(true);
513        editor.set_wrap_column(Some(6));
514        let plain_width = editor.max_content_width();
515        let shown = hint(0, 5, "1234");
516        editor.set_virtual_text("hints", vec![shown.clone()]);
517        assert_eq!(editor.visual_lines_cached(800.0).len(), 2);
518
519        editor.set_virtual_text_enabled(false);
520        assert_eq!(editor.visual_lines_cached(800.0).len(), 1, "no wrap");
521        assert!(editor.virtual_text_widths(0).is_empty());
522        assert!((editor.max_content_width() - plain_width).abs() < 0.01);
523        assert_eq!(
524            editor.line_runs(0, None, (0, 5)).len(),
525            1,
526            "only the buffer text is drawn"
527        );
528        assert_eq!(editor.virtual_text("hints"), std::slice::from_ref(&shown));
529
530        // A layer replaced while hidden is the one shown afterwards.
531        let replaced = hint(0, 5, "12345");
532        editor.set_virtual_text("hints", vec![replaced.clone()]);
533        editor.set_virtual_text_enabled(true);
534        assert_eq!(editor.visual_lines_cached(800.0).len(), 2);
535        assert!(
536            editor
537                .line_runs(0, None, (4, 5))
538                .contains(&LineRun::Virtual(&replaced))
539        );
540    }
541
542    #[test]
543    fn columns_past_the_line_are_drawn_at_its_end() {
544        let mut editor = CodeEditor::new("ab", "rs");
545        editor.set_virtual_text("hints", vec![hint(0, 99, "!")]);
546        assert_eq!(editor.virtual_text_widths(0)[0].0, 2);
547        assert!(editor.virtual_text_widths(5).is_empty());
548    }
549}