Skip to main content

strata_editor/
cursor.rs

1//! Multi-cursor tracking, selection ranges, and collision normalization.
2
3use serde::{Deserialize, Serialize};
4
5/// Exact 2D position in text buffer coordinates (0-indexed line and column).
6#[derive(
7    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
8)]
9pub struct Position {
10    pub line: usize,
11    pub col: usize,
12}
13
14impl Position {
15    pub const ZERO: Self = Self { line: 0, col: 0 };
16
17    pub const fn new(line: usize, col: usize) -> Self {
18        Self { line, col }
19    }
20}
21
22/// A text selection representing an active cursor caret or highlighted range.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
24pub struct Selection {
25    /// Fixed anchor origin where selection started.
26    pub anchor: Position,
27    /// Active focus point where the caret currently sits.
28    pub focus: Position,
29}
30
31impl Selection {
32    /// Constructs a collapsed single-point cursor caret.
33    pub const fn point(pos: Position) -> Self {
34        Self {
35            anchor: pos,
36            focus: pos,
37        }
38    }
39
40    /// Constructs a selection range between anchor and focus.
41    pub const fn range(anchor: Position, focus: Position) -> Self {
42        Self { anchor, focus }
43    }
44
45    /// Returns whether this selection is a collapsed single-point caret.
46    pub fn is_collapsed(&self) -> bool {
47        self.anchor == self.focus
48    }
49
50    /// Returns the ordered start and end positions `(start, end)` where `start <= end`.
51    pub fn ordered_range(&self) -> (Position, Position) {
52        if self.anchor <= self.focus {
53            (self.anchor, self.focus)
54        } else {
55            (self.focus, self.anchor)
56        }
57    }
58
59    /// Returns whether this selection contains the given position.
60    pub fn contains(&self, pos: Position) -> bool {
61        let (start, end) = self.ordered_range();
62        pos >= start && pos <= end
63    }
64
65    /// Checks if this selection overlaps or directly touches another selection.
66    pub fn touches_or_overlaps(&self, other: &Selection) -> bool {
67        let (s1, e1) = self.ordered_range();
68        let (s2, e2) = other.ordered_range();
69        !(e1 < s2 || e2 < s1)
70    }
71
72    /// Merges this selection with an overlapping selection.
73    pub fn merge(&self, other: &Selection) -> Self {
74        let (s1, e1) = self.ordered_range();
75        let (s2, e2) = other.ordered_range();
76        let min_pos = s1.min(s2);
77        let max_pos = e1.max(e2);
78        Self {
79            anchor: min_pos,
80            focus: max_pos,
81        }
82    }
83}
84
85/// Multi-cursor engine managing synchronized cursors across the document.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct MultiCursor {
88    selections: Vec<Selection>,
89    primary_idx: usize,
90}
91
92impl Default for MultiCursor {
93    fn default() -> Self {
94        Self::new()
95    }
96}
97
98impl MultiCursor {
99    /// Initializes multi-cursor engine with a single cursor at `(0, 0)`.
100    pub fn new() -> Self {
101        Self {
102            selections: vec![Selection::point(Position::ZERO)],
103            primary_idx: 0,
104        }
105    }
106
107    /// Initializes with a single cursor at specified position.
108    pub fn single(pos: Position) -> Self {
109        Self {
110            selections: vec![Selection::point(pos)],
111            primary_idx: 0,
112        }
113    }
114
115    /// Constructs a MultiCursor engine directly from a collection of selections.
116    pub fn from_selections(selections: Vec<Selection>) -> Self {
117        if selections.is_empty() {
118            Self::new()
119        } else {
120            let mut mc = Self {
121                selections,
122                primary_idx: 0,
123            };
124            mc.normalize();
125            mc
126        }
127    }
128
129    /// Returns the primary active selection.
130    pub fn primary(&self) -> &Selection {
131        &self.selections[self.primary_idx]
132    }
133
134    /// Returns all active selections.
135    pub fn all(&self) -> &[Selection] {
136        &self.selections
137    }
138
139    /// Returns mutable slice of all selections.
140    pub fn all_mut(&mut self) -> &mut [Selection] {
141        &mut self.selections
142    }
143
144    /// Clears all selections.
145    pub fn clear(&mut self) {
146        self.selections.clear();
147        self.primary_idx = 0;
148    }
149
150    /// Clears secondary cursors and sets single active caret.
151    pub fn set_single(&mut self, pos: Position) {
152        self.selections = vec![Selection::point(pos)];
153        self.primary_idx = 0;
154    }
155
156    /// Appends a new cursor or selection range, automatically normalizing and merging.
157    pub fn add_selection(&mut self, sel: Selection) {
158        self.selections.push(sel);
159        self.normalize();
160    }
161
162    /// Appends a new single-point cursor caret at `pos`.
163    pub fn add_cursor(&mut self, pos: Position) {
164        self.add_selection(Selection::point(pos));
165    }
166
167    /// Returns the number of active selections/cursors.
168    pub fn count(&self) -> usize {
169        self.selections.len()
170    }
171
172    /// Adds rectangular column block cursors between `start_line` and `end_line` at column `col`.
173    pub fn add_column_cursors(&mut self, start_line: usize, end_line: usize, col: usize) {
174        let min_l = start_line.min(end_line);
175        let max_l = start_line.max(end_line);
176
177        self.selections.clear();
178        for l in min_l..=max_l {
179            self.selections
180                .push(Selection::point(Position::new(l, col)));
181        }
182        self.primary_idx = 0;
183        self.normalize();
184    }
185
186    /// Normalizes selections: sorts them in document order and merges any overlapping carets.
187    pub fn normalize(&mut self) {
188        if self.selections.len() <= 1 {
189            return;
190        }
191
192        self.selections.sort_by_key(|s| s.ordered_range().0);
193
194        let mut merged: Vec<Selection> = Vec::with_capacity(self.selections.len());
195        for sel in self.selections.drain(..) {
196            if let Some(last) = merged.last_mut() {
197                if last.touches_or_overlaps(&sel) {
198                    *last = last.merge(&sel);
199                    continue;
200                }
201            }
202            merged.push(sel);
203        }
204
205        self.selections = merged;
206        if self.primary_idx >= self.selections.len() {
207            self.primary_idx = self.selections.len().saturating_sub(1);
208        }
209    }
210
211    /// Returns all active selections sorted in descending document order (bottom-to-top, right-to-left).
212    pub fn selections_descending(&self) -> Vec<Selection> {
213        let mut sorted = self.selections.clone();
214        sorted.sort_by_key(|a| std::cmp::Reverse(a.ordered_range().0));
215        sorted
216    }
217}
218
219/// Shifts a position based on a preceding document edit that replaced range `edit_start..edit_end` with `inserted_lines`.
220pub fn shift_position_after_edit(
221    pos: Position,
222    edit_start: Position,
223    edit_end: Position,
224    inserted_lines: &[&str],
225) -> Position {
226    if pos < edit_start {
227        return pos;
228    }
229
230    let delta_lines =
231        (inserted_lines.len() as isize - 1) - (edit_end.line as isize - edit_start.line as isize);
232
233    if pos <= edit_end {
234        if inserted_lines.len() == 1 {
235            Position::new(
236                edit_start.line,
237                edit_start.col + inserted_lines[0].chars().count(),
238            )
239        } else {
240            let last_line_len = inserted_lines.last().map_or(0, |l| l.chars().count());
241            Position::new(edit_start.line + inserted_lines.len() - 1, last_line_len)
242        }
243    } else if pos.line == edit_end.line {
244        let col_offset = pos.col - edit_end.col;
245        if inserted_lines.len() == 1 {
246            Position::new(
247                edit_start.line,
248                edit_start.col + inserted_lines[0].chars().count() + col_offset,
249            )
250        } else {
251            let last_line_len = inserted_lines.last().map_or(0, |l| l.chars().count());
252            let target_line = (pos.line as isize + delta_lines).max(0) as usize;
253            Position::new(target_line, last_line_len + col_offset)
254        }
255    } else {
256        let target_line = (pos.line as isize + delta_lines).max(0) as usize;
257        Position::new(target_line, pos.col)
258    }
259}