Skip to main content

rustaco_core/
decorations.rs

1//! Decorations: ranges of text with a kind (search match, diagnostic, diff hunk, highlight)
2//! that move with edits. They live in the model, so every editor showing it sees them.
3//!
4//! Stored sorted by start. Ranges longer than [`LONG`] chars are kept apart and scanned
5//! linearly, so looking up the decorations of the visible lines is a binary search plus the
6//! few long ones (folding regions, multi-line diagnostics).
7
8use std::ops::Range;
9
10use crate::change::{Assoc, ChangeSet};
11
12const LONG: usize = 4096;
13
14/// How a decoration's edges behave when text is typed exactly at them (Monaco's names).
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub enum Stickiness {
17    /// Text typed at either edge becomes part of the decoration.
18    AlwaysGrows,
19    /// Text typed at an edge stays outside.
20    #[default]
21    NeverGrows,
22    /// Text typed at the start is inside, at the end outside.
23    GrowsBefore,
24    /// Text typed at the end is inside, at the start outside.
25    GrowsAfter,
26}
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
29pub struct DecorationId(pub u64);
30
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct Decoration {
33    pub id: DecorationId,
34    pub range: Range<usize>,
35    /// What the decoration means; frontends map kinds to styles.
36    pub kind: u32,
37    pub stickiness: Stickiness,
38    /// Decorations added together share an owner and can be replaced together.
39    pub owner: u32,
40}
41
42#[derive(Clone, Debug, Default)]
43pub struct Decorations {
44    short: Vec<Decoration>,
45    long: Vec<Decoration>,
46    next_id: u64,
47    /// Bumped by every change, so views can cache what they derive from decorations.
48    generation: u64,
49}
50
51impl Decorations {
52    pub fn len(&self) -> usize {
53        self.short.len() + self.long.len()
54    }
55
56    /// Changes whenever any decoration is added, removed or moved.
57    pub fn generation(&self) -> u64 {
58        self.generation
59    }
60
61    pub fn is_empty(&self) -> bool {
62        self.len() == 0
63    }
64
65    /// Replaces all decorations of `owner` with `ranges`, returning their ids.
66    pub fn set(
67        &mut self,
68        owner: u32,
69        kind: u32,
70        stickiness: Stickiness,
71        ranges: impl IntoIterator<Item = Range<usize>>,
72    ) -> Vec<DecorationId> {
73        self.set_each(owner, stickiness, ranges.into_iter().map(|r| (r, kind)))
74    }
75
76    /// Replaces all decorations of `owner` with `items`, each a range with its own kind.
77    pub fn set_each(
78        &mut self,
79        owner: u32,
80        stickiness: Stickiness,
81        items: impl IntoIterator<Item = (Range<usize>, u32)>,
82    ) -> Vec<DecorationId> {
83        self.clear(owner);
84        self.generation += 1;
85        let mut ids = Vec::new();
86        for (range, kind) in items {
87            self.next_id += 1;
88            let d = Decoration { id: DecorationId(self.next_id), range, kind, stickiness, owner };
89            ids.push(d.id);
90            if d.range.len() > LONG { self.long.push(d) } else { self.short.push(d) }
91        }
92        self.short.sort_by_key(|d| (d.range.start, d.id));
93        ids
94    }
95
96    pub fn clear(&mut self, owner: u32) {
97        let before = self.len();
98        self.short.retain(|d| d.owner != owner);
99        self.long.retain(|d| d.owner != owner);
100        if self.len() != before {
101            self.generation += 1;
102        }
103    }
104
105    pub fn get(&self, id: DecorationId) -> Option<&Decoration> {
106        self.short.iter().chain(&self.long).find(|d| d.id == id)
107    }
108
109    /// Decorations overlapping `range` (a collapsed decoration at `range.start` counts), in
110    /// order of start.
111    pub fn in_range(&self, range: Range<usize>) -> Vec<&Decoration> {
112        let from = self.short.partition_point(|d| d.range.start + LONG < range.start);
113        let mut out: Vec<&Decoration> = self.short[from..]
114            .iter()
115            .take_while(|d| d.range.start <= range.end)
116            .filter(|d| overlaps(&d.range, &range))
117            .chain(self.long.iter().filter(|d| overlaps(&d.range, &range)))
118            .collect();
119        out.sort_by_key(|d| (d.range.start, d.id));
120        out
121    }
122
123    /// Every decoration, in no particular order.
124    pub fn iter(&self) -> impl Iterator<Item = &Decoration> {
125        self.short.iter().chain(&self.long)
126    }
127
128    /// All decorations of `owner`, in order of start.
129    pub fn of_owner(&self, owner: u32) -> Vec<&Decoration> {
130        let mut out: Vec<&Decoration> = self.short.iter().chain(&self.long).filter(|d| d.owner == owner).collect();
131        out.sort_by_key(|d| (d.range.start, d.id));
132        out
133    }
134
135    /// Moves every decoration through an applied change set.
136    pub(crate) fn apply(&mut self, changes: &ChangeSet) {
137        if self.is_empty() || changes.is_empty() {
138            return;
139        }
140        self.generation += 1;
141        let edits = changes.edits();
142        let first = edits[0].start;
143        let last = edits[edits.len() - 1].end;
144        let delta: isize = edits.iter().map(|e| e.text.chars().count() as isize - (e.end - e.start) as isize).sum();
145        let map = |d: &mut Decoration| {
146            let (start_assoc, end_assoc) = match d.stickiness {
147                Stickiness::AlwaysGrows => (Assoc::Before, Assoc::After),
148                Stickiness::NeverGrows => (Assoc::After, Assoc::Before),
149                Stickiness::GrowsBefore => (Assoc::Before, Assoc::Before),
150                Stickiness::GrowsAfter => (Assoc::After, Assoc::After),
151            };
152            let start = changes.map(d.range.start, start_assoc);
153            let end = changes.map(d.range.end, end_assoc).max(start);
154            d.range = start..end;
155        };
156        // Short decorations ending before the first edit stay; those starting after the last
157        // one only shift. Only the ones in between go through the change set, so an edit
158        // costs the decorations near it, not all of them.
159        let lo = self.short.partition_point(|d| d.range.start + LONG < first);
160        let hi = self.short.partition_point(|d| d.range.start <= last);
161        for d in &mut self.short[hi..] {
162            d.range = d.range.start.wrapping_add_signed(delta)..d.range.end.wrapping_add_signed(delta);
163        }
164        self.short[lo..hi].iter_mut().for_each(map);
165        self.long.iter_mut().for_each(map);
166        // Ranges that changed length may belong to the other list now.
167        if self.short[lo..hi].iter().any(|d| d.range.len() > LONG) || self.long.iter().any(|d| d.range.len() <= LONG) {
168            let (now_long, short): (Vec<_>, Vec<_>) =
169                std::mem::take(&mut self.short).into_iter().partition(|d| d.range.len() > LONG);
170            let (now_short, long): (Vec<_>, Vec<_>) =
171                std::mem::take(&mut self.long).into_iter().partition(|d| d.range.len() <= LONG);
172            self.short = short;
173            self.short.extend(now_short);
174            self.long = long;
175            self.long.extend(now_long);
176        }
177        if !self.short.is_sorted_by_key(|d| (d.range.start, d.id)) {
178            self.short.sort_by_key(|d| (d.range.start, d.id));
179        }
180    }
181}
182
183fn overlaps(a: &Range<usize>, b: &Range<usize>) -> bool {
184    if a.is_empty() { b.start <= a.start && a.start <= b.end } else { a.start < b.end && b.start < a.end }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use crate::change::Edit;
191
192    #[test]
193    fn mapping_only_nearby_decorations_matches_mapping_all() {
194        let mut seed = 0x1234_5678_u64;
195        let mut rand = move |n: usize| {
196            seed ^= seed << 13;
197            seed ^= seed >> 7;
198            seed ^= seed << 17;
199            (seed % n.max(1) as u64) as usize
200        };
201        let mut len = 50_000;
202        let mut fast = Decorations::default();
203        let ranges: Vec<Range<usize>> = (0..2000)
204            .map(|_| {
205                let a = rand(len);
206                a..(a + if rand(10) == 0 { rand(10_000) } else { rand(30) }).min(len)
207            })
208            .collect();
209        fast.set(1, 0, Stickiness::NeverGrows, ranges.clone());
210        let mut naive: Vec<(DecorationId, Range<usize>)> = fast.iter().map(|d| (d.id, d.range.clone())).collect();
211        for _ in 0..200 {
212            let mut edits = Vec::new();
213            let mut at = 0;
214            for _ in 0..1 + rand(3) {
215                let start = (at + rand(len / 3)).min(len);
216                let end = (start + rand(20)).min(len);
217                edits.push(Edit::new(start, end, "x".repeat(rand(5))));
218                at = end + 1;
219                if at >= len {
220                    break;
221                }
222            }
223            let changes = ChangeSet::new(edits);
224            len = (len as isize
225                + changes.edits().iter().map(|e| e.text.len() as isize - (e.end - e.start) as isize).sum::<isize>())
226                as usize;
227            fast.apply(&changes);
228            for (_, r) in &mut naive {
229                let start = changes.map(r.start, Assoc::After);
230                *r = start..changes.map(r.end, Assoc::Before).max(start);
231            }
232            let mut got: Vec<(DecorationId, Range<usize>)> = fast.iter().map(|d| (d.id, d.range.clone())).collect();
233            got.sort_by_key(|x| x.0);
234            naive.sort_by_key(|x| x.0);
235            assert_eq!(got, naive);
236            assert!(fast.short.is_sorted_by_key(|d| (d.range.start, d.id)));
237        }
238    }
239
240    #[test]
241    fn decorations_follow_edits_by_stickiness() {
242        let mut d = Decorations::default();
243        let ids = d.set(1, 0, Stickiness::NeverGrows, std::iter::once(2..5));
244        let grows = d.set(2, 0, Stickiness::AlwaysGrows, std::iter::once(2..5));
245        d.apply(&ChangeSet::new(vec![Edit::insert(0, "xx"), Edit::insert(5, "yy")]));
246        assert_eq!(d.get(ids[0]).unwrap().range, 4..7, "typing at the end stays outside");
247        assert_eq!(d.get(grows[0]).unwrap().range, 4..9, "typing at the end grows it");
248        d.apply(&ChangeSet::new(vec![Edit::delete(3, 20)]));
249        assert_eq!(d.get(ids[0]).unwrap().range, 3..3, "deleted text collapses the decoration");
250    }
251
252    #[test]
253    fn lookup_by_range_includes_long_decorations() {
254        let mut d = Decorations::default();
255        d.set(1, 0, Stickiness::NeverGrows, (0..1000).map(|i| i * 10..i * 10 + 3));
256        d.set(2, 9, Stickiness::NeverGrows, std::iter::once(0..50_000));
257        let found = d.in_range(500..520);
258        assert_eq!(found.iter().filter(|x| x.owner == 1).count(), 2);
259        assert!(found.iter().any(|x| x.owner == 2));
260        d.clear(1);
261        assert_eq!(d.len(), 1);
262    }
263}