Skip to main content

freya_edit/
text_editor.rs

1use std::{
2    borrow::Cow,
3    cmp::Ordering,
4    fmt::Display,
5    ops::Range,
6};
7
8use freya_clipboard::clipboard::Clipboard;
9use freya_core::{
10    elements::paragraph::{
11        ParagraphCursorExt,
12        ParagraphHolder,
13        ParagraphHolderInner,
14    },
15    events::modifiers::ModifiersExt,
16};
17use keyboard_types::{
18    Key,
19    Modifiers,
20    NamedKey,
21};
22use ropey::Rope;
23use unicode_segmentation::UnicodeSegmentation;
24
25use crate::editor_history::EditorHistory;
26
27#[derive(PartialEq, Clone, Debug, Copy, Hash)]
28pub enum EditorLine {
29    /// Only one `paragraph` element exists in the whole editor.
30    SingleParagraph,
31    /// There are multiple `paragraph` elements in the editor, one per line.
32    Paragraph(usize),
33}
34
35/// Holds the position of a cursor in a text
36#[derive(Clone, PartialEq, Debug)]
37pub enum TextSelection {
38    Cursor(usize),
39    Range { from: usize, to: usize },
40}
41
42impl TextSelection {
43    /// Create a new [TextSelection::Cursor]
44    pub fn new_cursor(pos: usize) -> Self {
45        Self::Cursor(pos)
46    }
47
48    /// Create a new [TextSelection::Range]
49    pub fn new_range((from, to): (usize, usize)) -> Self {
50        Self::Range { from, to }
51    }
52
53    /// Get the position
54    pub fn pos(&self) -> usize {
55        self.end()
56    }
57
58    /// Set the selection as a cursor
59    pub fn set_as_cursor(&mut self) {
60        *self = Self::Cursor(self.end())
61    }
62
63    /// Set the selection as a range
64    pub fn set_as_range(&mut self) {
65        *self = Self::Range {
66            from: self.start(),
67            to: self.end(),
68        }
69    }
70
71    /// Get the start of the cursor position.
72    pub fn start(&self) -> usize {
73        match self {
74            Self::Cursor(pos) => *pos,
75            Self::Range { from, .. } => *from,
76        }
77    }
78
79    /// Get the end of the cursor position.
80    pub fn end(&self) -> usize {
81        match self {
82            Self::Cursor(pos) => *pos,
83            Self::Range { to, .. } => *to,
84        }
85    }
86
87    /// Move the end position of the cursor.
88    pub fn move_to(&mut self, position: usize) {
89        match self {
90            Self::Cursor(pos) => *pos = position,
91            Self::Range { to, .. } => {
92                *to = position;
93            }
94        }
95    }
96
97    /// Clamps UTF-16 offsets to the text length and rounds down to character boundaries.
98    pub fn clamp(&mut self, rope: &Rope) {
99        let len = rope.len_utf16_cu();
100        let clamp = |position: usize| {
101            let position = position.min(len);
102            rope.char_to_utf16_cu(rope.utf16_cu_to_char(position))
103        };
104
105        match self {
106            Self::Cursor(position) => *position = clamp(*position),
107            Self::Range { from, to } => {
108                *from = clamp(*from);
109                *to = clamp(*to);
110            }
111        }
112    }
113
114    pub fn is_range(&self) -> bool {
115        matches!(self, Self::Range { .. })
116    }
117}
118
119/// A text line from a [TextEditor]
120#[derive(Clone)]
121pub struct Line<'a> {
122    pub text: Cow<'a, str>,
123    pub utf16_len: usize,
124}
125
126impl Line<'_> {
127    /// Get the length of the line
128    pub fn utf16_len(&self) -> usize {
129        self.utf16_len
130    }
131}
132
133impl Display for Line<'_> {
134    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135        f.write_str(&self.text)
136    }
137}
138
139bitflags::bitflags! {
140    /// Events for [TextEditor]
141    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
142    pub struct TextEvent: u8 {
143         /// Cursor position has been moved
144        const CURSOR_CHANGED = 0x01;
145        /// Text has changed
146        const TEXT_CHANGED = 0x02;
147        /// Selected text has changed
148        const SELECTION_CHANGED = 0x04;
149    }
150}
151
152/// Common trait for editable texts
153pub trait TextEditor {
154    type LinesIterator<'a>: Iterator<Item = Line<'a>>
155    where
156        Self: 'a;
157
158    fn set(&mut self, text: &str);
159
160    /// Iterator over all the lines in the text.
161    fn lines(&self) -> Self::LinesIterator<'_>;
162
163    /// Insert a character in the text in the given position.
164    fn insert_char(&mut self, char: char, char_idx: usize) -> usize;
165
166    /// Insert a string in the text in the given position.
167    fn insert(&mut self, text: &str, char_idx: usize) -> usize;
168
169    /// Remove a part of the text.
170    fn remove(&mut self, range: Range<usize>) -> usize;
171
172    /// Get line from the given char
173    fn char_to_line(&self, char_idx: usize) -> usize;
174
175    /// Get the first char from the given line
176    fn line_to_char(&self, line_idx: usize) -> usize;
177
178    fn utf16_cu_to_char(&self, utf16_cu_idx: usize) -> usize;
179
180    fn char_to_utf16_cu(&self, idx: usize) -> usize;
181
182    /// Get a line from the text
183    fn line(&self, line_idx: usize) -> Option<Line<'_>>;
184
185    fn text(&self) -> Cow<'_, str>;
186
187    /// Total of lines
188    fn len_lines(&self) -> usize;
189
190    /// Total of chars
191    fn len_chars(&self) -> usize;
192
193    /// Total of utf16 code units
194    fn len_utf16_cu(&self) -> usize;
195
196    /// Get a readable text selection
197    fn selection(&self) -> &TextSelection;
198
199    /// Get a mutable reference to text selection
200    fn selection_mut(&mut self) -> &mut TextSelection;
201
202    /// Get the UTF-16 range of the grapheme cluster containing the given position.
203    fn grapheme_cluster_at(&self, pos_utf16: usize) -> Range<usize> {
204        let line_idx = self.char_to_line(self.utf16_cu_to_char(pos_utf16));
205        let line_start = self.char_to_utf16_cu(self.line_to_char(line_idx));
206        let Some(line) = self.line(line_idx) else {
207            return pos_utf16..pos_utf16;
208        };
209
210        let mut cluster = line_start..line_start;
211        for grapheme in line.text.graphemes(true) {
212            cluster = cluster.end..cluster.end + grapheme.encode_utf16().count();
213            if cluster.end > pos_utf16 {
214                return cluster;
215            }
216        }
217        pos_utf16..pos_utf16
218    }
219
220    /// Get the cursor row
221    fn cursor_row(&self) -> usize {
222        let pos = self.cursor_pos();
223        let pos_utf8 = self.utf16_cu_to_char(pos);
224        self.char_to_line(pos_utf8)
225    }
226
227    /// Get the cursor column
228    fn cursor_col(&self) -> usize {
229        let pos = self.cursor_pos();
230        let pos_utf8 = self.utf16_cu_to_char(pos);
231        let line = self.char_to_line(pos_utf8);
232        let line_char_utf8 = self.line_to_char(line);
233        let line_char = self.char_to_utf16_cu(line_char_utf8);
234        pos - line_char
235    }
236
237    /// Last valid cursor position in `row`, before the line ending if it has one.
238    fn line_end_position(&self, row: usize) -> Option<usize> {
239        let line = self.line(row)?;
240        let row_start = self.char_to_utf16_cu(self.line_to_char(row));
241        let row_end = row_start + line.utf16_len();
242        if row + 1 == self.len_lines() {
243            Some(row_end)
244        } else {
245            Some(self.grapheme_cluster_at(row_end - 1).start)
246        }
247    }
248
249    /// Move the cursor to `row`, keeping `col` when possible and snapping to a
250    /// grapheme cluster boundary.
251    fn move_cursor_to_row(&mut self, row: usize, col: usize) {
252        let Some(last_position) = self.line_end_position(row) else {
253            return;
254        };
255        let row_start = self.char_to_utf16_cu(self.line_to_char(row));
256        let col = col.min(last_position - row_start);
257        let pos = self.grapheme_cluster_at(row_start + col).start;
258        self.selection_mut().move_to(pos);
259    }
260
261    /// Move the cursor 1 line down
262    fn cursor_down(
263        &mut self,
264        editor_line: Option<EditorLine>,
265        holder: Option<&ParagraphHolder>,
266    ) -> bool {
267        if let Some(editor_line) = editor_line
268            && let Some(holder) = holder
269            && let Some(position) = self.visual_line_position(holder, editor_line, 1)
270        {
271            self.selection_mut().move_to(position);
272
273            return true;
274        }
275
276        let old_row = self.cursor_row();
277        let old_col = self.cursor_col();
278
279        match old_row.cmp(&(self.len_lines() - 1)) {
280            Ordering::Less => {
281                self.move_cursor_to_row(old_row + 1, old_col);
282
283                true
284            }
285            Ordering::Equal => {
286                let end = self.len_utf16_cu();
287                self.selection_mut().move_to(end);
288
289                true
290            }
291            Ordering::Greater => false,
292        }
293    }
294
295    /// Move the cursor 1 line up
296    fn cursor_up(
297        &mut self,
298        editor_line: Option<EditorLine>,
299        holder: Option<&ParagraphHolder>,
300    ) -> bool {
301        if let Some(editor_line) = editor_line
302            && let Some(holder) = holder
303            && let Some(position) = self.visual_line_position(holder, editor_line, -1)
304        {
305            self.selection_mut().move_to(position);
306
307            return true;
308        }
309
310        let pos = self.cursor_pos();
311        let old_row = self.cursor_row();
312        let old_col = self.cursor_col();
313
314        if pos > 0 {
315            if old_row == 0 {
316                self.selection_mut().move_to(0);
317            } else {
318                self.move_cursor_to_row(old_row - 1, old_col);
319            }
320
321            true
322        } else {
323            false
324        }
325    }
326
327    /// Cursor position one visual line up or down.
328    fn visual_line_position(
329        &self,
330        holder: &ParagraphHolder,
331        editor_line: EditorLine,
332        line_offset: isize,
333    ) -> Option<usize> {
334        let holder = holder.0.borrow();
335        let ParagraphHolderInner { paragraph, .. } = holder.as_ref()?;
336
337        if !matches!(editor_line, EditorLine::SingleParagraph) {
338            return None;
339        }
340
341        let cursor_rect = paragraph.measured_cursor_rect(&self.text(), self.cursor_pos())?;
342
343        let lines = paragraph.get_line_metrics();
344        let current = if self.cursor_pos() == self.len_utf16_cu() {
345            lines.len().checked_sub(1)?
346        } else {
347            paragraph.get_line_number_at_utf16_offset(self.cursor_pos())?
348        };
349        let line = lines.get(current.checked_add_signed(line_offset)?)?;
350
351        Some(paragraph.cursor_index_at_point((cursor_rect.left as f64, line.baseline)))
352    }
353
354    /// Move the cursor 1 grapheme cluster to the right
355    fn cursor_right(&mut self) -> bool {
356        if self.cursor_pos() < self.len_utf16_cu() {
357            let to = self.grapheme_cluster_at(self.selection().end()).end;
358            self.selection_mut().move_to(to);
359
360            true
361        } else {
362            false
363        }
364    }
365
366    /// Move the cursor 1 grapheme cluster to the left
367    fn cursor_left(&mut self) -> bool {
368        if self.cursor_pos() > 0 {
369            let to = self.grapheme_cluster_at(self.selection().end() - 1).start;
370            self.selection_mut().move_to(to);
371
372            true
373        } else {
374            false
375        }
376    }
377
378    /// Find the end of the next word from the given position, if any.
379    fn next_word_pos(&self, pos: usize) -> Option<usize> {
380        let len = self.len_utf16_cu();
381        if pos >= len {
382            return None;
383        }
384
385        // Walk forward line by line starting at the given position.
386        let start_char = self.utf16_cu_to_char(pos);
387        let initial_line = self.char_to_line(start_char);
388        let initial_offset = start_char - self.line_to_char(initial_line);
389
390        for line_idx in initial_line..self.len_lines() {
391            let Some(line) = self.line(line_idx) else {
392                continue;
393            };
394            let line_char_offset = self.line_to_char(line_idx);
395            let from = if line_idx == initial_line {
396                initial_offset
397            } else {
398                0
399            };
400
401            // Stop at the end of the first non-whitespace segment past the position.
402            let mut char_offset = 0;
403            for word in line.text.split_word_bounds() {
404                char_offset += word.chars().count();
405                if char_offset > from && !word.chars().all(char::is_whitespace) {
406                    return Some(self.char_to_utf16_cu(line_char_offset + char_offset));
407                }
408            }
409        }
410
411        // Trailing whitespace only, snap to text end.
412        Some(len)
413    }
414
415    /// Find the start of the previous word from the given position, if any.
416    fn prev_word_pos(&self, pos: usize) -> Option<usize> {
417        if pos == 0 {
418            return None;
419        }
420
421        // Walk backward line by line starting at the given position.
422        let start_char = self.utf16_cu_to_char(pos);
423        let initial_line = self.char_to_line(start_char);
424        let initial_offset = start_char - self.line_to_char(initial_line);
425
426        for line_idx in (0..=initial_line).rev() {
427            let Some(line) = self.line(line_idx) else {
428                continue;
429            };
430            let line_char_offset = self.line_to_char(line_idx);
431            let to = if line_idx == initial_line {
432                initial_offset
433            } else {
434                line.text.chars().count()
435            };
436
437            // Track the latest non-whitespace segment that starts before the position.
438            let mut char_offset = 0;
439            let mut last_word_start = None;
440            for word in line.text.split_word_bounds() {
441                if char_offset >= to {
442                    break;
443                }
444                if !word.chars().all(char::is_whitespace) {
445                    last_word_start = Some(char_offset);
446                }
447                char_offset += word.chars().count();
448            }
449
450            if let Some(start) = last_word_start {
451                return Some(self.char_to_utf16_cu(line_char_offset + start));
452            }
453        }
454
455        // Leading whitespace only, snap to text start.
456        Some(0)
457    }
458
459    /// Move the cursor to the end of the next word.
460    fn cursor_word_right(&mut self) -> bool {
461        if let Some(new_pos) = self.next_word_pos(self.cursor_pos()) {
462            self.selection_mut().move_to(new_pos);
463            true
464        } else {
465            false
466        }
467    }
468
469    /// Move the cursor to the start of the previous word.
470    fn cursor_word_left(&mut self) -> bool {
471        if let Some(new_pos) = self.prev_word_pos(self.cursor_pos()) {
472            self.selection_mut().move_to(new_pos);
473            true
474        } else {
475            false
476        }
477    }
478
479    /// Get the cursor position
480    fn cursor_pos(&self) -> usize {
481        self.selection().pos()
482    }
483
484    /// Move the cursor position
485    fn move_cursor_to(&mut self, pos: usize) {
486        self.selection_mut().move_to(pos);
487    }
488
489    // Check if has any selection at all
490    fn has_any_selection(&self) -> bool;
491
492    // Return the selected text
493    fn get_selection(&self) -> Option<(usize, usize)>;
494
495    // Return the visible selected text for the given editor line
496    fn get_visible_selection(&self, editor_line: EditorLine) -> Option<(usize, usize)> {
497        let (selected_from, selected_to) = match self.selection() {
498            TextSelection::Cursor(_) => return None,
499            TextSelection::Range { from, to } => (*from, *to),
500        };
501
502        match editor_line {
503            EditorLine::Paragraph(line_index) => {
504                let selected_from_row = self.char_to_line(self.utf16_cu_to_char(selected_from));
505                let selected_to_row = self.char_to_line(self.utf16_cu_to_char(selected_to));
506
507                let editor_row_idx = self.char_to_utf16_cu(self.line_to_char(line_index));
508                let selected_from_row_idx =
509                    self.char_to_utf16_cu(self.line_to_char(selected_from_row));
510                let selected_to_row_idx = self.char_to_utf16_cu(self.line_to_char(selected_to_row));
511
512                let selected_from_col_idx = selected_from - selected_from_row_idx;
513                let selected_to_col_idx = selected_to - selected_to_row_idx;
514
515                // Between starting line and endling line
516                if (line_index > selected_from_row && line_index < selected_to_row)
517                    || (line_index < selected_from_row && line_index > selected_to_row)
518                {
519                    let len = self.line(line_index).unwrap().utf16_len();
520                    return Some((0, len));
521                }
522
523                match selected_from_row.cmp(&selected_to_row) {
524                    // Selection direction is from bottom -> top
525                    Ordering::Greater => {
526                        if selected_from_row == line_index {
527                            // Starting line
528                            Some((0, selected_from_col_idx))
529                        } else if selected_to_row == line_index {
530                            // Ending line
531                            let len = self.line(selected_to_row).unwrap().utf16_len();
532                            Some((selected_to_col_idx, len))
533                        } else {
534                            None
535                        }
536                    }
537                    // Selection direction is from top -> bottom
538                    Ordering::Less => {
539                        if selected_from_row == line_index {
540                            // Starting line
541                            let len = self.line(selected_from_row).unwrap().utf16_len();
542                            Some((selected_from_col_idx, len))
543                        } else if selected_to_row == line_index {
544                            // Ending line
545                            Some((0, selected_to_col_idx))
546                        } else {
547                            None
548                        }
549                    }
550                    Ordering::Equal if selected_from_row == line_index => {
551                        // Starting and endline line are the same
552                        Some((selected_from - editor_row_idx, selected_to - editor_row_idx))
553                    }
554                    _ => None,
555                }
556            }
557            EditorLine::SingleParagraph => Some((selected_from, selected_to)),
558        }
559    }
560
561    // Remove the selection
562    fn clear_selection(&mut self);
563
564    // Select some text
565    fn set_selection(&mut self, selected: (usize, usize));
566
567    // Measure a new text selection
568
569    fn measure_selection(&self, to: usize, line_index: EditorLine) -> TextSelection {
570        let mut selection = self.selection().clone();
571
572        match line_index {
573            EditorLine::Paragraph(line_index) => {
574                let row_char = self.line_to_char(line_index);
575                let pos = self.char_to_utf16_cu(row_char) + to;
576                selection.move_to(pos);
577            }
578            EditorLine::SingleParagraph => {
579                selection.move_to(to);
580            }
581        }
582
583        selection
584    }
585
586    // Process a Keyboard event
587    #[allow(clippy::too_many_arguments)]
588    fn process_key(
589        &mut self,
590        key: &Key,
591        modifiers: &Modifiers,
592        editor_line: Option<EditorLine>,
593        holder: Option<&ParagraphHolder>,
594        allow_tabs: bool,
595        allow_changes: bool,
596        allow_read_clipboard: bool,
597        allow_write_clipboard: bool,
598    ) -> TextEvent {
599        let mut event = TextEvent::empty();
600
601        let selection = self.get_selection();
602        let skip_arrows_movement = !modifiers.contains(Modifiers::SHIFT) && selection.is_some();
603        let word_jump = modifiers.contains(Modifiers::ctrl_or_alt());
604
605        match key {
606            Key::Named(NamedKey::Shift) => {}
607            Key::Named(NamedKey::Control) => {}
608            Key::Named(NamedKey::Alt) => {}
609            Key::Named(NamedKey::Escape) => {
610                self.clear_selection();
611            }
612            Key::Named(NamedKey::ArrowDown) => {
613                if modifiers.contains(Modifiers::SHIFT) {
614                    self.selection_mut().set_as_range();
615                } else {
616                    self.selection_mut().set_as_cursor();
617                }
618
619                if !skip_arrows_movement && self.cursor_down(editor_line, holder) {
620                    event.insert(TextEvent::CURSOR_CHANGED);
621                }
622            }
623            Key::Named(NamedKey::ArrowLeft) => {
624                if modifiers.contains(Modifiers::SHIFT) {
625                    self.selection_mut().set_as_range();
626                } else {
627                    self.selection_mut().set_as_cursor();
628                }
629
630                let moved = !skip_arrows_movement
631                    && if word_jump {
632                        self.cursor_word_left()
633                    } else {
634                        self.cursor_left()
635                    };
636
637                if moved {
638                    event.insert(TextEvent::CURSOR_CHANGED);
639                }
640            }
641            Key::Named(NamedKey::ArrowRight) => {
642                if modifiers.contains(Modifiers::SHIFT) {
643                    self.selection_mut().set_as_range();
644                } else {
645                    self.selection_mut().set_as_cursor();
646                }
647
648                let moved = !skip_arrows_movement
649                    && if word_jump {
650                        self.cursor_word_right()
651                    } else {
652                        self.cursor_right()
653                    };
654
655                if moved {
656                    event.insert(TextEvent::CURSOR_CHANGED);
657                }
658            }
659            Key::Named(NamedKey::ArrowUp) => {
660                if modifiers.contains(Modifiers::SHIFT) {
661                    self.selection_mut().set_as_range();
662                } else {
663                    self.selection_mut().set_as_cursor();
664                }
665
666                if !skip_arrows_movement && self.cursor_up(editor_line, holder) {
667                    event.insert(TextEvent::CURSOR_CHANGED);
668                }
669            }
670            Key::Named(named_key @ (NamedKey::Home | NamedKey::End)) => {
671                if modifiers.contains(Modifiers::SHIFT) {
672                    self.selection_mut().set_as_range();
673                } else {
674                    self.selection_mut().set_as_cursor();
675                }
676
677                let whole_text = modifiers.contains(Modifiers::ctrl_or_meta());
678                let pos = match (named_key, whole_text) {
679                    (NamedKey::Home, true) => 0,
680                    (NamedKey::Home, false) => {
681                        self.char_to_utf16_cu(self.line_to_char(self.cursor_row()))
682                    }
683                    (_, true) => self.len_utf16_cu(),
684                    (_, false) => self
685                        .line_end_position(self.cursor_row())
686                        .unwrap_or_else(|| self.len_utf16_cu()),
687                };
688
689                if pos != self.cursor_pos() {
690                    self.selection_mut().move_to(pos);
691                    event.insert(TextEvent::CURSOR_CHANGED);
692                }
693            }
694            Key::Named(NamedKey::Backspace) if allow_changes => {
695                let cursor_pos = self.cursor_pos();
696
697                let removal = if let Some((start, end)) = self.get_selection_range() {
698                    Some(start..end)
699                } else if word_jump {
700                    self.prev_word_pos(cursor_pos)
701                        .map(|start| start..cursor_pos)
702                } else if cursor_pos > 0 {
703                    Some(self.grapheme_cluster_at(cursor_pos - 1).start..cursor_pos)
704                } else {
705                    None
706                };
707
708                if let Some(removal) = removal {
709                    let end = removal.end;
710                    let removed_text_len = self.remove(removal);
711                    self.move_cursor_to(end - removed_text_len);
712                    event.insert(TextEvent::TEXT_CHANGED);
713                }
714            }
715            Key::Named(NamedKey::Delete) if allow_changes => {
716                let cursor_pos = self.cursor_pos();
717
718                let removal = if let Some((start, end)) = self.get_selection_range() {
719                    Some(start..end)
720                } else if word_jump {
721                    self.next_word_pos(cursor_pos).map(|end| cursor_pos..end)
722                } else if cursor_pos < self.len_utf16_cu() {
723                    Some(cursor_pos..self.grapheme_cluster_at(cursor_pos).end)
724                } else {
725                    None
726                };
727
728                if let Some(removal) = removal {
729                    let start = removal.start;
730                    self.remove(removal);
731                    self.move_cursor_to(start);
732                    event.insert(TextEvent::TEXT_CHANGED);
733                }
734            }
735            Key::Named(NamedKey::Enter) if allow_changes => {
736                // Breaks the line
737                let cursor_pos = self.cursor_pos();
738                self.insert_char('\n', cursor_pos);
739                self.cursor_right();
740
741                event.insert(TextEvent::TEXT_CHANGED);
742            }
743            Key::Named(NamedKey::Tab) if allow_tabs && allow_changes => {
744                // Inserts a tab
745                let text = " ".repeat(self.get_indentation().into());
746                let cursor_pos = self.cursor_pos();
747                self.insert(&text, cursor_pos);
748                self.move_cursor_to(cursor_pos + text.chars().count());
749
750                event.insert(TextEvent::TEXT_CHANGED);
751            }
752            Key::Character(character) => {
753                let meta_or_ctrl = modifiers.contains(Modifiers::ctrl_or_meta());
754
755                match character.as_str() {
756                    " " if allow_changes => {
757                        let selection = self.get_selection_range();
758                        if let Some((start, end)) = selection {
759                            self.remove(start..end);
760                            self.move_cursor_to(start);
761                            event.insert(TextEvent::TEXT_CHANGED);
762                        }
763
764                        // Simply adds an space
765                        let cursor_pos = self.cursor_pos();
766                        self.insert_char(' ', cursor_pos);
767                        self.cursor_right();
768
769                        event.insert(TextEvent::TEXT_CHANGED);
770                    }
771
772                    // Select all text
773                    "a" if meta_or_ctrl => {
774                        let len = self.len_utf16_cu();
775                        self.set_selection((0, len));
776                    }
777
778                    // Copy selected text
779                    "c" if meta_or_ctrl && allow_write_clipboard => {
780                        let selected = self.get_selected_text();
781                        if let Some(selected) = selected {
782                            Clipboard::set(selected).ok();
783                        }
784                    }
785
786                    // Cut selected text
787                    "x" if meta_or_ctrl && allow_changes && allow_write_clipboard => {
788                        let selection = self.get_selection_range();
789                        if let Some((start, end)) = selection {
790                            let text = self.get_selected_text().unwrap();
791                            self.remove(start..end);
792                            Clipboard::set(text).ok();
793                            self.move_cursor_to(start);
794                            event.insert(TextEvent::TEXT_CHANGED);
795                        }
796                    }
797
798                    // Paste copied text
799                    "v" if meta_or_ctrl && allow_changes && allow_read_clipboard => {
800                        if let Ok(copied_text) = Clipboard::get() {
801                            let selection = self.get_selection_range();
802                            if let Some((start, end)) = selection {
803                                self.remove(start..end);
804                                self.move_cursor_to(start);
805                            }
806                            let cursor_pos = self.cursor_pos();
807                            self.insert(&copied_text, cursor_pos);
808                            let last_idx = copied_text.encode_utf16().count() + cursor_pos;
809                            self.move_cursor_to(last_idx);
810                            event.insert(TextEvent::TEXT_CHANGED);
811                        }
812                    }
813
814                    // Undo last change
815                    "z" if meta_or_ctrl && allow_changes => {
816                        let undo_result = self.undo();
817
818                        if let Some(selection) = undo_result {
819                            *self.selection_mut() = selection;
820                            event.insert(TextEvent::TEXT_CHANGED);
821                            event.insert(TextEvent::SELECTION_CHANGED);
822                        }
823                    }
824
825                    // Redo last change
826                    "y" if meta_or_ctrl && allow_changes => {
827                        let redo_result = self.redo();
828
829                        if let Some(selection) = redo_result {
830                            *self.selection_mut() = selection;
831                            event.insert(TextEvent::TEXT_CHANGED);
832                            event.insert(TextEvent::SELECTION_CHANGED);
833                        }
834                    }
835
836                    _ if allow_changes => {
837                        // Remove selected text
838                        let selection = self.get_selection_range();
839                        if let Some((start, end)) = selection {
840                            self.remove(start..end);
841                            self.move_cursor_to(start);
842                            event.insert(TextEvent::TEXT_CHANGED);
843                        }
844
845                        if let Ok(ch) = character.parse::<char>() {
846                            // Inserts a character
847                            let cursor_pos = self.cursor_pos();
848                            let inserted_text_len = self.insert_char(ch, cursor_pos);
849                            self.move_cursor_to(cursor_pos + inserted_text_len);
850                            event.insert(TextEvent::TEXT_CHANGED);
851                        } else {
852                            // Inserts a text
853                            let cursor_pos = self.cursor_pos();
854                            let inserted_text_len = self.insert(character, cursor_pos);
855                            self.move_cursor_to(cursor_pos + inserted_text_len);
856                            event.insert(TextEvent::TEXT_CHANGED);
857                        }
858                    }
859                    _ => {}
860                }
861            }
862            _ => {}
863        }
864
865        if event.contains(TextEvent::TEXT_CHANGED) && !event.contains(TextEvent::SELECTION_CHANGED)
866        {
867            self.clear_selection();
868        }
869
870        if self.get_selection() != selection {
871            event.insert(TextEvent::SELECTION_CHANGED);
872        }
873
874        event
875    }
876
877    fn get_selected_text(&self) -> Option<String>;
878
879    fn undo(&mut self) -> Option<TextSelection>;
880
881    fn redo(&mut self) -> Option<TextSelection>;
882
883    fn editor_history(&self) -> &EditorHistory;
884
885    fn editor_history_mut(&mut self) -> &mut EditorHistory;
886
887    fn get_selection_range(&self) -> Option<(usize, usize)>;
888
889    fn get_indentation(&self) -> u8;
890
891    /// Find the UTF-16 boundaries of the logical line containing a position.
892    fn find_line_boundaries(&self, position: usize) -> (usize, usize) {
893        let line_index = self.char_to_line(self.utf16_cu_to_char(position));
894        let start = self.char_to_utf16_cu(self.line_to_char(line_index));
895        let length = self.line(line_index).map_or(0, |line| line.utf16_len());
896        (start, start + length)
897    }
898
899    fn find_word_boundaries(&self, pos: usize) -> (usize, usize) {
900        let pos_char = self.utf16_cu_to_char(pos);
901        let len_chars = self.len_chars();
902
903        if len_chars == 0 {
904            return (pos, pos);
905        }
906
907        // Get the line containing the cursor
908        let line_idx = self.char_to_line(pos_char);
909        let line_char = self.line_to_char(line_idx);
910        let line = self.line(line_idx).unwrap();
911
912        let line_str: std::borrow::Cow<str> = line.text;
913        let pos_in_line = pos_char - line_char;
914
915        // Find word boundaries within the line
916        let mut char_offset = 0;
917        for word in line_str.split_word_bounds() {
918            let word_char_len = word.chars().count();
919            let word_start = char_offset;
920            let word_end = char_offset + word_char_len;
921
922            if pos_in_line >= word_start && pos_in_line < word_end {
923                let start_char = line_char + word_start;
924                let end_char = line_char + word_end;
925                return (
926                    self.char_to_utf16_cu(start_char),
927                    self.char_to_utf16_cu(end_char),
928                );
929            }
930
931            char_offset = word_end;
932        }
933
934        (pos, pos)
935    }
936}