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