Skip to main content

ratatui_code_editor/
actions.rs

1use crate::code::Operation;
2use crate::editor::Editor;
3use crate::selection::Selection;
4
5pub trait Action {
6    fn apply(&mut self, editor: &mut Editor);
7}
8
9/// Moves the cursor one character to the right.
10///
11/// If `shift` is true, the selection is extended to the new cursor position.
12/// If `shift` is false and there is an active selection, the cursor jumps
13/// to the end of the selection and the selection is cleared.
14/// Otherwise, the cursor moves one position to the right.
15pub struct MoveRight {
16    pub shift: bool,
17}
18
19impl Action for MoveRight {
20    fn apply(&mut self, editor: &mut Editor) {
21        let cursor = editor.get_cursor();
22
23        if !self.shift {
24            if let Some(sel) = editor.get_selection() {
25                if !sel.is_empty() {
26                    let (_, end) = sel.sorted();
27                    editor.set_cursor(end);
28                    editor.clamp_cursor_to_focus_rows();
29                    editor.clear_selection();
30                    return;
31                }
32            }
33        }
34
35        if cursor < editor.code_ref().len() {
36            let code = editor.code_ref();
37            let mut new_cursor = code.next_grapheme_boundary(cursor);
38            let new_line = code.char_to_line(new_cursor);
39            if !editor.line_visible(new_line) {
40                if let Some(next_line) = editor.next_line(new_line) {
41                    new_cursor = code.line_to_char(next_line);
42                }
43            }
44            if self.shift {
45                editor.extend_selection(new_cursor);
46            } else {
47                editor.clear_selection();
48            }
49            editor.set_cursor(new_cursor);
50            editor.clamp_cursor_to_focus_rows();
51        }
52    }
53}
54
55/// Moves the cursor one character to the left.
56///
57/// If `shift` is true, the selection is extended to the new cursor position.
58/// If `shift` is false and there is an active selection, the cursor jumps
59/// to the start of the selection and the selection is cleared.
60/// Otherwise, the cursor moves one position to the left.
61pub struct MoveLeft {
62    pub shift: bool,
63}
64
65impl Action for MoveLeft {
66    fn apply(&mut self, editor: &mut Editor) {
67        let cursor = editor.get_cursor();
68
69        if !self.shift {
70            if let Some(sel) = editor.get_selection() {
71                if !sel.is_empty() {
72                    let (start, _) = sel.sorted();
73                    editor.set_cursor(start);
74                    editor.clamp_cursor_to_focus_rows();
75                    editor.clear_selection();
76                    return;
77                }
78            }
79        }
80
81        if cursor > 0 {
82            let code = editor.code_ref();
83            let mut new_cursor = code.prev_grapheme_boundary(cursor);
84            let new_line = code.char_to_line(new_cursor);
85            if !editor.line_visible(new_line) {
86                if let Some(prev_line) = editor.prev_line(new_line) {
87                    new_cursor =
88                        code.line_to_char(prev_line) + code.line_len(prev_line).saturating_sub(1);
89                }
90            }
91            if self.shift {
92                editor.extend_selection(new_cursor);
93            } else {
94                editor.clear_selection();
95            }
96            editor.set_cursor(new_cursor);
97            editor.clamp_cursor_to_focus_rows();
98        }
99    }
100}
101
102/// Moves the cursor one line up.
103///
104/// If the previous line is shorter, the cursor is placed at the end of that line.
105/// If `shift` is true, the selection is extended to the new cursor position.
106/// If `shift` is false, the selection is cleared.
107pub struct MoveUp {
108    pub shift: bool,
109}
110
111impl Action for MoveUp {
112    fn apply(&mut self, editor: &mut Editor) {
113        let cursor = editor.get_cursor();
114        let code = editor.code_ref();
115        let (row, col) = code.point(cursor);
116
117        let Some(prev_row) = editor.prev_line(row) else {
118            return;
119        };
120
121        let current_visual_col = code.char_col_to_visual(row, col);
122        let prev_start = code.line_to_char(prev_row);
123        let prev_len = code.line_len(prev_row);
124        let new_col = code
125            .visual_to_char_col(prev_row, current_visual_col)
126            .min(prev_len);
127        let new_cursor = prev_start + new_col;
128
129        // Update selection or clear it
130        if self.shift {
131            editor.extend_selection(new_cursor);
132        } else {
133            editor.clear_selection();
134        }
135
136        // Set the new cursor position
137        editor.set_cursor(new_cursor);
138        editor.clamp_cursor_to_focus_rows();
139    }
140}
141
142/// Moves the cursor one line down.
143///
144/// If the next line is shorter, the cursor is placed at the end of that line.
145/// If `shift` is true, the selection is extended to the new cursor position.
146/// If `shift` is false, the selection is cleared.
147///
148pub struct MoveDown {
149    pub shift: bool,
150}
151
152impl Action for MoveDown {
153    fn apply(&mut self, editor: &mut Editor) {
154        let cursor = editor.get_cursor();
155        let code = editor.code_ref();
156        let (row, col) = code.point(cursor);
157        let Some(next_row) = editor.next_line(row) else {
158            return;
159        };
160
161        let current_visual_col = code.char_col_to_visual(row, col);
162        let next_start = code.line_to_char(next_row);
163        let next_len = code.line_len(next_row);
164        let new_col = code
165            .visual_to_char_col(next_row, current_visual_col)
166            .min(next_len);
167        let new_cursor = next_start + new_col;
168
169        // Update selection or clear it
170        if self.shift {
171            editor.extend_selection(new_cursor);
172        } else {
173            editor.clear_selection();
174        }
175
176        // Set the new cursor position
177        editor.set_cursor(new_cursor);
178        editor.clamp_cursor_to_focus_rows();
179    }
180}
181
182/// Inserts arbitrary text at the cursor, replacing the selection if any.
183pub struct InsertText {
184    pub text: String,
185}
186
187impl Action for InsertText {
188    fn apply(&mut self, editor: &mut Editor) {
189        // 1. Extract current cursor and selection
190        let mut cursor = editor.get_cursor();
191        let mut selection = editor.get_selection();
192
193        // 2. Work with code
194        let code = editor.code_mut();
195        code.tx();
196        code.set_state_before(cursor, selection);
197
198        // 3. Remove selection if present
199        if let Some(sel) = &selection {
200            if !sel.is_empty() {
201                let (start, end) = sel.sorted();
202                code.remove(start, end);
203                cursor = start;
204            }
205        }
206        selection = None;
207
208        // 4. Insert the text at the cursor
209        code.insert(cursor, &self.text);
210        cursor += self.text.chars().count();
211
212        // 5. Update editor state
213        code.set_state_after(cursor, selection);
214        code.commit();
215
216        editor.set_cursor(cursor);
217        editor.set_selection(selection);
218        editor.reset_highlight_cache();
219    }
220}
221
222/// Inserts a newline at the cursor with automatic indentation.
223///
224/// The indentation is computed based on the current line and column.
225/// Delegates the actual insertion to `InsertText`.
226pub struct InsertNewline;
227
228impl Action for InsertNewline {
229    fn apply(&mut self, editor: &mut Editor) {
230        // 1. Get current cursor position
231        let cursor = editor.get_cursor();
232        let code = editor.code_mut();
233        let (row, col) = code.point(cursor);
234
235        // 2. Compute indentation for the new line
236        let indent_level = code.indentation_level(row, col);
237        let indent_text = code.indent().repeat(indent_level);
238
239        // 3. Prepare the text to insert
240        let text_to_insert = format!("\n{}", indent_text);
241
242        // 4. Use InsertText action to insert the text
243        let mut insert_action = InsertText {
244            text: text_to_insert,
245        };
246        insert_action.apply(editor);
247    }
248}
249
250/// Deletes the selected text or the character before the cursor.
251///
252/// - If there is a non-empty selection, deletes the selection.
253/// - If there is no selection, deletes the previous character.
254/// - If the cursor is after indentation only, deletes the entire indentation.
255pub struct Delete;
256
257impl Action for Delete {
258    fn apply(&mut self, editor: &mut Editor) {
259        // 1. Extract current cursor and selection
260        let mut cursor = editor.get_cursor();
261        let mut selection = editor.get_selection();
262
263        // 2. Work with code
264        let code = editor.code_mut();
265        code.tx();
266        code.set_state_before(cursor, selection);
267
268        if let Some(sel) = &selection
269            && !sel.is_empty()
270        {
271            // Delete selection
272            let (start, end) = sel.sorted();
273            code.remove(start, end);
274            cursor = start;
275            selection = None;
276        } else if cursor > 0 {
277            // Delete single char or indentation
278            let (row, col) = code.point(cursor);
279            if code.is_only_indentation_before(row, col) {
280                let from = cursor - col;
281                code.remove(from, cursor);
282                cursor = from;
283            } else {
284                let prev_cursor = code.prev_grapheme_boundary(cursor);
285                code.remove(prev_cursor, cursor);
286                cursor = prev_cursor;
287            }
288        }
289
290        // 3. Commit changes and update editor
291        code.set_state_after(cursor, selection);
292        code.commit();
293
294        editor.set_cursor(cursor);
295        editor.set_selection(selection);
296        editor.reset_highlight_cache();
297    }
298}
299
300pub struct ToggleComment;
301
302impl Action for ToggleComment {
303    /// The `ToggleComment` action toggles line comments at the start of the selected lines.
304    ///
305    /// If all lines in the selection already start with the language's comment string
306    /// (e.g., "//" for Rust), this action removes the comment string from each affected line.
307    /// Otherwise, it prepends the comment string to the beginning of each line in the selection.
308    ///
309    /// If there is no selection, the action is applied to the line under the cursor.
310    fn apply(&mut self, editor: &mut Editor) {
311        // 1. Extract current cursor and selection
312        let mut cursor = editor.get_cursor();
313        let mut selection = editor.get_selection();
314        let selection_anchor = editor.selection_anchor();
315
316        // 2. Work with code
317        let code = editor.code_mut();
318
319        code.tx();
320        code.set_state_before(cursor, selection);
321
322        let comment_text = code.comment();
323        let comment_len = comment_text.chars().count();
324
325        // 3. Determine lines to modify
326        let lines_to_handle = if let Some(sel) = &selection
327            && !sel.is_empty()
328        {
329            let (start, end) = sel.sorted();
330            let (start_row, _) = code.point(start);
331            let (end_row, _) = code.point(end);
332            (start_row..=end_row).collect::<Vec<_>>()
333        } else {
334            let (row, _) = code.point(cursor);
335            vec![row]
336        };
337
338        // 4. Check if all lines already have the comment
339        let all_have_comment = lines_to_handle.iter().all(|&line_idx| {
340            let line_start = code.line_to_char(line_idx);
341            let line_len = code.line_len(line_idx);
342            line_start + comment_len <= line_start + line_len
343                && code.slice(line_start, line_start + comment_len) == comment_text
344        });
345
346        // 5. Apply changes (add or remove comment)
347        let mut comments_added = 0usize;
348        let mut comments_removed = 0usize;
349
350        for &line_idx in lines_to_handle.iter().rev() {
351            let start = code.line_to_char(line_idx);
352            if all_have_comment {
353                // Remove comment if present at start
354                let slice = code.slice(start, start + comment_len);
355                if slice == comment_text {
356                    code.remove(start, start + comment_len);
357                    comments_removed += 1;
358                }
359            } else {
360                // Add comment at start
361                code.insert(start, &comment_text);
362                comments_added += 1;
363            }
364        }
365
366        // 6. Update cursor and selection
367        if let Some(sel) = &selection
368            && !sel.is_empty()
369        {
370            let (smin, _) = sel.sorted();
371            let mut anchor = selection_anchor;
372            let is_forward = anchor == smin;
373
374            if is_forward {
375                if !all_have_comment {
376                    cursor += comment_len * comments_added;
377                    anchor += comment_len;
378                } else {
379                    cursor = cursor.saturating_sub(comment_len * comments_removed);
380                    anchor = anchor.saturating_sub(comment_len);
381                }
382            } else {
383                if !all_have_comment {
384                    cursor += comment_len;
385                    anchor += comment_len * comments_added;
386                } else {
387                    cursor = cursor.saturating_sub(comment_len);
388                    anchor = anchor.saturating_sub(comment_len * comments_removed);
389                }
390            }
391
392            selection = Some(Selection::from_anchor_and_cursor(anchor, cursor));
393        } else {
394            if !all_have_comment {
395                cursor += comment_len;
396            } else {
397                cursor = cursor.saturating_sub(comment_len);
398            }
399        }
400
401        // 7. Commit changes
402        code.set_state_after(cursor, selection);
403        code.commit();
404
405        // 8. Return changed values to the editor
406        editor.set_cursor(cursor);
407        editor.set_selection(selection);
408        editor.reset_highlight_cache();
409    }
410}
411
412/// Inserts indentation at the beginning of the current line or selected lines.
413///
414/// - If there is a selection, inserts indentation at the start of each selected line.
415/// - If there is no selection, inserts indentation at the current line.
416/// - Updates cursor and selection accordingly.
417pub struct Indent;
418
419impl Action for Indent {
420    fn apply(&mut self, editor: &mut Editor) {
421        // 1. Extract current cursor and selection
422        let mut cursor = editor.get_cursor();
423        let mut selection = editor.get_selection();
424        let selection_anchor = editor.selection_anchor();
425
426        // 2. Work with code
427        let code = editor.code_mut();
428        code.tx();
429        code.set_state_before(cursor, selection);
430
431        let indent_text = code.indent();
432
433        // 3. Determine lines to handle
434        let lines_to_handle = if let Some(sel) = &selection
435            && !sel.is_empty()
436        {
437            let (start, end) = sel.sorted();
438            let (start_row, _) = code.point(start);
439            let (end_row, _) = code.point(end);
440            (start_row..=end_row).collect::<Vec<_>>()
441        } else {
442            let (row, _) = code.point(cursor);
443            vec![row]
444        };
445
446        // 4. Insert indentation for each line (reverse to not shift indices)
447        let mut indents_added = 0;
448        for &line_idx in lines_to_handle.iter().rev() {
449            let line_start = code.line_to_char(line_idx);
450            code.insert(line_start, &indent_text);
451            indents_added += 1;
452        }
453
454        // 5. Update cursor and selection
455        if let Some(sel) = &selection
456            && !sel.is_empty()
457        {
458            let (smin, _) = sel.sorted();
459            let mut anchor = selection_anchor;
460            let is_forward = anchor == smin;
461
462            if is_forward {
463                cursor += indent_text.len() * indents_added;
464                anchor += indent_text.len();
465            } else {
466                cursor += indent_text.len();
467                anchor += indent_text.len() * indents_added;
468            }
469
470            selection = Some(Selection::from_anchor_and_cursor(anchor, cursor));
471        } else {
472            cursor += indent_text.len();
473        }
474
475        // 6. Commit changes
476        code.set_state_after(cursor, selection);
477        code.commit();
478
479        editor.set_cursor(cursor);
480        editor.set_selection(selection);
481        editor.reset_highlight_cache();
482    }
483}
484
485/// Removes one indentation level from the start of the current line or selected lines.
486///
487/// - If there is a selection, removes indentation from each selected line.
488/// - If there is no selection, removes indentation from the current line.
489/// - Updates cursor and selection accordingly.
490pub struct UnIndent;
491
492impl Action for UnIndent {
493    fn apply(&mut self, editor: &mut Editor) {
494        // 1. Extract current cursor and selection
495        let mut cursor = editor.get_cursor();
496        let mut selection = editor.get_selection();
497        let selection_anchor = editor.selection_anchor();
498
499        // 2. Work with code
500        let code = editor.code_mut();
501        code.tx();
502        code.set_state_before(cursor, selection);
503
504        let indent_text = code.indent();
505        let indent_len = indent_text.chars().count();
506
507        // 3. Determine lines to handle
508        let lines_to_handle = if let Some(sel) = &selection
509            && !sel.is_empty()
510        {
511            let (start, end) = sel.sorted();
512            let (start_row, _) = code.point(start);
513            let (end_row, _) = code.point(end);
514            (start_row..=end_row).collect::<Vec<_>>()
515        } else {
516            let (row, _) = code.point(cursor);
517            vec![row]
518        };
519
520        // 4. Remove indentation from each line
521        let mut lines_untabbed = 0;
522        for &line_idx in lines_to_handle.iter().rev() {
523            if let Some(indent_cols) = code.find_indent_at_line_start(line_idx) {
524                let remove_count = indent_cols.min(indent_len);
525                if remove_count > 0 {
526                    let line_start = code.line_to_char(line_idx);
527                    code.remove(line_start, line_start + remove_count);
528                    lines_untabbed += 1;
529                }
530            }
531        }
532
533        // 5. Update cursor and selection
534        if let Some(sel) = &selection
535            && !sel.is_empty()
536        {
537            let (smin, _) = sel.sorted();
538            let mut anchor = selection_anchor;
539            let is_forward = anchor == smin;
540
541            if is_forward {
542                cursor = cursor.saturating_sub(indent_len * lines_untabbed);
543                anchor = anchor.saturating_sub(indent_len);
544            } else {
545                cursor = cursor.saturating_sub(indent_len);
546                anchor = anchor.saturating_sub(indent_len * lines_untabbed);
547            }
548
549            selection = Some(Selection::from_anchor_and_cursor(anchor, cursor));
550        } else {
551            cursor = cursor.saturating_sub(indent_len * lines_untabbed);
552        }
553
554        // 6. Commit changes
555        code.set_state_after(cursor, selection);
556        code.commit();
557
558        editor.set_cursor(cursor);
559        editor.set_selection(selection);
560        editor.reset_highlight_cache();
561    }
562}
563
564/// Selects the entire text in the editor.
565pub struct SelectAll;
566
567impl Action for SelectAll {
568    fn apply(&mut self, editor: &mut Editor) {
569        // Set selection from start to end of the document
570        let from = 0;
571        let code = editor.code_mut();
572        let to = code.len_chars();
573        let sel = Selection::new(from, to);
574        editor.set_selection(Some(sel));
575    }
576}
577
578/// Duplicates the selected text or the current line if no selection exists.
579///
580/// If there is a selection, it duplicates the selected text immediately after it.
581/// If there is no selection, it duplicates the entire line under the cursor,
582/// preserving the cursor's relative column position.
583pub struct Duplicate;
584
585impl Action for Duplicate {
586    fn apply(&mut self, editor: &mut Editor) {
587        // 1. Extract current cursor and selection
588        let mut cursor = editor.get_cursor();
589        let mut selection = editor.get_selection();
590        let code = editor.code_mut();
591
592        code.tx();
593        code.set_state_before(cursor, selection);
594
595        if let Some(sel) = &selection {
596            // Duplicate selected text
597            let text = code.slice(sel.start, sel.end);
598            let insert_pos = sel.end;
599            code.insert(insert_pos, &text);
600            cursor = insert_pos + text.chars().count();
601            selection = None;
602        } else {
603            // Duplicate the current line
604            let (line_start, line_end) = code.line_boundaries(cursor);
605            let line_text = code.slice(line_start, line_end);
606            let column = cursor - line_start;
607
608            let insert_pos = line_end;
609            let to_insert = if line_text.ends_with('\n') {
610                line_text.clone()
611            } else {
612                format!("{}\n", line_text)
613            };
614            code.insert(insert_pos, &to_insert);
615
616            // Keep cursor on the same relative column in the new line
617            let new_line_len = to_insert.trim_end_matches('\n').chars().count();
618            let new_column = column.min(new_line_len);
619            cursor = insert_pos + new_column;
620        }
621
622        code.set_state_after(cursor, selection);
623        code.commit();
624
625        // Update editor state
626        editor.set_cursor(cursor);
627        editor.set_selection(selection);
628        editor.reset_highlight_cache();
629    }
630}
631
632/// Deletes the entire line under the cursor.
633pub struct DeleteLine;
634
635impl Action for DeleteLine {
636    fn apply(&mut self, editor: &mut Editor) {
637        // 1. Extract current cursor and selection
638        let mut cursor = editor.get_cursor();
639        let mut selection = editor.get_selection();
640        let code = editor.code_mut();
641
642        // 2. Compute line boundaries
643        let (start, end) = code.line_boundaries(cursor);
644
645        // Do nothing if the line is empty and at the end of file
646        if start == end && start == code.len() {
647            return;
648        }
649
650        // 3. Remove the line
651        code.tx();
652        code.set_state_before(cursor, selection);
653        code.remove(start, end);
654        code.set_state_after(start, None);
655        code.commit();
656
657        // 4. Update editor state
658        cursor = start;
659        selection = None;
660        editor.set_cursor(cursor);
661        editor.set_selection(selection);
662        editor.reset_highlight_cache();
663    }
664}
665
666/// Cuts the current selection: copies it to the clipboard and removes it from the editor.
667pub struct Cut;
668
669impl Action for Cut {
670    fn apply(&mut self, editor: &mut Editor) {
671        // 1. Extract current cursor and selection
672        let mut cursor = editor.get_cursor();
673        let mut selection = editor.get_selection();
674
675        let sel = match &selection {
676            Some(sel) if !sel.is_empty() => sel.clone(),
677            _ => return, // nothing to cut
678        };
679
680        // 2. Copy to clipboard first, before borrowing code mutably
681        let text = editor.code_ref().slice(sel.start, sel.end);
682        let _ = editor.set_clipboard(&text);
683
684        // 3. Now borrow code mutably
685        let code = editor.code_mut();
686        code.tx();
687        code.set_state_before(cursor, selection);
688        code.remove(sel.start, sel.end);
689        code.set_state_after(sel.start, None);
690        code.commit();
691
692        // 4. Update editor state
693        cursor = sel.start;
694        selection = None;
695        editor.set_cursor(cursor);
696        editor.set_selection(selection);
697        editor.reset_highlight_cache();
698    }
699}
700
701/// Copies the selected text to the clipboard.
702///
703/// Does nothing if there is no active selection.
704pub struct Copy;
705
706impl Action for Copy {
707    fn apply(&mut self, editor: &mut Editor) {
708        // 1. Extract current selection
709        let selection = editor.get_selection();
710
711        // 2. Return early if no selection
712        let Some(sel) = selection else { return };
713        if sel.is_empty() {
714            return;
715        }
716
717        // 3. Get text and copy to clipboard
718        let text = editor.code_ref().slice(sel.start, sel.end);
719        let _ = editor.set_clipboard(&text);
720    }
721}
722
723/// Pastes text from the clipboard at the current cursor position.
724///
725/// If a selection exists, it will be replaced by the pasted text.
726/// The pasted text is adjusted using language-specific indentation rules.
727pub struct Paste;
728
729impl Action for Paste {
730    fn apply(&mut self, editor: &mut Editor) {
731        // 1. Get clipboard contents
732        let Ok(text) = editor.get_clipboard() else {
733            return;
734        };
735        if text.is_empty() {
736            return;
737        }
738
739        // 2. Extract current cursor and selection
740        let mut cursor = editor.get_cursor();
741        let mut selection = editor.get_selection();
742        let code = editor.code_mut();
743
744        // 3. Prepare transaction
745        code.tx();
746        code.set_state_before(cursor, selection);
747
748        // 4. Remove selection if present
749        if let Some(sel) = &selection {
750            if !sel.is_empty() {
751                let (start, end) = sel.sorted();
752                code.remove(start, end);
753                cursor = start;
754                selection = None;
755            }
756        }
757
758        // 5. Perform paste with smart indentation
759        let inserted = code.smart_paste(cursor, &text);
760        cursor += inserted;
761
762        // 6. Finalize transaction
763        code.set_state_after(cursor, selection);
764        code.commit();
765
766        // 7. Update editor state
767        editor.set_cursor(cursor);
768        editor.set_selection(selection);
769        editor.reset_highlight_cache();
770    }
771}
772
773/// Undoes the last edit in the code buffer.
774///
775/// Restores both the cursor position and selection state
776/// from the saved editor snapshot if available.
777pub struct Undo;
778
779impl Action for Undo {
780    fn apply(&mut self, editor: &mut Editor) {
781        // 1. Get mutable access to code
782        let code = editor.code_mut();
783
784        // 2. Try to undo
785        let edits = code.undo();
786        editor.reset_highlight_cache();
787
788        // 3. If nothing to undo, return
789        let Some(batch) = edits else { return };
790
791        // 4. Restore cursor and selection from saved state if possible
792        if let Some(before) = batch.state_before {
793            editor.set_cursor(before.offset);
794            editor.set_selection(before.selection);
795            return;
796        }
797
798        // 5. Otherwise infer cursor position from edits
799        for edit in batch.edits.iter().rev() {
800            match edit.operation {
801                Operation::Insert => {
802                    editor.set_cursor(edit.start);
803                }
804                Operation::Remove => {
805                    editor.set_cursor(edit.start + edit.text.chars().count());
806                }
807            }
808        }
809    }
810}
811
812/// Redoes the last undone edit in the code buffer.
813///
814/// Restores both the cursor position and selection state
815/// from the saved editor snapshot if available.
816pub struct Redo;
817
818impl Action for Redo {
819    fn apply(&mut self, editor: &mut Editor) {
820        // 1. Get mutable access to code
821        let code = editor.code_mut();
822
823        // 2. Try to redo
824        let edits = code.redo();
825        editor.reset_highlight_cache();
826
827        // 3. If nothing to redo, return
828        let Some(batch) = edits else { return };
829
830        // 4. Restore cursor and selection from saved state if possible
831        if let Some(after) = batch.state_after {
832            editor.set_cursor(after.offset);
833            editor.set_selection(after.selection);
834            return;
835        }
836
837        // 5. Otherwise infer cursor position from edits
838        for edit in batch.edits {
839            match edit.operation {
840                Operation::Insert => {
841                    editor.set_cursor(edit.start + edit.text.chars().count());
842                }
843                Operation::Remove => {
844                    editor.set_cursor(edit.start);
845                }
846            }
847        }
848    }
849}