Skip to main content

rustaco_core/
selection.rs

1//! Selections and multi-cursor sets.
2
3/// A selection between `anchor` (fixed end) and `head` (the caret), in char offsets.
4/// An empty selection is a plain cursor.
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6pub struct Selection {
7    pub anchor: usize,
8    pub head: usize,
9    /// Column the caret tries to return to when moving vertically through shorter lines.
10    pub goal_column: Option<usize>,
11}
12
13impl Selection {
14    pub const fn new(anchor: usize, head: usize) -> Self {
15        Self { anchor, head, goal_column: None }
16    }
17
18    pub const fn cursor(pos: usize) -> Self {
19        Self::new(pos, pos)
20    }
21
22    pub fn start(&self) -> usize {
23        self.anchor.min(self.head)
24    }
25
26    pub fn end(&self) -> usize {
27        self.anchor.max(self.head)
28    }
29
30    pub fn len(&self) -> usize {
31        self.end() - self.start()
32    }
33
34    pub fn is_empty(&self) -> bool {
35        self.anchor == self.head
36    }
37
38    /// True when the caret sits before the anchor (selection made right to left).
39    pub fn is_backward(&self) -> bool {
40        self.head < self.anchor
41    }
42
43    fn merge(self, other: Selection) -> Selection {
44        let (start, end) = (self.start().min(other.start()), self.end().max(other.end()));
45        let backward = if self.is_empty() { other.is_backward() } else { self.is_backward() };
46        if backward { Selection::new(end, start) } else { Selection::new(start, end) }
47    }
48}
49
50/// A non-empty set of selections, sorted by position, never overlapping.
51/// One of them is primary: it scrolls into view and receives single-cursor commands.
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub struct Selections {
54    ranges: Vec<Selection>,
55    primary: usize,
56}
57
58impl Selections {
59    pub fn single(sel: Selection) -> Self {
60        Self { ranges: vec![sel], primary: 0 }
61    }
62
63    /// Builds a normalized set. Overlapping selections, and a cursor touching
64    /// another selection, are merged.
65    ///
66    /// # Panics
67    /// If `ranges` is empty or `primary` is out of bounds.
68    pub fn new(ranges: Vec<Selection>, primary: usize) -> Self {
69        assert!(primary < ranges.len(), "primary selection out of bounds");
70        let mut s = Self { ranges, primary };
71        s.normalize();
72        s
73    }
74
75    pub fn iter(&self) -> std::slice::Iter<'_, Selection> {
76        self.ranges.iter()
77    }
78
79    pub fn as_slice(&self) -> &[Selection] {
80        &self.ranges
81    }
82
83    pub fn len(&self) -> usize {
84        self.ranges.len()
85    }
86
87    pub fn is_empty(&self) -> bool {
88        false
89    }
90
91    pub fn primary(&self) -> Selection {
92        self.ranges[self.primary]
93    }
94
95    pub fn primary_index(&self) -> usize {
96        self.primary
97    }
98
99    /// Applies `f` to every selection, keeping the primary index, and renormalizes.
100    pub fn map(&self, f: impl FnMut(&Selection) -> Selection) -> Self {
101        Self::new(self.ranges.iter().map(f).collect(), self.primary)
102    }
103
104    fn normalize(&mut self) {
105        if self.ranges.len() == 1 {
106            return;
107        }
108        let mut indexed: Vec<(usize, Selection)> = self.ranges.drain(..).enumerate().collect();
109        indexed.sort_by_key(|(_, s)| (s.start(), s.end()));
110        let mut primary = 0;
111        for (i, sel) in indexed {
112            if let Some(last) = self.ranges.last_mut() {
113                let touches = sel.start() == last.end() && (sel.is_empty() || last.is_empty());
114                if sel.start() < last.end() || touches {
115                    *last = last.merge(sel);
116                    if i == self.primary {
117                        primary = self.ranges.len() - 1;
118                    }
119                    continue;
120                }
121            }
122            self.ranges.push(sel);
123            if i == self.primary {
124                primary = self.ranges.len() - 1;
125            }
126        }
127        self.primary = primary;
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn sorts_and_tracks_primary() {
137        let s = Selections::new(vec![Selection::cursor(9), Selection::cursor(2)], 0);
138        assert_eq!(s.as_slice(), [Selection::cursor(2), Selection::cursor(9)]);
139        assert_eq!(s.primary(), Selection::cursor(9));
140    }
141
142    #[test]
143    fn merges_overlap_and_touching_cursor() {
144        let s = Selections::new(
145            vec![Selection::new(0, 4), Selection::new(6, 2), Selection::cursor(6), Selection::new(7, 9)],
146            3,
147        );
148        assert_eq!(s.as_slice(), [Selection::new(0, 6), Selection::new(7, 9)]);
149        assert_eq!(s.primary_index(), 1);
150    }
151
152    #[test]
153    fn keeps_adjacent_non_empty_selections_apart() {
154        let s = Selections::new(vec![Selection::new(0, 2), Selection::new(2, 4)], 0);
155        assert_eq!(s.len(), 2);
156    }
157}