Skip to main content

iced_code_editor/canvas_editor/editing/
selection.rs

1//! Text selection logic.
2
3use crate::buffer::text_utils::{char_range_to_byte_range, char_to_byte_index};
4use crate::canvas_editor::CodeEditor;
5
6impl CodeEditor {
7    /// Clears the current selection on all cursors.
8    pub(crate) fn clear_selection(&mut self) {
9        self.cursors.clear_all_selections();
10        // Selection affects only overlay visuals (highlight rectangles), so avoid
11        // invalidating the expensive content cache.
12        self.overlay_cache.clear();
13    }
14
15    /// Returns the primary cursor's selection as `(start, end)` positions.
16    ///
17    /// Positions are `(line, column)`, 0-indexed, with the column counted in
18    /// characters (like [`CodeEditor::cursor_position`]). The range is
19    /// normalized: `start` comes before `end`, whichever way the selection
20    /// was made. Returns `None` when nothing is selected. With several
21    /// cursors, only the primary one is considered.
22    ///
23    /// # Example
24    ///
25    /// ```
26    /// use iced_code_editor::{CodeEditor, Message};
27    ///
28    /// let mut editor = CodeEditor::new("one\ntwo", "txt");
29    /// assert_eq!(editor.selection_range(), None);
30    ///
31    /// let _ = editor.update(&Message::SelectAll);
32    /// assert_eq!(editor.selection_range(), Some(((0, 0), (1, 3))));
33    /// ```
34    pub fn selection_range(&self) -> Option<((usize, usize), (usize, usize))> {
35        self.get_selection_range().filter(|(start, end)| start != end)
36    }
37
38    /// Returns the text selected by the primary cursor.
39    ///
40    /// Lines are joined with `\n`. Returns `None` when nothing is selected.
41    /// With several cursors, only the primary one is considered.
42    ///
43    /// # Example
44    ///
45    /// ```
46    /// use iced_code_editor::{CodeEditor, Message};
47    ///
48    /// let mut editor = CodeEditor::new("one\ntwo", "txt");
49    /// assert_eq!(editor.selected_text(), None);
50    ///
51    /// let _ = editor.update(&Message::SelectAll);
52    /// assert_eq!(editor.selected_text().as_deref(), Some("one\ntwo"));
53    /// ```
54    pub fn selected_text(&self) -> Option<String> {
55        self.get_selected_text()
56    }
57
58    /// Returns the primary cursor's selected text range in normalized order (start before end).
59    pub(crate) fn get_selection_range(
60        &self,
61    ) -> Option<((usize, usize), (usize, usize))> {
62        self.cursors.primary().selection_range()
63    }
64
65    /// Returns the selected text of the primary cursor as a string.
66    pub(crate) fn get_selected_text(&self) -> Option<String> {
67        let (start, end) = self.get_selection_range()?;
68
69        if start == end {
70            return None; // No selection
71        }
72
73        Some(self.extract_text_range(start, end))
74    }
75
76    /// Extracts text between two positions from the buffer.
77    pub(crate) fn extract_text_range(
78        &self,
79        start: (usize, usize),
80        end: (usize, usize),
81    ) -> String {
82        let mut result = String::new();
83
84        if start.0 == end.0 {
85            // Single line selection
86            let line = self.buffer.line(start.0);
87            let (start_byte, end_byte) =
88                char_range_to_byte_range(line, start.1, end.1);
89            result.push_str(&line[start_byte..end_byte]);
90        } else {
91            // Multi-line selection
92            // First line
93            let first_line = self.buffer.line(start.0);
94            let start_byte = char_to_byte_index(first_line, start.1);
95            result.push_str(&first_line[start_byte..]);
96            result.push('\n');
97
98            // Middle lines
99            for line_idx in (start.0 + 1)..end.0 {
100                result.push_str(self.buffer.line(line_idx));
101                result.push('\n');
102            }
103
104            // Last line
105            let last_line = self.buffer.line(end.0);
106            let end_byte = char_to_byte_index(last_line, end.1);
107            result.push_str(&last_line[..end_byte]);
108        }
109
110        result
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn test_selection_single_line() {
120        let mut editor = CodeEditor::new("hello world", "py");
121        editor.cursors.primary_mut().anchor = Some((0, 0));
122        editor.cursors.primary_mut().position = (0, 5);
123
124        let text = editor.get_selected_text();
125        assert_eq!(text, Some("hello".to_string()));
126    }
127
128    #[test]
129    fn test_selection_multiline() {
130        let mut editor = CodeEditor::new("line1\nline2\nline3", "py");
131        editor.cursors.primary_mut().anchor = Some((0, 2));
132        editor.cursors.primary_mut().position = (2, 3);
133
134        let text = editor.get_selected_text();
135        assert_eq!(text, Some("ne1\nline2\nlin".to_string()));
136    }
137
138    #[test]
139    fn test_selection_range_normalization() {
140        let mut editor = CodeEditor::new("hello world", "py");
141        // Set selection in reverse order (end before start)
142        editor.cursors.primary_mut().anchor = Some((0, 5));
143        editor.cursors.primary_mut().position = (0, 0);
144
145        let range = editor.get_selection_range();
146        // Should normalize to (0,0) -> (0,5)
147        assert_eq!(range, Some(((0, 0), (0, 5))));
148    }
149
150    #[test]
151    fn test_clear_selection() {
152        let mut editor = CodeEditor::new("hello world", "py");
153        editor.cursors.primary_mut().anchor = Some((0, 0));
154        editor.cursors.primary_mut().position = (0, 5);
155
156        editor.clear_selection();
157        assert!(!editor.cursors.primary().has_selection());
158    }
159
160    #[test]
161    fn test_selection_out_of_bounds() {
162        let mut editor = CodeEditor::new("hello", "py");
163        // Start out of bounds (column 10)
164        editor.cursors.primary_mut().anchor = Some((0, 10));
165        editor.cursors.primary_mut().position = (0, 15);
166
167        let text = editor.get_selected_text();
168        // With the fix, start is out of bounds, so we get empty string.
169        assert_eq!(text, Some("".to_string()));
170    }
171
172    #[test]
173    fn test_selection_multiline_out_of_bounds() {
174        let mut editor = CodeEditor::new("line1\nline2\nline3", "py");
175        // Start out of bounds on first line
176        editor.cursors.primary_mut().anchor = Some((0, 10));
177        // End normal on last line
178        editor.cursors.primary_mut().position = (2, 3);
179
180        let text = editor.get_selected_text();
181        // An out-of-bounds start column is clamped to the end of the first
182        // line, so the selection starts there and includes the newline that
183        // separates it from the next line.
184        assert_eq!(text, Some("\nline2\nlin".to_string()));
185
186        // Now test end out of bounds
187        editor.cursors.primary_mut().anchor = Some((0, 2));
188        editor.cursors.primary_mut().position = (2, 10);
189        let text = editor.get_selected_text();
190        assert_eq!(text, Some("ne1\nline2\nline3".to_string()));
191    }
192
193    #[test]
194    fn test_selection_unicode() {
195        let mut editor = CodeEditor::new("你好\n世界", "txt");
196
197        editor.cursors.primary_mut().anchor = Some((0, 1));
198        editor.cursors.primary_mut().position = (1, 1);
199
200        let text = editor.get_selected_text();
201        assert_eq!(text, Some("好\n世".to_string()));
202    }
203
204    #[test]
205    fn test_selection_with_empty_lines() {
206        let mut editor = CodeEditor::new("line1\n\nline3", "txt");
207        editor.cursors.primary_mut().anchor = Some((0, 0));
208        editor.cursors.primary_mut().position = (2, 5);
209
210        let text = editor.get_selected_text();
211        assert_eq!(text, Some("line1\n\nline3".to_string()));
212    }
213
214    #[test]
215    fn test_selection_emoji() {
216        let mut editor = CodeEditor::new("a😀b", "txt");
217
218        editor.cursors.primary_mut().anchor = Some((0, 1));
219        editor.cursors.primary_mut().position = (0, 2);
220
221        let text = editor.get_selected_text();
222        assert_eq!(text, Some("😀".to_string()));
223    }
224
225    #[test]
226    #[allow(clippy::unwrap_used)]
227    fn test_selection_complex_emoji() {
228        let complex_emoji = "👨‍👩‍👧‍👦";
229        let mut editor = CodeEditor::new(complex_emoji, "txt");
230
231        let char_count = complex_emoji.chars().count();
232
233        editor.cursors.primary_mut().anchor = Some((0, 0));
234        editor.cursors.primary_mut().position = (0, char_count);
235
236        let text = editor.get_selected_text();
237        assert_eq!(text, Some(complex_emoji.to_string()));
238
239        if char_count > 1 {
240            editor.cursors.primary_mut().anchor = Some((0, 0));
241            editor.cursors.primary_mut().position = (0, 1);
242            let text = editor.get_selected_text();
243            let first_char = complex_emoji.chars().next().unwrap().to_string();
244            assert_eq!(text, Some(first_char));
245        }
246    }
247}