iced-code-editor 0.5.0

A custom code editor widget for the Iced GUI framework with syntax highlighting, line numbers, and scrolling support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Arrow-key, Home/End, Ctrl+Home/End, Page Up/Down, and goto-position message handlers.

use iced::Task;

use crate::canvas_editor::{ArrowDirection, CodeEditor, Message, VimMode};

impl CodeEditor {
    pub(crate) fn vim_accepts_insert_input(&self) -> bool {
        !self.vim_enabled || self.vim_state.mode() == VimMode::Insert
    }

    /// Prepares the selection state of every cursor before a navigation move.
    ///
    /// When Shift is held, each cursor that has no anchor yet gets one at its
    /// current position so the upcoming move extends a selection. Otherwise
    /// every selection is dropped, so the move only relocates the cursors.
    ///
    /// Shared by the arrow keys, Home/End and Page Up/Down handlers.
    ///
    /// # Arguments
    ///
    /// * `shift_pressed` - Whether Shift is held (for selection)
    fn prepare_selection_for_move(&mut self, shift_pressed: bool) {
        if shift_pressed {
            // Set anchor on ALL cursors that don't yet have one
            for cursor in self.cursors.as_mut_slice() {
                if cursor.anchor.is_none() {
                    cursor.set_anchor();
                }
            }
        } else {
            // Clear all selections so the move does not drag one along
            self.clear_selection();
        }
    }

    /// Handles arrow key navigation.
    ///
    /// # Arguments
    ///
    /// * `direction` - The direction of movement
    /// * `shift_pressed` - Whether Shift is held (for selection)
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that scrolls to keep the cursor visible
    pub(crate) fn handle_arrow_key(
        &mut self,
        direction: ArrowDirection,
        shift_pressed: bool,
    ) -> Task<Message> {
        // End grouping on navigation
        self.end_grouping_if_active();

        self.prepare_selection_for_move(shift_pressed);
        self.move_cursor(direction);
        self.finish_navigation_operation();
        self.scroll_to_cursor()
    }

    /// Handles Home key press.
    ///
    /// Moves the cursor to the start of the current line.
    ///
    /// # Arguments
    ///
    /// * `shift_pressed` - Whether Shift is held (for selection)
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that scrolls to keep the cursor visible (including
    /// horizontal scroll back to x=0 when wrap is disabled)
    pub(crate) fn handle_home(&mut self, shift_pressed: bool) -> Task<Message> {
        self.prepare_selection_for_move(shift_pressed);
        for cursor in self.cursors.as_mut_slice() {
            cursor.position.1 = 0;
        }
        self.cursors.sort_and_merge();
        self.finish_navigation_operation();
        self.scroll_to_cursor()
    }

    /// Handles End key press.
    ///
    /// Moves the cursor to the end of the current line.
    ///
    /// # Arguments
    ///
    /// * `shift_pressed` - Whether Shift is held (for selection)
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that scrolls to keep the cursor visible (including
    /// horizontal scroll to end of line when wrap is disabled)
    pub(crate) fn handle_end(&mut self, shift_pressed: bool) -> Task<Message> {
        self.prepare_selection_for_move(shift_pressed);
        for cursor in self.cursors.as_mut_slice() {
            cursor.position.1 = self.buffer.line_len(cursor.position.0);
        }
        self.cursors.sort_and_merge();
        self.finish_navigation_operation();
        self.scroll_to_cursor()
    }

    /// Handles Ctrl+Home key press.
    ///
    /// Moves the cursor to the beginning of the document.
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that scrolls to keep the cursor visible
    pub(crate) fn handle_ctrl_home(&mut self) -> Task<Message> {
        // Move cursor to the beginning of the document
        self.clear_selection();
        self.cursors.set_single((0, 0));
        self.finish_navigation_operation();
        self.scroll_to_cursor()
    }

    /// Handles Ctrl+End key press.
    ///
    /// Moves the cursor to the end of the document.
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that scrolls to keep the cursor visible
    pub(crate) fn handle_ctrl_end(&mut self) -> Task<Message> {
        // Move cursor to the end of the document
        self.clear_selection();
        let last_line = self.buffer.line_count().saturating_sub(1);
        let last_col = self.buffer.line_len(last_line);
        self.cursors.set_single((last_line, last_col));
        self.finish_navigation_operation();
        self.scroll_to_cursor()
    }

    /// Handles Page Up key press.
    ///
    /// Moves every cursor up by one viewport height.
    ///
    /// # Arguments
    ///
    /// * `shift_pressed` - Whether Shift is held (for selection)
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that scrolls to keep the cursor visible
    pub(crate) fn handle_page_up(
        &mut self,
        shift_pressed: bool,
    ) -> Task<Message> {
        // End grouping on navigation
        self.end_grouping_if_active();

        self.prepare_selection_for_move(shift_pressed);
        self.page_up();
        self.finish_navigation_operation();
        self.scroll_to_cursor()
    }

    /// Handles Page Down key press.
    ///
    /// Moves every cursor down by one viewport height.
    ///
    /// # Arguments
    ///
    /// * `shift_pressed` - Whether Shift is held (for selection)
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that scrolls to keep the cursor visible
    pub(crate) fn handle_page_down(
        &mut self,
        shift_pressed: bool,
    ) -> Task<Message> {
        // End grouping on navigation
        self.end_grouping_if_active();

        self.prepare_selection_for_move(shift_pressed);
        self.page_down();
        self.finish_navigation_operation();
        self.scroll_to_cursor()
    }

    /// Handles direct navigation to an explicit logical position.
    ///
    /// # Arguments
    ///
    /// * `line` - Target line index (0-based)
    /// * `col` - Target column index (0-based)
    ///
    /// # Returns
    ///
    /// A `Task<Message>` that scrolls to keep the cursor visible
    pub(crate) fn handle_goto_position(
        &mut self,
        line: usize,
        col: usize,
    ) -> Task<Message> {
        // End grouping on navigation command
        self.end_grouping_if_active();
        self.set_cursor(line, col)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_home_key() {
        let mut editor = CodeEditor::new("hello world", "py");
        editor.cursors.primary_mut().position = (0, 5); // Move to middle of line
        let _ = editor.update(&Message::Home(false));
        assert_eq!(editor.cursors.primary_position(), (0, 0));
    }

    #[test]
    fn test_end_key() {
        let mut editor = CodeEditor::new("hello world", "py");
        editor.cursors.primary_mut().position = (0, 0);
        let _ = editor.update(&Message::End(false));
        assert_eq!(editor.cursors.primary_position(), (0, 11)); // Length of "hello world"
    }

    #[test]
    fn test_arrow_key_with_shift_creates_selection() {
        let mut editor = CodeEditor::new("hello world", "py");
        editor.cursors.primary_mut().position = (0, 0);

        // Shift+Right should start selection
        let _ = editor.update(&Message::ArrowKey(ArrowDirection::Right, true));
        assert!(editor.cursors.primary().anchor.is_some());
        assert!(editor.cursors.primary().has_selection());
    }

    #[test]
    fn test_arrow_key_without_shift_clears_selection() {
        let mut editor = CodeEditor::new("hello world", "py");
        editor.cursors.primary_mut().anchor = Some((0, 0));
        editor.cursors.primary_mut().position = (0, 5);

        // Regular arrow key should clear selection
        let _ = editor.update(&Message::ArrowKey(ArrowDirection::Right, false));
        assert!(editor.cursors.primary().anchor.is_none());
        assert!(!editor.cursors.primary().has_selection());
    }

    /// Builds a multi-line editor whose viewport is exactly three lines tall,
    /// so `Page Up`/`Page Down` move by a known number of lines.
    fn paged_editor() -> CodeEditor {
        let content = (0..10)
            .map(|index| format!("line{index}"))
            .collect::<Vec<_>>()
            .join("\n");
        let mut editor = CodeEditor::new(&content, "py");
        editor.viewport_height = editor.line_height * 3.0;
        editor
    }

    #[test]
    fn test_page_down_without_shift_clears_selection() {
        let mut editor = paged_editor();
        editor.cursors.primary_mut().anchor = Some((0, 0));
        editor.cursors.primary_mut().position = (0, 2);

        let _ = editor.update(&Message::PageDown(false));

        assert_eq!(editor.cursors.primary_position(), (3, 2));
        assert!(editor.cursors.primary().anchor.is_none());
        assert!(!editor.cursors.primary().has_selection());
    }

    #[test]
    fn test_page_up_without_shift_clears_selection() {
        let mut editor = paged_editor();
        editor.cursors.primary_mut().anchor = Some((9, 0));
        editor.cursors.primary_mut().position = (5, 2);

        let _ = editor.update(&Message::PageUp(false));

        assert_eq!(editor.cursors.primary_position(), (2, 2));
        assert!(editor.cursors.primary().anchor.is_none());
        assert!(!editor.cursors.primary().has_selection());
    }

    #[test]
    fn test_page_down_with_shift_creates_selection() {
        let mut editor = paged_editor();
        editor.cursors.primary_mut().position = (0, 0);

        let _ = editor.update(&Message::PageDown(true));

        assert_eq!(editor.cursors.primary_position(), (3, 0));
        assert_eq!(editor.cursors.primary().anchor, Some((0, 0)));
        assert!(editor.cursors.primary().has_selection());
    }

    #[test]
    fn test_page_up_with_shift_creates_selection() {
        let mut editor = paged_editor();
        editor.cursors.primary_mut().position = (5, 0);

        let _ = editor.update(&Message::PageUp(true));

        assert_eq!(editor.cursors.primary_position(), (2, 0));
        assert_eq!(editor.cursors.primary().anchor, Some((5, 0)));
        assert!(editor.cursors.primary().has_selection());
    }

    #[test]
    fn test_page_down_after_click_does_not_select() {
        // Regression test: a plain click leaves an anchor behind for a
        // potential drag selection; Page Down must not turn it into one.
        let mut editor = paged_editor();
        let point = iced::Point::new(
            editor.gutter_width() + 5.0 + editor.char_width * 2.0,
            editor.line_height / 2.0,
        );

        let _ = editor.update(&Message::MouseClick(point));
        let _ = editor.update(&Message::MouseRelease);
        assert!(!editor.cursors.primary().has_selection());

        let _ = editor.update(&Message::PageDown(false));

        assert!(editor.cursors.primary().anchor.is_none());
        assert!(!editor.cursors.primary().has_selection());
    }

    #[test]
    fn test_page_down_ends_grouping() {
        let mut editor = paged_editor();
        editor.request_focus();
        editor.has_canvas_focus = true;
        editor.focus_locked = false;
        editor.cursors.primary_mut().position = (0, 5);

        let _ = editor.update(&Message::CharacterInput('!'));
        assert!(editor.is_grouping);

        let _ = editor.update(&Message::PageDown(false));
        assert!(!editor.is_grouping);
    }

    #[test]
    fn test_ctrl_home() {
        let mut editor = CodeEditor::new("line1\nline2\nline3", "py");
        editor.cursors.primary_mut().position = (2, 5); // Start at line 3, column 5
        let _ = editor.update(&Message::CtrlHome);
        assert_eq!(editor.cursors.primary_position(), (0, 0)); // Should move to beginning of document
    }

    #[test]
    fn test_ctrl_end() {
        let mut editor = CodeEditor::new("line1\nline2\nline3", "py");
        editor.cursors.primary_mut().position = (0, 0); // Start at beginning
        let _ = editor.update(&Message::CtrlEnd);
        assert_eq!(editor.cursors.primary_position(), (2, 5)); // Should move to end of last line (line3 has 5 chars)
    }

    #[test]
    fn test_ctrl_home_clears_selection() {
        let mut editor = CodeEditor::new("line1\nline2\nline3", "py");
        editor.cursors.primary_mut().position = (2, 5);
        editor.cursors.primary_mut().anchor = Some((0, 0));
        editor.cursors.primary_mut().position = (2, 5);

        let _ = editor.update(&Message::CtrlHome);
        assert_eq!(editor.cursors.primary_position(), (0, 0));
        assert!(editor.cursors.primary().anchor.is_none());
        assert!(!editor.cursors.primary().has_selection());
    }

    #[test]
    fn test_ctrl_end_clears_selection() {
        let mut editor = CodeEditor::new("line1\nline2\nline3", "py");
        editor.cursors.primary_mut().position = (0, 0);
        editor.cursors.primary_mut().anchor = Some((0, 0));
        editor.cursors.primary_mut().position = (1, 3);

        let _ = editor.update(&Message::CtrlEnd);
        assert_eq!(editor.cursors.primary_position(), (2, 5));
        assert!(editor.cursors.primary().anchor.is_none());
        assert!(!editor.cursors.primary().has_selection());
    }

    #[test]
    fn test_goto_position_sets_cursor_and_clears_selection() {
        let mut editor = CodeEditor::new("line1\nline2\nline3", "py");
        editor.cursors.primary_mut().anchor = Some((0, 0));
        editor.cursors.primary_mut().position = (1, 2);

        let _ = editor.update(&Message::GotoPosition(1, 3));

        assert_eq!(editor.cursors.primary_position(), (1, 3));
        assert!(editor.cursors.primary().anchor.is_none());
        assert!(!editor.cursors.primary().has_selection());
    }

    #[test]
    fn test_goto_position_clamps_out_of_range() {
        let mut editor = CodeEditor::new("a\nbb", "py");

        let _ = editor.update(&Message::GotoPosition(99, 99));

        // Clamped to last line (index 1) and end of that line (len = 2)
        assert_eq!(editor.cursors.primary_position(), (1, 2));
    }

    #[test]
    fn test_navigation_ends_grouping() {
        let mut editor = CodeEditor::new("hello", "py");
        // Ensure editor has focus for character input
        editor.request_focus();
        editor.has_canvas_focus = true;
        editor.focus_locked = false;

        editor.cursors.primary_mut().position = (0, 5);

        // Type a character (starts grouping)
        let _ = editor.update(&Message::CharacterInput('!'));
        assert!(editor.is_grouping);

        // Move cursor (ends grouping)
        let _ = editor.update(&Message::ArrowKey(ArrowDirection::Left, false));
        assert!(!editor.is_grouping);

        // Type another character (starts new group)
        let _ = editor.update(&Message::CharacterInput('?'));
        assert!(editor.is_grouping);

        editor.history.end_group();

        // Two separate undo operations
        let _ = editor.update(&Message::Undo);
        assert_eq!(editor.buffer.line(0), "hello!");

        let _ = editor.update(&Message::Undo);
        assert_eq!(editor.buffer.line(0), "hello");
    }
}