ratatui-code-editor 0.0.5

ratatui-code-editor is A code editor widget for ratatui, built with syntax highlighting powered by Tree-sitter.
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
use crate::code::Operation;
use crate::editor::Editor;
use crate::selection::Selection;

pub trait Action {
    fn apply(&mut self, editor: &mut Editor);
}

/// Moves the cursor one character to the right.
///
/// If `shift` is true, the selection is extended to the new cursor position.
/// If `shift` is false and there is an active selection, the cursor jumps
/// to the end of the selection and the selection is cleared.
/// Otherwise, the cursor moves one position to the right.
pub struct MoveRight {
    pub shift: bool,
}

impl Action for MoveRight {
    fn apply(&mut self, editor: &mut Editor) {
        let cursor = editor.get_cursor();

        if !self.shift {
            if let Some(sel) = editor.get_selection() {
                if !sel.is_empty() {
                    let (_, end) = sel.sorted();
                    editor.set_cursor(end);
                    editor.clamp_cursor_to_focus_rows();
                    editor.clear_selection();
                    return;
                }
            }
        }

        if cursor < editor.code_ref().len() {
            let code = editor.code_ref();
            let mut new_cursor = code.next_grapheme_boundary(cursor);
            let new_line = code.char_to_line(new_cursor);
            if !editor.line_visible(new_line) {
                if let Some(next_line) = editor.next_line(new_line) {
                    new_cursor = code.line_to_char(next_line);
                }
            }
            if self.shift {
                editor.extend_selection(new_cursor);
            } else {
                editor.clear_selection();
            }
            editor.set_cursor(new_cursor);
            editor.clamp_cursor_to_focus_rows();
        }
    }
}

/// Moves the cursor one character to the left.
///
/// If `shift` is true, the selection is extended to the new cursor position.
/// If `shift` is false and there is an active selection, the cursor jumps
/// to the start of the selection and the selection is cleared.
/// Otherwise, the cursor moves one position to the left.
pub struct MoveLeft {
    pub shift: bool,
}

impl Action for MoveLeft {
    fn apply(&mut self, editor: &mut Editor) {
        let cursor = editor.get_cursor();

        if !self.shift {
            if let Some(sel) = editor.get_selection() {
                if !sel.is_empty() {
                    let (start, _) = sel.sorted();
                    editor.set_cursor(start);
                    editor.clamp_cursor_to_focus_rows();
                    editor.clear_selection();
                    return;
                }
            }
        }

        if cursor > 0 {
            let code = editor.code_ref();
            let mut new_cursor = code.prev_grapheme_boundary(cursor);
            let new_line = code.char_to_line(new_cursor);
            if !editor.line_visible(new_line) {
                if let Some(prev_line) = editor.prev_line(new_line) {
                    new_cursor =
                        code.line_to_char(prev_line) + code.line_len(prev_line).saturating_sub(1);
                }
            }
            if self.shift {
                editor.extend_selection(new_cursor);
            } else {
                editor.clear_selection();
            }
            editor.set_cursor(new_cursor);
            editor.clamp_cursor_to_focus_rows();
        }
    }
}

/// Moves the cursor one line up.
///
/// If the previous line is shorter, the cursor is placed at the end of that line.
/// If `shift` is true, the selection is extended to the new cursor position.
/// If `shift` is false, the selection is cleared.
pub struct MoveUp {
    pub shift: bool,
}

impl Action for MoveUp {
    fn apply(&mut self, editor: &mut Editor) {
        let cursor = editor.get_cursor();
        let code = editor.code_ref();
        let (row, col) = code.point(cursor);

        let Some(prev_row) = editor.prev_line(row) else {
            return;
        };

        let current_visual_col = code.char_col_to_visual(row, col);
        let prev_start = code.line_to_char(prev_row);
        let prev_len = code.line_len(prev_row);
        let new_col = code
            .visual_to_char_col(prev_row, current_visual_col)
            .min(prev_len);
        let new_cursor = prev_start + new_col;

        // Update selection or clear it
        if self.shift {
            editor.extend_selection(new_cursor);
        } else {
            editor.clear_selection();
        }

        // Set the new cursor position
        editor.set_cursor(new_cursor);
        editor.clamp_cursor_to_focus_rows();
    }
}

/// Moves the cursor one line down.
///
/// If the next line is shorter, the cursor is placed at the end of that line.
/// If `shift` is true, the selection is extended to the new cursor position.
/// If `shift` is false, the selection is cleared.
///
pub struct MoveDown {
    pub shift: bool,
}

impl Action for MoveDown {
    fn apply(&mut self, editor: &mut Editor) {
        let cursor = editor.get_cursor();
        let code = editor.code_ref();
        let (row, col) = code.point(cursor);
        let Some(next_row) = editor.next_line(row) else {
            return;
        };

        let current_visual_col = code.char_col_to_visual(row, col);
        let next_start = code.line_to_char(next_row);
        let next_len = code.line_len(next_row);
        let new_col = code
            .visual_to_char_col(next_row, current_visual_col)
            .min(next_len);
        let new_cursor = next_start + new_col;

        // Update selection or clear it
        if self.shift {
            editor.extend_selection(new_cursor);
        } else {
            editor.clear_selection();
        }

        // Set the new cursor position
        editor.set_cursor(new_cursor);
        editor.clamp_cursor_to_focus_rows();
    }
}

/// Inserts arbitrary text at the cursor, replacing the selection if any.
pub struct InsertText {
    pub text: String,
}

impl Action for InsertText {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Extract current cursor and selection
        let mut cursor = editor.get_cursor();
        let mut selection = editor.get_selection();

        // 2. Work with code
        let code = editor.code_mut();
        code.tx();
        code.set_state_before(cursor, selection);

        // 3. Remove selection if present
        if let Some(sel) = &selection {
            if !sel.is_empty() {
                let (start, end) = sel.sorted();
                code.remove(start, end);
                cursor = start;
            }
        }
        selection = None;

        // 4. Insert the text at the cursor
        code.insert(cursor, &self.text);
        cursor += self.text.chars().count();

        // 5. Update editor state
        code.set_state_after(cursor, selection);
        code.commit();

        editor.set_cursor(cursor);
        editor.set_selection(selection);
        editor.reset_highlight_cache();
    }
}

/// Inserts a newline at the cursor with automatic indentation.
///
/// The indentation is computed based on the current line and column.
/// Delegates the actual insertion to `InsertText`.
pub struct InsertNewline;

impl Action for InsertNewline {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Get current cursor position
        let cursor = editor.get_cursor();
        let code = editor.code_mut();
        let (row, col) = code.point(cursor);

        // 2. Compute indentation for the new line
        let indent_level = code.indentation_level(row, col);
        let indent_text = code.indent().repeat(indent_level);

        // 3. Prepare the text to insert
        let text_to_insert = format!("\n{}", indent_text);

        // 4. Use InsertText action to insert the text
        let mut insert_action = InsertText {
            text: text_to_insert,
        };
        insert_action.apply(editor);
    }
}

/// Deletes the selected text or the character before the cursor.
///
/// - If there is a non-empty selection, deletes the selection.
/// - If there is no selection, deletes the previous character.
/// - If the cursor is after indentation only, deletes the entire indentation.
pub struct Delete;

impl Action for Delete {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Extract current cursor and selection
        let mut cursor = editor.get_cursor();
        let mut selection = editor.get_selection();

        // 2. Work with code
        let code = editor.code_mut();
        code.tx();
        code.set_state_before(cursor, selection);

        if let Some(sel) = &selection
            && !sel.is_empty()
        {
            // Delete selection
            let (start, end) = sel.sorted();
            code.remove(start, end);
            cursor = start;
            selection = None;
        } else if cursor > 0 {
            // Delete single char or indentation
            let (row, col) = code.point(cursor);
            if code.is_only_indentation_before(row, col) {
                let from = cursor - col;
                code.remove(from, cursor);
                cursor = from;
            } else {
                let prev_cursor = code.prev_grapheme_boundary(cursor);
                code.remove(prev_cursor, cursor);
                cursor = prev_cursor;
            }
        }

        // 3. Commit changes and update editor
        code.set_state_after(cursor, selection);
        code.commit();

        editor.set_cursor(cursor);
        editor.set_selection(selection);
        editor.reset_highlight_cache();
    }
}

pub struct ToggleComment;

impl Action for ToggleComment {
    /// The `ToggleComment` action toggles line comments at the start of the selected lines.
    ///
    /// If all lines in the selection already start with the language's comment string
    /// (e.g., "//" for Rust), this action removes the comment string from each affected line.
    /// Otherwise, it prepends the comment string to the beginning of each line in the selection.
    ///
    /// If there is no selection, the action is applied to the line under the cursor.
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Extract current cursor and selection
        let mut cursor = editor.get_cursor();
        let mut selection = editor.get_selection();
        let selection_anchor = editor.selection_anchor();

        // 2. Work with code
        let code = editor.code_mut();

        code.tx();
        code.set_state_before(cursor, selection);

        let comment_text = code.comment();
        let comment_len = comment_text.chars().count();

        // 3. Determine lines to modify
        let lines_to_handle = if let Some(sel) = &selection
            && !sel.is_empty()
        {
            let (start, end) = sel.sorted();
            let (start_row, _) = code.point(start);
            let (end_row, _) = code.point(end);
            (start_row..=end_row).collect::<Vec<_>>()
        } else {
            let (row, _) = code.point(cursor);
            vec![row]
        };

        // 4. Check if all lines already have the comment
        let all_have_comment = lines_to_handle.iter().all(|&line_idx| {
            let line_start = code.line_to_char(line_idx);
            let line_len = code.line_len(line_idx);
            line_start + comment_len <= line_start + line_len
                && code.slice(line_start, line_start + comment_len) == comment_text
        });

        // 5. Apply changes (add or remove comment)
        let mut comments_added = 0usize;
        let mut comments_removed = 0usize;

        for &line_idx in lines_to_handle.iter().rev() {
            let start = code.line_to_char(line_idx);
            if all_have_comment {
                // Remove comment if present at start
                let slice = code.slice(start, start + comment_len);
                if slice == comment_text {
                    code.remove(start, start + comment_len);
                    comments_removed += 1;
                }
            } else {
                // Add comment at start
                code.insert(start, &comment_text);
                comments_added += 1;
            }
        }

        // 6. Update cursor and selection
        if let Some(sel) = &selection
            && !sel.is_empty()
        {
            let (smin, _) = sel.sorted();
            let mut anchor = selection_anchor;
            let is_forward = anchor == smin;

            if is_forward {
                if !all_have_comment {
                    cursor += comment_len * comments_added;
                    anchor += comment_len;
                } else {
                    cursor = cursor.saturating_sub(comment_len * comments_removed);
                    anchor = anchor.saturating_sub(comment_len);
                }
            } else {
                if !all_have_comment {
                    cursor += comment_len;
                    anchor += comment_len * comments_added;
                } else {
                    cursor = cursor.saturating_sub(comment_len);
                    anchor = anchor.saturating_sub(comment_len * comments_removed);
                }
            }

            selection = Some(Selection::from_anchor_and_cursor(anchor, cursor));
        } else {
            if !all_have_comment {
                cursor += comment_len;
            } else {
                cursor = cursor.saturating_sub(comment_len);
            }
        }

        // 7. Commit changes
        code.set_state_after(cursor, selection);
        code.commit();

        // 8. Return changed values to the editor
        editor.set_cursor(cursor);
        editor.set_selection(selection);
        editor.reset_highlight_cache();
    }
}

/// Inserts indentation at the beginning of the current line or selected lines.
///
/// - If there is a selection, inserts indentation at the start of each selected line.
/// - If there is no selection, inserts indentation at the current line.
/// - Updates cursor and selection accordingly.
pub struct Indent;

impl Action for Indent {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Extract current cursor and selection
        let mut cursor = editor.get_cursor();
        let mut selection = editor.get_selection();
        let selection_anchor = editor.selection_anchor();

        // 2. Work with code
        let code = editor.code_mut();
        code.tx();
        code.set_state_before(cursor, selection);

        let indent_text = code.indent();

        // 3. Determine lines to handle
        let lines_to_handle = if let Some(sel) = &selection
            && !sel.is_empty()
        {
            let (start, end) = sel.sorted();
            let (start_row, _) = code.point(start);
            let (end_row, _) = code.point(end);
            (start_row..=end_row).collect::<Vec<_>>()
        } else {
            let (row, _) = code.point(cursor);
            vec![row]
        };

        // 4. Insert indentation for each line (reverse to not shift indices)
        let mut indents_added = 0;
        for &line_idx in lines_to_handle.iter().rev() {
            let line_start = code.line_to_char(line_idx);
            code.insert(line_start, &indent_text);
            indents_added += 1;
        }

        // 5. Update cursor and selection
        if let Some(sel) = &selection
            && !sel.is_empty()
        {
            let (smin, _) = sel.sorted();
            let mut anchor = selection_anchor;
            let is_forward = anchor == smin;

            if is_forward {
                cursor += indent_text.len() * indents_added;
                anchor += indent_text.len();
            } else {
                cursor += indent_text.len();
                anchor += indent_text.len() * indents_added;
            }

            selection = Some(Selection::from_anchor_and_cursor(anchor, cursor));
        } else {
            cursor += indent_text.len();
        }

        // 6. Commit changes
        code.set_state_after(cursor, selection);
        code.commit();

        editor.set_cursor(cursor);
        editor.set_selection(selection);
        editor.reset_highlight_cache();
    }
}

/// Removes one indentation level from the start of the current line or selected lines.
///
/// - If there is a selection, removes indentation from each selected line.
/// - If there is no selection, removes indentation from the current line.
/// - Updates cursor and selection accordingly.
pub struct UnIndent;

impl Action for UnIndent {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Extract current cursor and selection
        let mut cursor = editor.get_cursor();
        let mut selection = editor.get_selection();
        let selection_anchor = editor.selection_anchor();

        // 2. Work with code
        let code = editor.code_mut();
        code.tx();
        code.set_state_before(cursor, selection);

        let indent_text = code.indent();
        let indent_len = indent_text.chars().count();

        // 3. Determine lines to handle
        let lines_to_handle = if let Some(sel) = &selection
            && !sel.is_empty()
        {
            let (start, end) = sel.sorted();
            let (start_row, _) = code.point(start);
            let (end_row, _) = code.point(end);
            (start_row..=end_row).collect::<Vec<_>>()
        } else {
            let (row, _) = code.point(cursor);
            vec![row]
        };

        // 4. Remove indentation from each line
        let mut lines_untabbed = 0;
        for &line_idx in lines_to_handle.iter().rev() {
            if let Some(indent_cols) = code.find_indent_at_line_start(line_idx) {
                let remove_count = indent_cols.min(indent_len);
                if remove_count > 0 {
                    let line_start = code.line_to_char(line_idx);
                    code.remove(line_start, line_start + remove_count);
                    lines_untabbed += 1;
                }
            }
        }

        // 5. Update cursor and selection
        if let Some(sel) = &selection
            && !sel.is_empty()
        {
            let (smin, _) = sel.sorted();
            let mut anchor = selection_anchor;
            let is_forward = anchor == smin;

            if is_forward {
                cursor = cursor.saturating_sub(indent_len * lines_untabbed);
                anchor = anchor.saturating_sub(indent_len);
            } else {
                cursor = cursor.saturating_sub(indent_len);
                anchor = anchor.saturating_sub(indent_len * lines_untabbed);
            }

            selection = Some(Selection::from_anchor_and_cursor(anchor, cursor));
        } else {
            cursor = cursor.saturating_sub(indent_len * lines_untabbed);
        }

        // 6. Commit changes
        code.set_state_after(cursor, selection);
        code.commit();

        editor.set_cursor(cursor);
        editor.set_selection(selection);
        editor.reset_highlight_cache();
    }
}

/// Selects the entire text in the editor.
pub struct SelectAll;

impl Action for SelectAll {
    fn apply(&mut self, editor: &mut Editor) {
        // Set selection from start to end of the document
        let from = 0;
        let code = editor.code_mut();
        let to = code.len_chars();
        let sel = Selection::new(from, to);
        editor.set_selection(Some(sel));
    }
}

/// Duplicates the selected text or the current line if no selection exists.
///
/// If there is a selection, it duplicates the selected text immediately after it.
/// If there is no selection, it duplicates the entire line under the cursor,
/// preserving the cursor's relative column position.
pub struct Duplicate;

impl Action for Duplicate {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Extract current cursor and selection
        let mut cursor = editor.get_cursor();
        let mut selection = editor.get_selection();
        let code = editor.code_mut();

        code.tx();
        code.set_state_before(cursor, selection);

        if let Some(sel) = &selection {
            // Duplicate selected text
            let text = code.slice(sel.start, sel.end);
            let insert_pos = sel.end;
            code.insert(insert_pos, &text);
            cursor = insert_pos + text.chars().count();
            selection = None;
        } else {
            // Duplicate the current line
            let (line_start, line_end) = code.line_boundaries(cursor);
            let line_text = code.slice(line_start, line_end);
            let column = cursor - line_start;

            let insert_pos = line_end;
            let to_insert = if line_text.ends_with('\n') {
                line_text.clone()
            } else {
                format!("{}\n", line_text)
            };
            code.insert(insert_pos, &to_insert);

            // Keep cursor on the same relative column in the new line
            let new_line_len = to_insert.trim_end_matches('\n').chars().count();
            let new_column = column.min(new_line_len);
            cursor = insert_pos + new_column;
        }

        code.set_state_after(cursor, selection);
        code.commit();

        // Update editor state
        editor.set_cursor(cursor);
        editor.set_selection(selection);
        editor.reset_highlight_cache();
    }
}

/// Deletes the entire line under the cursor.
pub struct DeleteLine;

impl Action for DeleteLine {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Extract current cursor and selection
        let mut cursor = editor.get_cursor();
        let mut selection = editor.get_selection();
        let code = editor.code_mut();

        // 2. Compute line boundaries
        let (start, end) = code.line_boundaries(cursor);

        // Do nothing if the line is empty and at the end of file
        if start == end && start == code.len() {
            return;
        }

        // 3. Remove the line
        code.tx();
        code.set_state_before(cursor, selection);
        code.remove(start, end);
        code.set_state_after(start, None);
        code.commit();

        // 4. Update editor state
        cursor = start;
        selection = None;
        editor.set_cursor(cursor);
        editor.set_selection(selection);
        editor.reset_highlight_cache();
    }
}

/// Cuts the current selection: copies it to the clipboard and removes it from the editor.
pub struct Cut;

impl Action for Cut {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Extract current cursor and selection
        let mut cursor = editor.get_cursor();
        let mut selection = editor.get_selection();

        let sel = match &selection {
            Some(sel) if !sel.is_empty() => sel.clone(),
            _ => return, // nothing to cut
        };

        // 2. Copy to clipboard first, before borrowing code mutably
        let text = editor.code_ref().slice(sel.start, sel.end);
        let _ = editor.set_clipboard(&text);

        // 3. Now borrow code mutably
        let code = editor.code_mut();
        code.tx();
        code.set_state_before(cursor, selection);
        code.remove(sel.start, sel.end);
        code.set_state_after(sel.start, None);
        code.commit();

        // 4. Update editor state
        cursor = sel.start;
        selection = None;
        editor.set_cursor(cursor);
        editor.set_selection(selection);
        editor.reset_highlight_cache();
    }
}

/// Copies the selected text to the clipboard.
///
/// Does nothing if there is no active selection.
pub struct Copy;

impl Action for Copy {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Extract current selection
        let selection = editor.get_selection();

        // 2. Return early if no selection
        let Some(sel) = selection else { return };
        if sel.is_empty() {
            return;
        }

        // 3. Get text and copy to clipboard
        let text = editor.code_ref().slice(sel.start, sel.end);
        let _ = editor.set_clipboard(&text);
    }
}

/// Pastes text from the clipboard at the current cursor position.
///
/// If a selection exists, it will be replaced by the pasted text.
/// The pasted text is adjusted using language-specific indentation rules.
pub struct Paste;

impl Action for Paste {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Get clipboard contents
        let Ok(text) = editor.get_clipboard() else {
            return;
        };
        if text.is_empty() {
            return;
        }

        // 2. Extract current cursor and selection
        let mut cursor = editor.get_cursor();
        let mut selection = editor.get_selection();
        let code = editor.code_mut();

        // 3. Prepare transaction
        code.tx();
        code.set_state_before(cursor, selection);

        // 4. Remove selection if present
        if let Some(sel) = &selection {
            if !sel.is_empty() {
                let (start, end) = sel.sorted();
                code.remove(start, end);
                cursor = start;
                selection = None;
            }
        }

        // 5. Perform paste with smart indentation
        let inserted = code.smart_paste(cursor, &text);
        cursor += inserted;

        // 6. Finalize transaction
        code.set_state_after(cursor, selection);
        code.commit();

        // 7. Update editor state
        editor.set_cursor(cursor);
        editor.set_selection(selection);
        editor.reset_highlight_cache();
    }
}

/// Undoes the last edit in the code buffer.
///
/// Restores both the cursor position and selection state
/// from the saved editor snapshot if available.
pub struct Undo;

impl Action for Undo {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Get mutable access to code
        let code = editor.code_mut();

        // 2. Try to undo
        let edits = code.undo();
        editor.reset_highlight_cache();

        // 3. If nothing to undo, return
        let Some(batch) = edits else { return };

        // 4. Restore cursor and selection from saved state if possible
        if let Some(before) = batch.state_before {
            editor.set_cursor(before.offset);
            editor.set_selection(before.selection);
            return;
        }

        // 5. Otherwise infer cursor position from edits
        for edit in batch.edits.iter().rev() {
            match edit.operation {
                Operation::Insert => {
                    editor.set_cursor(edit.start);
                }
                Operation::Remove => {
                    editor.set_cursor(edit.start + edit.text.chars().count());
                }
            }
        }
    }
}

/// Redoes the last undone edit in the code buffer.
///
/// Restores both the cursor position and selection state
/// from the saved editor snapshot if available.
pub struct Redo;

impl Action for Redo {
    fn apply(&mut self, editor: &mut Editor) {
        // 1. Get mutable access to code
        let code = editor.code_mut();

        // 2. Try to redo
        let edits = code.redo();
        editor.reset_highlight_cache();

        // 3. If nothing to redo, return
        let Some(batch) = edits else { return };

        // 4. Restore cursor and selection from saved state if possible
        if let Some(after) = batch.state_after {
            editor.set_cursor(after.offset);
            editor.set_selection(after.selection);
            return;
        }

        // 5. Otherwise infer cursor position from edits
        for edit in batch.edits {
            match edit.operation {
                Operation::Insert => {
                    editor.set_cursor(edit.start + edit.text.chars().count());
                }
                Operation::Remove => {
                    editor.set_cursor(edit.start);
                }
            }
        }
    }
}