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::prelude::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    /// Replaces the current selection with pasted text.
587    fn paste(&mut self, contents: &str) -> TextEvent {
588        if contents.is_empty() && self.get_selection_range().is_none() {
589            return TextEvent::empty();
590        }
591        if let Some((start, end)) = self.get_selection_range() {
592            self.remove(start..end);
593            self.move_cursor_to(start);
594        }
595        let position = self.cursor_pos();
596        let inserted = self.insert(contents, position);
597        self.move_cursor_to(position + inserted);
598        self.clear_selection();
599        TextEvent::TEXT_CHANGED | TextEvent::SELECTION_CHANGED
600    }
601
602    #[allow(clippy::too_many_arguments)]
603    fn process_key(
604        &mut self,
605        key: &Key,
606        modifiers: &Modifiers,
607        editor_line: Option<EditorLine>,
608        holder: Option<&ParagraphHolder>,
609        allow_tabs: bool,
610        allow_changes: bool,
611        allow_write_clipboard: bool,
612    ) -> TextEvent {
613        let mut event = TextEvent::empty();
614
615        let selection = self.get_selection();
616        let skip_arrows_movement = !modifiers.contains(Modifiers::SHIFT) && selection.is_some();
617        let word_jump = modifiers.contains(Modifiers::ctrl_or_alt());
618
619        match key {
620            Key::Named(NamedKey::Shift) => {}
621            Key::Named(NamedKey::Control) => {}
622            Key::Named(NamedKey::Alt) => {}
623            Key::Named(NamedKey::Escape) => {
624                self.clear_selection();
625            }
626            Key::Named(NamedKey::ArrowDown) => {
627                if modifiers.contains(Modifiers::SHIFT) {
628                    self.selection_mut().set_as_range();
629                } else {
630                    self.selection_mut().set_as_cursor();
631                }
632
633                if !skip_arrows_movement && self.cursor_down(editor_line, holder) {
634                    event.insert(TextEvent::CURSOR_CHANGED);
635                }
636            }
637            Key::Named(NamedKey::ArrowLeft) => {
638                if modifiers.contains(Modifiers::SHIFT) {
639                    self.selection_mut().set_as_range();
640                } else {
641                    self.selection_mut().set_as_cursor();
642                }
643
644                let moved = !skip_arrows_movement
645                    && if word_jump {
646                        self.cursor_word_left()
647                    } else {
648                        self.cursor_left()
649                    };
650
651                if moved {
652                    event.insert(TextEvent::CURSOR_CHANGED);
653                }
654            }
655            Key::Named(NamedKey::ArrowRight) => {
656                if modifiers.contains(Modifiers::SHIFT) {
657                    self.selection_mut().set_as_range();
658                } else {
659                    self.selection_mut().set_as_cursor();
660                }
661
662                let moved = !skip_arrows_movement
663                    && if word_jump {
664                        self.cursor_word_right()
665                    } else {
666                        self.cursor_right()
667                    };
668
669                if moved {
670                    event.insert(TextEvent::CURSOR_CHANGED);
671                }
672            }
673            Key::Named(NamedKey::ArrowUp) => {
674                if modifiers.contains(Modifiers::SHIFT) {
675                    self.selection_mut().set_as_range();
676                } else {
677                    self.selection_mut().set_as_cursor();
678                }
679
680                if !skip_arrows_movement && self.cursor_up(editor_line, holder) {
681                    event.insert(TextEvent::CURSOR_CHANGED);
682                }
683            }
684            Key::Named(named_key @ (NamedKey::Home | NamedKey::End)) => {
685                if modifiers.contains(Modifiers::SHIFT) {
686                    self.selection_mut().set_as_range();
687                } else {
688                    self.selection_mut().set_as_cursor();
689                }
690
691                let whole_text = modifiers.contains(Modifiers::ctrl_or_meta());
692                let pos = match (named_key, whole_text) {
693                    (NamedKey::Home, true) => 0,
694                    (NamedKey::Home, false) => {
695                        self.char_to_utf16_cu(self.line_to_char(self.cursor_row()))
696                    }
697                    (_, true) => self.len_utf16_cu(),
698                    (_, false) => self
699                        .line_end_position(self.cursor_row())
700                        .unwrap_or_else(|| self.len_utf16_cu()),
701                };
702
703                if pos != self.cursor_pos() {
704                    self.selection_mut().move_to(pos);
705                    event.insert(TextEvent::CURSOR_CHANGED);
706                }
707            }
708            Key::Named(NamedKey::Backspace) if allow_changes => {
709                let cursor_pos = self.cursor_pos();
710
711                let removal = if let Some((start, end)) = self.get_selection_range() {
712                    Some(start..end)
713                } else if word_jump {
714                    self.prev_word_pos(cursor_pos)
715                        .map(|start| start..cursor_pos)
716                } else if cursor_pos > 0 {
717                    Some(self.grapheme_cluster_at(cursor_pos - 1).start..cursor_pos)
718                } else {
719                    None
720                };
721
722                if let Some(removal) = removal {
723                    let end = removal.end;
724                    let removed_text_len = self.remove(removal);
725                    self.move_cursor_to(end - removed_text_len);
726                    event.insert(TextEvent::TEXT_CHANGED);
727                }
728            }
729            Key::Named(NamedKey::Delete) if allow_changes => {
730                let cursor_pos = self.cursor_pos();
731
732                let removal = if let Some((start, end)) = self.get_selection_range() {
733                    Some(start..end)
734                } else if word_jump {
735                    self.next_word_pos(cursor_pos).map(|end| cursor_pos..end)
736                } else if cursor_pos < self.len_utf16_cu() {
737                    Some(cursor_pos..self.grapheme_cluster_at(cursor_pos).end)
738                } else {
739                    None
740                };
741
742                if let Some(removal) = removal {
743                    let start = removal.start;
744                    self.remove(removal);
745                    self.move_cursor_to(start);
746                    event.insert(TextEvent::TEXT_CHANGED);
747                }
748            }
749            Key::Named(NamedKey::Enter) if allow_changes => {
750                // Breaks the line
751                let cursor_pos = self.cursor_pos();
752                self.insert_char('\n', cursor_pos);
753                self.cursor_right();
754
755                event.insert(TextEvent::TEXT_CHANGED);
756            }
757            Key::Named(NamedKey::Tab) if allow_tabs && allow_changes => {
758                // Inserts a tab
759                let text = " ".repeat(self.get_indentation().into());
760                let cursor_pos = self.cursor_pos();
761                self.insert(&text, cursor_pos);
762                self.move_cursor_to(cursor_pos + text.chars().count());
763
764                event.insert(TextEvent::TEXT_CHANGED);
765            }
766            Key::Character(character) => {
767                let meta_or_ctrl = modifiers.contains(Modifiers::ctrl_or_meta());
768
769                match character.as_str() {
770                    " " if allow_changes => {
771                        let selection = self.get_selection_range();
772                        if let Some((start, end)) = selection {
773                            self.remove(start..end);
774                            self.move_cursor_to(start);
775                            event.insert(TextEvent::TEXT_CHANGED);
776                        }
777
778                        // Simply adds an space
779                        let cursor_pos = self.cursor_pos();
780                        self.insert_char(' ', cursor_pos);
781                        self.cursor_right();
782
783                        event.insert(TextEvent::TEXT_CHANGED);
784                    }
785
786                    // Select all text
787                    "a" if meta_or_ctrl => {
788                        let len = self.len_utf16_cu();
789                        self.set_selection((0, len));
790                    }
791
792                    "c" | "C" | "x" | "X" if meta_or_ctrl => {
793                        let cut = matches!(character.as_str(), "x" | "X");
794                        if allow_write_clipboard
795                            && (!cut || allow_changes)
796                            && let Some(selected) = self.get_selected_text()
797                        {
798                            Clipboard::set_text_deferred(selected);
799                            if cut && let Some((start, end)) = self.get_selection_range() {
800                                self.remove(start..end);
801                                self.move_cursor_to(start);
802                                event.insert(TextEvent::TEXT_CHANGED);
803                            }
804                        }
805                    }
806                    "v" | "V" if meta_or_ctrl => {}
807
808                    // Undo last change
809                    "z" if meta_or_ctrl && allow_changes => {
810                        let undo_result = self.undo();
811
812                        if let Some(selection) = undo_result {
813                            *self.selection_mut() = selection;
814                            event.insert(TextEvent::TEXT_CHANGED);
815                            event.insert(TextEvent::SELECTION_CHANGED);
816                        }
817                    }
818
819                    // Redo last change
820                    "y" if meta_or_ctrl && allow_changes => {
821                        let redo_result = self.redo();
822
823                        if let Some(selection) = redo_result {
824                            *self.selection_mut() = selection;
825                            event.insert(TextEvent::TEXT_CHANGED);
826                            event.insert(TextEvent::SELECTION_CHANGED);
827                        }
828                    }
829
830                    _ if allow_changes => {
831                        // Remove selected text
832                        let selection = self.get_selection_range();
833                        if let Some((start, end)) = selection {
834                            self.remove(start..end);
835                            self.move_cursor_to(start);
836                            event.insert(TextEvent::TEXT_CHANGED);
837                        }
838
839                        if let Ok(ch) = character.parse::<char>() {
840                            // Inserts a character
841                            let cursor_pos = self.cursor_pos();
842                            let inserted_text_len = self.insert_char(ch, cursor_pos);
843                            self.move_cursor_to(cursor_pos + inserted_text_len);
844                            event.insert(TextEvent::TEXT_CHANGED);
845                        } else {
846                            // Inserts a text
847                            let cursor_pos = self.cursor_pos();
848                            let inserted_text_len = self.insert(character, cursor_pos);
849                            self.move_cursor_to(cursor_pos + inserted_text_len);
850                            event.insert(TextEvent::TEXT_CHANGED);
851                        }
852                    }
853                    _ => {}
854                }
855            }
856            _ => {}
857        }
858
859        if event.contains(TextEvent::TEXT_CHANGED) && !event.contains(TextEvent::SELECTION_CHANGED)
860        {
861            self.clear_selection();
862        }
863
864        if self.get_selection() != selection {
865            event.insert(TextEvent::SELECTION_CHANGED);
866        }
867
868        event
869    }
870
871    fn get_selected_text(&self) -> Option<String>;
872
873    fn undo(&mut self) -> Option<TextSelection>;
874
875    fn redo(&mut self) -> Option<TextSelection>;
876
877    fn editor_history(&self) -> &EditorHistory;
878
879    fn editor_history_mut(&mut self) -> &mut EditorHistory;
880
881    fn get_selection_range(&self) -> Option<(usize, usize)>;
882
883    fn get_indentation(&self) -> u8;
884
885    /// Find the UTF-16 boundaries of the logical line containing a position.
886    fn find_line_boundaries(&self, position: usize) -> (usize, usize) {
887        let line_index = self.char_to_line(self.utf16_cu_to_char(position));
888        let start = self.char_to_utf16_cu(self.line_to_char(line_index));
889        let length = self.line(line_index).map_or(0, |line| line.utf16_len());
890        (start, start + length)
891    }
892
893    fn find_word_boundaries(&self, pos: usize) -> (usize, usize) {
894        let pos_char = self.utf16_cu_to_char(pos);
895        let len_chars = self.len_chars();
896
897        if len_chars == 0 {
898            return (pos, pos);
899        }
900
901        // Get the line containing the cursor
902        let line_idx = self.char_to_line(pos_char);
903        let line_char = self.line_to_char(line_idx);
904        let line = self.line(line_idx).unwrap();
905
906        let line_str: std::borrow::Cow<str> = line.text;
907        let pos_in_line = pos_char - line_char;
908
909        // Find word boundaries within the line
910        let mut char_offset = 0;
911        for word in line_str.split_word_bounds() {
912            let word_char_len = word.chars().count();
913            let word_start = char_offset;
914            let word_end = char_offset + word_char_len;
915
916            if pos_in_line >= word_start && pos_in_line < word_end {
917                let start_char = line_char + word_start;
918                let end_char = line_char + word_end;
919                return (
920                    self.char_to_utf16_cu(start_char),
921                    self.char_to_utf16_cu(end_char),
922                );
923            }
924
925            char_offset = word_end;
926        }
927
928        (pos, pos)
929    }
930}