mtk-rs 0.1.0-beta.4

Muse Toolkit
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
#[derive(Debug, Clone, PartialEq, Eq)]
struct EditSnapshot {
    text: String,
    cursor: usize,
    selection_anchor: Option<usize>,
}

/// A headless text editor abstraction that manages the state of a single-line or multi-line text input.
///
/// It handles UTF-8 safe cursor navigation, text selection via an anchor system, and text mutations
/// such as insertions and backspace/delete operations. It is completely decoupled from rendering.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Editor {
    /// The underlying text buffer.
    text: String,
    /// The current byte-index of the cursor within the text buffer.
    cursor: usize,
    /// The byte-index where a text selection began. If [None], no text is currently selected.
    /// When selecting text (e.g. holding Shift), this remains fixed while the `cursor` moves.
    selection_anchor: Option<usize>,
    /// Temporary text being composed by the OS Input Method Editor (IME).
    ime_preedit: Option<(String, Option<(usize, usize)>)>,
    /// Target column offset preserved when navigating vertically across lines of varying length.
    preferred_col: Option<usize>,
    /// Undo history stack.
    undo_stack: Vec<EditSnapshot>,
    /// Redo history stack.
    redo_stack: Vec<EditSnapshot>,
    /// Tracks if continuous typing is being grouped into a single undo step.
    in_typing_group: bool,
}

impl Default for Editor {
    fn default() -> Self {
        Self::new()
    }
}

impl Editor {
    /// Creates a new, empty `Editor` state.
    pub fn new() -> Self {
        Self {
            text: String::new(),
            cursor: 0,
            selection_anchor: None,
            ime_preedit: None,
            preferred_col: None,
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
            in_typing_group: false,
        }
    }

    /// Pushes an undo checkpoint before mutating state.
    fn push_undo_checkpoint(&mut self) {
        let snapshot = EditSnapshot {
            text: self.text.clone(),
            cursor: self.cursor,
            selection_anchor: self.selection_anchor,
        };
        if self.undo_stack.last() != Some(&snapshot) {
            self.undo_stack.push(snapshot);
            if self.undo_stack.len() > 128 {
                self.undo_stack.remove(0);
            }
            self.redo_stack.clear();
        }
    }

    /// Reverts the text buffer to the previous undo checkpoint.
    /// Returns `true` if an undo was performed, or `false` if the undo stack was empty.
    pub fn undo(&mut self) -> bool {
        self.in_typing_group = false;
        if let Some(prev) = self.undo_stack.pop() {
            let current = EditSnapshot {
                text: self.text.clone(),
                cursor: self.cursor,
                selection_anchor: self.selection_anchor,
            };
            self.redo_stack.push(current);
            self.text = prev.text;
            self.cursor = prev.cursor.min(self.text.len());
            self.selection_anchor = prev.selection_anchor.map(|a| a.min(self.text.len()));
            self.preferred_col = None;
            self.ime_preedit = None;
            true
        } else {
            false
        }
    }

    /// Reapplies a previously undone change from the redo stack.
    /// Returns `true` if a redo was performed, or `false` if the redo stack was empty.
    pub fn redo(&mut self) -> bool {
        self.in_typing_group = false;
        if let Some(next) = self.redo_stack.pop() {
            let current = EditSnapshot {
                text: self.text.clone(),
                cursor: self.cursor,
                selection_anchor: self.selection_anchor,
            };
            self.undo_stack.push(current);
            self.text = next.text;
            self.cursor = next.cursor.min(self.text.len());
            self.selection_anchor = next.selection_anchor.map(|a| a.min(self.text.len()));
            self.preferred_col = None;
            self.ime_preedit = None;
            true
        } else {
            false
        }
    }

    /// Returns `true` if there are undo steps available in the history stack.
    pub fn can_undo(&self) -> bool {
        !self.undo_stack.is_empty()
    }

    /// Returns `true` if there are redo steps available in the history stack.
    pub fn can_redo(&self) -> bool {
        !self.redo_stack.is_empty()
    }

    /// Clears both the undo and redo history stacks.
    pub fn clear_history(&mut self) {
        self.undo_stack.clear();
        self.redo_stack.clear();
        self.in_typing_group = false;
    }

    /// Explicitly breaks typing grouping and forces the next mutation to create a new undo step.
    pub fn push_checkpoint(&mut self) {
        self.push_undo_checkpoint();
        self.in_typing_group = false;
    }

    /// Returns the underlying text buffer without any temporary IME composition.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the text to be displayed on screen, which includes any active IME preedit text
    /// temporarily inserted at the cursor position.
    pub fn display_text(&self) -> String {
        if let Some((preedit_text, _)) = &self.ime_preedit {
            let mut display = String::with_capacity(self.text.len() + preedit_text.len());
            display.push_str(&self.text[..self.cursor]);
            display.push_str(preedit_text);
            display.push_str(&self.text[self.cursor..]);
            display
        } else {
            self.text.clone()
        }
    }

    /// Sets the active IME preedit state. If `text` is empty, the preedit state is cleared.
    /// If starting a new composition while text is selected, the selected text is deleted first.
    pub fn set_ime_preedit(&mut self, text: String, cursor_pos: Option<(usize, usize)>) {
        if text.is_empty() {
            self.ime_preedit = None;
        } else {
            if self.ime_preedit.is_none() {
                self.delete_selection();
            }
            self.ime_preedit = Some((text, cursor_pos));
        }
    }

    /// Commits the given text from the IME, inserting it into the buffer and clearing preedit.
    pub fn commit_ime(&mut self, text: &str) {
        self.ime_preedit = None;
        self.insert(text);
    }

    /// Returns the byte range `(start, end)` of the active IME preedit within the `display_text`.
    /// Returns `None` if there is no active IME composition.
    pub fn preedit_range(&self) -> Option<(usize, usize)> {
        self.ime_preedit
            .as_ref()
            .map(|(text, _)| (self.cursor, self.cursor + text.len()))
    }

    /// Returns the current byte-index position of the cursor relative to the underlying text buffer.
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// Returns the cursor index mapped to the `display_text` string, accounting for
    /// any active IME preedit and its internal cursor position.
    pub fn display_cursor(&self) -> usize {
        if let Some((text, cursor_pos)) = &self.ime_preedit {
            if let Some((start, end)) = cursor_pos {
                let offset = if *end > 0 {
                    *end
                } else if *start > 0 {
                    *start
                } else {
                    text.len()
                };
                self.cursor + offset.min(text.len())
            } else {
                self.cursor + text.len()
            }
        } else {
            self.cursor
        }
    }

    /// Returns the active text selection as a tuple of `(start, end)` byte indices.
    /// The `start` is guaranteed to be less than or equal to `end`.
    /// Returns `None` if no text is selected.
    pub fn selection(&self) -> Option<(usize, usize)> {
        self.selection_anchor.and_then(|anchor| {
            if anchor < self.cursor {
                Some((anchor, self.cursor))
            } else if anchor > self.cursor {
                Some((self.cursor, anchor))
            } else {
                None
            }
        })
    }

    /// Returns `true` if the text buffer is completely empty.
    pub fn is_empty(&self) -> bool {
        self.text.is_empty()
    }

    /// Replaces the entire text buffer with the given string, clearing any selection
    /// and moving the cursor to the end of the new text.
    pub fn set_text(&mut self, text: &str) {
        self.text = text.to_string();
        self.cursor = self.text.len();
        self.selection_anchor = None;
    }

    /// Sets the cursor position directly.
    pub fn set_cursor(&mut self, cursor: usize) {
        self.cursor = cursor.min(self.text.len());
    }

    /// Gets the selection anchor directly.
    pub fn selection_anchor(&self) -> Option<usize> {
        self.selection_anchor
    }

    /// Sets the selection anchor directly.
    pub fn set_selection_anchor(&mut self, anchor: Option<usize>) {
        if let Some(a) = anchor {
            self.selection_anchor = Some(a.min(self.text.len()));
        } else {
            self.selection_anchor = None;
        }
    }

    /// Inserts a string at the current cursor position.
    /// If there is an active selection, the selected text is deleted first.
    pub fn insert(&mut self, text: &str) {
        self.push_undo_checkpoint();
        self.in_typing_group = false;
        self.delete_selection();
        self.text.insert_str(self.cursor, text);
        self.cursor += text.len();
    }

    /// Inserts a single character at the current cursor position.
    /// If there is an active selection, the selected text is deleted first.
    pub fn insert_char(&mut self, ch: char) {
        if self.selection_anchor.is_some() {
            self.push_undo_checkpoint();
            self.in_typing_group = false;
            self.delete_selection();
        } else if ch.is_alphanumeric() {
            if !self.in_typing_group {
                self.push_undo_checkpoint();
                self.in_typing_group = true;
            }
        } else {
            self.push_undo_checkpoint();
            self.in_typing_group = false;
        }
        self.text.insert(self.cursor, ch);
        self.cursor += ch.len_utf8();
    }

    /// Deletes the character immediately preceding the cursor (Backspace).
    /// If there is an active selection, deletes the selection instead.
    pub fn delete_backward(&mut self) {
        self.push_undo_checkpoint();
        self.in_typing_group = false;
        if self.delete_selection() {
            return;
        }
        if self.cursor > 0 {
            let prev_char = self.text[..self.cursor].chars().next_back().unwrap();
            let len = prev_char.len_utf8();
            self.cursor -= len;
            self.text.remove(self.cursor);
        }
    }

    /// Deletes the character immediately following the cursor (Delete).
    /// If there is an active selection, deletes the selection instead.
    pub fn delete_forward(&mut self) {
        self.push_undo_checkpoint();
        self.in_typing_group = false;
        if self.delete_selection() {
            return;
        }
        if self.cursor < self.text.len() {
            self.text.remove(self.cursor);
        }
    }

    /// Deletes the word immediately preceding the cursor (Ctrl+Backspace).
    /// If there is an active selection, deletes the selection instead.
    pub fn delete_word_backward(&mut self) {
        self.push_undo_checkpoint();
        self.in_typing_group = false;
        if self.delete_selection() {
            return;
        }
        let end = self.cursor;
        self.step_word_left();
        let start = self.cursor;
        if start < end {
            self.text.replace_range(start..end, "");
        }
    }

    /// Deletes the word immediately following the cursor (Ctrl+Delete).
    /// If there is an active selection, deletes the selection instead.
    pub fn delete_word_forward(&mut self) {
        self.push_undo_checkpoint();
        self.in_typing_group = false;
        if self.delete_selection() {
            return;
        }
        let start = self.cursor;
        self.step_word_right();
        let end = self.cursor;
        if start < end {
            self.text.replace_range(start..end, "");
            self.cursor = start; // Cursor stays at start, text shrinks
        }
    }

    /// Deletes the currently selected text.
    /// Returns `true` if text was actually deleted, or `false` if there was no selection.
    pub fn delete_selection(&mut self) -> bool {
        if let Some((start, end)) = self.selection() {
            if start != end {
                self.text.replace_range(start..end, "");
                self.cursor = start;
                self.selection_anchor = None;
                return true;
            }
        }
        self.selection_anchor = None;
        false
    }

    /// Selects the entire text buffer.
    pub fn select_all(&mut self) {
        self.in_typing_group = false;
        self.selection_anchor = Some(0);
        self.cursor = self.text.len();
    }

    /// Moves the cursor one character to the left.
    /// If `shift` is true, extends the selection.
    /// If `shift` is false and there is a selection, jumps to the start of the selection.
    pub fn move_left(&mut self, shift: bool) {
        self.in_typing_group = false;
        if shift {
            if self.selection_anchor.is_none() {
                self.selection_anchor = Some(self.cursor);
            }
            self.step_left();
        } else {
            if let Some((start, end)) = self.selection() {
                if start != end {
                    self.cursor = start;
                    self.selection_anchor = None;
                    return;
                }
            }
            self.selection_anchor = None;
            self.step_left();
        }
    }

    /// Moves the cursor one character to the right.
    /// If `shift` is true, extends the selection.
    /// If `shift` is false and there is a selection, jumps to the end of the selection.
    pub fn move_right(&mut self, shift: bool) {
        if shift {
            if self.selection_anchor.is_none() {
                self.selection_anchor = Some(self.cursor);
            }
            self.step_right();
        } else {
            if let Some((start, end)) = self.selection() {
                if start != end {
                    self.cursor = end;
                    self.selection_anchor = None;
                    return;
                }
            }
            self.selection_anchor = None;
            self.step_right();
        }
    }

    /// Moves the cursor left by one word boundary.
    /// Skips over trailing non-alphanumeric characters, then skips all alphanumeric characters.
    pub fn move_word_left(&mut self, shift: bool) {
        if shift {
            if self.selection_anchor.is_none() {
                self.selection_anchor = Some(self.cursor);
            }
            self.step_word_left();
        } else {
            if let Some((start, end)) = self.selection() {
                if start != end {
                    self.cursor = start;
                    self.selection_anchor = None;
                    return;
                }
            }
            self.selection_anchor = None;
            self.step_word_left();
        }
    }

    /// Moves the cursor right by one word boundary.
    /// Skips all alphanumeric characters, then stops before the next alphanumeric character.
    pub fn move_word_right(&mut self, shift: bool) {
        if shift {
            if self.selection_anchor.is_none() {
                self.selection_anchor = Some(self.cursor);
            }
            self.step_word_right();
        } else {
            if let Some((start, end)) = self.selection() {
                if start != end {
                    self.cursor = end;
                    self.selection_anchor = None;
                    return;
                }
            }
            self.selection_anchor = None;
            self.step_word_right();
        }
    }

    /// Internal helper to step the cursor one character to the left.
    fn step_left(&mut self) {
        if self.cursor > 0 {
            let prev_char = self.text[..self.cursor].chars().next_back().unwrap();
            self.cursor -= prev_char.len_utf8();
        }
    }

    /// Internal helper to step the cursor one character to the right.
    fn step_right(&mut self) {
        if self.cursor < self.text.len() {
            let next_char = self.text[self.cursor..].chars().next().unwrap();
            self.cursor += next_char.len_utf8();
        }
    }

    /// Internal helper to step the cursor one word to the left.
    fn step_word_left(&mut self) {
        let mut chars = self.text[..self.cursor].chars().rev();
        let mut skipped_any = false;

        // Skip trailing non-alphanumeric chars
        while let Some(c) = chars.next() {
            if c.is_alphanumeric() {
                // Found alphanumeric, step back one to put it back conceptually
                // though we just break and handle below
                self.cursor -= c.len_utf8();
                break;
            } else {
                self.cursor -= c.len_utf8();
                skipped_any = true;
            }
        }

        // Now skip all alphanumeric chars
        for c in chars {
            if c.is_alphanumeric() {
                self.cursor -= c.len_utf8();
                skipped_any = true;
            } else {
                break;
            }
        }

        if !skipped_any {
            self.step_left(); // fallback
        }
    }

    /// Internal helper to step the cursor one word to the right.
    fn step_word_right(&mut self) {
        let mut chars = self.text[self.cursor..].chars();
        let mut skipped_any = false;

        // Skip alphanumeric chars first
        while let Some(c) = chars.next() {
            if c.is_alphanumeric() {
                self.cursor += c.len_utf8();
                skipped_any = true;
            } else {
                // If we found a non-alphanumeric, we stop and leave cursor before it
                // UNLESS we haven't skipped anything yet, in which case we skip non-alphanumeric
                if !skipped_any {
                    self.cursor += c.len_utf8();
                    skipped_any = true;
                    for next_c in chars.by_ref() {
                        if !next_c.is_alphanumeric() {
                            self.cursor += next_c.len_utf8();
                        } else {
                            break;
                        }
                    }
                }
                break;
            }
        }

        if !skipped_any {
            self.step_right(); // fallback
        }
    }

    /// Returns the total number of lines in the text buffer.
    pub fn line_count(&self) -> usize {
        self.text.split('\n').count()
    }

    /// Returns `(line_index, column_byte_offset)` for the current cursor position.
    pub fn current_line_info(&self) -> (usize, usize) {
        let mut line_idx = 0;
        let mut last_line_start = 0;

        for (i, b) in self.text[..self.cursor].bytes().enumerate() {
            if b == b'\n' {
                line_idx += 1;
                last_line_start = i + 1;
            }
        }

        let col_offset = self.cursor - last_line_start;
        (line_idx, col_offset)
    }

    /// Returns `(start_byte, end_byte)` for the specified line index (0-indexed).
    /// `end_byte` excludes the trailing newline `\n` if present.
    pub fn line_range(&self, line_idx: usize) -> Option<(usize, usize)> {
        let mut current_idx = 0;
        let mut start = 0;

        for (i, b) in self.text.bytes().enumerate() {
            if current_idx == line_idx {
                if b == b'\n' {
                    return Some((start, i));
                }
            } else if b == b'\n' {
                current_idx += 1;
                start = i + 1;
            }
        }

        if current_idx == line_idx {
            Some((start, self.text.len()))
        } else {
            None
        }
    }

    /// Inserts a newline `\n` at the current cursor position.
    pub fn insert_newline(&mut self) {
        self.preferred_col = None;
        self.insert_char('\n');
    }

    /// Moves the cursor to the beginning of the current line (Home key).
    pub fn move_line_start(&mut self, shift: bool) {
        self.preferred_col = None;
        let (cur_line, _) = self.current_line_info();
        if let Some((start, _)) = self.line_range(cur_line) {
            if shift {
                if self.selection_anchor.is_none() {
                    self.selection_anchor = Some(self.cursor);
                }
            } else {
                self.selection_anchor = None;
            }
            self.cursor = start;
        }
    }

    /// Moves the cursor to the end of the current line (End key).
    pub fn move_line_end(&mut self, shift: bool) {
        self.preferred_col = None;
        let (cur_line, _) = self.current_line_info();
        if let Some((_, end)) = self.line_range(cur_line) {
            if shift {
                if self.selection_anchor.is_none() {
                    self.selection_anchor = Some(self.cursor);
                }
            } else {
                self.selection_anchor = None;
            }
            self.cursor = end;
        }
    }

    /// Moves the cursor up to the previous line (Up Arrow key), preserving preferred column width.
    pub fn move_up(&mut self, shift: bool) {
        let (cur_line, cur_col) = self.current_line_info();
        if cur_line == 0 {
            return;
        }

        let pref_col = *self.preferred_col.get_or_insert(cur_col);

        if shift {
            if self.selection_anchor.is_none() {
                self.selection_anchor = Some(self.cursor);
            }
        } else {
            self.selection_anchor = None;
        }

        let target_line = cur_line - 1;
        if let Some((start, end)) = self.line_range(target_line) {
            let line_text = &self.text[start..end];
            let mut col_bytes = 0;
            for c in line_text.chars() {
                if col_bytes + c.len_utf8() > pref_col {
                    break;
                }
                col_bytes += c.len_utf8();
            }
            self.cursor = start + col_bytes;
        }
    }

    /// Moves the cursor down to the next line (Down Arrow key), preserving preferred column width.
    pub fn move_down(&mut self, shift: bool) {
        let (cur_line, cur_col) = self.current_line_info();
        let total_lines = self.line_count();
        if cur_line + 1 >= total_lines {
            return;
        }

        let pref_col = *self.preferred_col.get_or_insert(cur_col);

        if shift {
            if self.selection_anchor.is_none() {
                self.selection_anchor = Some(self.cursor);
            }
        } else {
            self.selection_anchor = None;
        }

        let target_line = cur_line + 1;
        if let Some((start, end)) = self.line_range(target_line) {
            let line_text = &self.text[start..end];
            let mut col_bytes = 0;
            for c in line_text.chars() {
                if col_bytes + c.len_utf8() > pref_col {
                    break;
                }
                col_bytes += c.len_utf8();
            }
            self.cursor = start + col_bytes;
        }
    }

    /// Moves the cursor to the very beginning of the text buffer.
    pub fn move_to_start(&mut self, shift: bool) {
        self.preferred_col = None;
        if shift {
            if self.selection_anchor.is_none() {
                self.selection_anchor = Some(self.cursor);
            }
        } else {
            self.selection_anchor = None;
        }
        self.cursor = 0;
    }

    /// Moves the cursor to the very end of the text buffer.
    pub fn move_to_end(&mut self, shift: bool) {
        self.preferred_col = None;
        if shift {
            if self.selection_anchor.is_none() {
                self.selection_anchor = Some(self.cursor);
            }
        } else {
            self.selection_anchor = None;
        }
        self.cursor = self.text.len();
    }
}

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

    #[test]
    fn test_editor_insert() {
        let mut editor = Editor::new();
        editor.insert("hello");
        assert_eq!(editor.text(), "hello");
        assert_eq!(editor.cursor(), 5);
    }

    #[test]
    fn test_editor_movements() {
        let mut editor = Editor::new();
        editor.insert("abc");
        editor.move_left(false);
        assert_eq!(editor.cursor(), 2); // after 'b'
        editor.move_left(false);
        assert_eq!(editor.cursor(), 1); // after 'a'
        editor.move_right(false);
        assert_eq!(editor.cursor(), 2);
    }

    #[test]
    fn test_editor_delete() {
        let mut editor = Editor::new();
        editor.insert("hello");
        editor.delete_backward();
        assert_eq!(editor.text(), "hell");
        editor.move_left(false); // cursor after 'l'
        editor.move_left(false); // cursor after 'e'
        editor.delete_forward(); // deletes 'l'
        assert_eq!(editor.text(), "hel");
    }

    #[test]
    fn test_editor_selection() {
        let mut editor = Editor::new();
        editor.insert("hello");
        editor.move_left(true);
        editor.move_left(true);
        assert_eq!(editor.selection(), Some((3, 5)));
        editor.delete_backward();
        assert_eq!(editor.text(), "hel");
        assert_eq!(editor.cursor(), 3);
        assert_eq!(editor.selection(), None);
    }

    #[test]
    fn test_unicode_boundaries() {
        let mut editor = Editor::new();
        editor.insert("🦀rust");
        assert_eq!(editor.cursor(), 8); // 🦀 is 4 bytes + rust is 4 bytes
        editor.move_to_start(false);
        assert_eq!(editor.cursor(), 0);
        editor.move_right(false);
        assert_eq!(editor.cursor(), 4);
        editor.delete_forward();
        assert_eq!(editor.text(), "🦀ust");
    }

    #[test]
    fn test_word_boundaries() {
        let mut editor = Editor::new();
        editor.insert("hello, world!");

        // cursor is at the end (13)
        editor.move_word_left(false);
        // jumps back over "world!" -> stops before "world!"
        assert_eq!(editor.cursor(), 7);

        editor.move_word_left(false);
        // jumps back over "hello, " -> stops before "hello"
        assert_eq!(editor.cursor(), 0);

        editor.move_word_right(false);
        // jumps over "hello", stops before ","
        assert_eq!(editor.cursor(), 5);

        editor.move_word_right(false);
        // jumps over ", ", stops before "world"
        assert_eq!(editor.cursor(), 7);

        editor.move_word_right(false);
        // jumps over "world", stops before "!"
        assert_eq!(editor.cursor(), 12);
    }

    #[test]
    fn test_editor_ime() {
        let mut editor = Editor::new();
        editor.insert("hello ");
        assert_eq!(editor.cursor(), 6);

        // Start composing "world"
        editor.set_ime_preedit("worl".to_string(), None);
        assert_eq!(editor.display_text(), "hello worl");
        assert_eq!(editor.preedit_range(), Some((6, 10)));
        assert_eq!(editor.text(), "hello "); // Underlying text unchanged
        assert_eq!(editor.cursor(), 6); // Cursor unchanged

        // Commit the composition
        editor.commit_ime("world");
        assert_eq!(editor.display_text(), "hello world");
        assert_eq!(editor.text(), "hello world");
        assert_eq!(editor.preedit_range(), None);
        assert_eq!(editor.cursor(), 11);
    }

    #[test]
    fn test_editor_selection_replacement() {
        let mut editor = Editor::new();
        editor.insert("hello world");
        editor.select_all(); // Selects 0..11
        assert_eq!(editor.selection(), Some((0, 11)));

        // Type 'a' over selection
        editor.insert("a");
        assert_eq!(editor.text(), "a");
        assert_eq!(editor.cursor(), 1);
        assert_eq!(editor.selection(), None);

        // Select 'a' and start IME composition
        editor.select_all();
        assert_eq!(editor.selection(), Some((0, 1)));
        editor.set_ime_preedit("ni".to_string(), None);
        assert_eq!(editor.text(), ""); // Selected text 'a' deleted immediately
        assert_eq!(editor.display_text(), "ni");
        assert_eq!(editor.selection(), None);
    }

    #[test]
    fn test_editor_multiline() {
        let mut editor = Editor::new();
        editor.insert("first line\nsecond line\nthird line");

        assert_eq!(editor.line_count(), 3);
        assert_eq!(editor.line_range(0), Some((0, 10)));
        assert_eq!(editor.line_range(1), Some((11, 22)));
        assert_eq!(editor.line_range(2), Some((23, 33)));

        // Cursor is at end of third line (33)
        assert_eq!(editor.current_line_info(), (2, 10));

        // Move to line start
        editor.move_line_start(false);
        assert_eq!(editor.cursor(), 23);
        assert_eq!(editor.current_line_info(), (2, 0));

        // Move to line end
        editor.move_line_end(false);
        assert_eq!(editor.cursor(), 33);

        // Move Up to second line
        editor.move_up(false);
        assert_eq!(editor.current_line_info(), (1, 10));
        assert_eq!(editor.cursor(), 21); // after 'e' of "second line"

        // Move Up to first line
        editor.move_up(false);
        assert_eq!(editor.current_line_info(), (0, 10));
        assert_eq!(editor.cursor(), 10); // after 'e' of "first line"

        // Move Down to second line
        editor.move_down(false);
        assert_eq!(editor.current_line_info(), (1, 10));
        assert_eq!(editor.cursor(), 21);
    }

    #[test]
    fn test_editor_undo_redo_basic() {
        let mut editor = Editor::new();
        assert!(!editor.can_undo());
        assert!(!editor.can_redo());

        editor.insert("hello");
        assert_eq!(editor.text(), "hello");
        assert!(editor.can_undo());
        assert!(!editor.can_redo());

        editor.insert(" world");
        assert_eq!(editor.text(), "hello world");

        assert!(editor.undo());
        assert_eq!(editor.text(), "hello");
        assert!(editor.can_redo());

        assert!(editor.undo());
        assert_eq!(editor.text(), "");
        assert!(!editor.can_undo());

        assert!(editor.redo());
        assert_eq!(editor.text(), "hello");

        assert!(editor.redo());
        assert_eq!(editor.text(), "hello world");
        assert!(!editor.can_redo());
    }

    #[test]
    fn test_editor_undo_typing_grouping() {
        let mut editor = Editor::new();
        for ch in "hello".chars() {
            editor.insert_char(ch);
        }
        assert_eq!(editor.text(), "hello");

        // Single undo should revert the entire alphanumeric continuous word "hello"
        assert!(editor.undo());
        assert_eq!(editor.text(), "");

        assert!(editor.redo());
        assert_eq!(editor.text(), "hello");

        // Type space and another word
        editor.insert_char(' ');
        for ch in "world".chars() {
            editor.insert_char(ch);
        }
        assert_eq!(editor.text(), "hello world");

        // Undo "world"
        assert!(editor.undo());
        assert_eq!(editor.text(), "hello ");

        // Undo space
        assert!(editor.undo());
        assert_eq!(editor.text(), "hello");
    }

    #[test]
    fn test_editor_undo_deletion() {
        let mut editor = Editor::new();
        editor.insert("testing");
        editor.delete_backward();
        assert_eq!(editor.text(), "testin");

        assert!(editor.undo());
        assert_eq!(editor.text(), "testing");
    }
}