cosmic_text/edit/
vi.rs

1use alloc::{collections::BTreeMap, string::String};
2use core::cmp;
3use modit::{Event, Key, Parser, TextObject, WordIter};
4
5use crate::{
6    Action, AttrsList, BorrowedWithFontSystem, BufferRef, Change, Color, Cursor, Edit, FontSystem,
7    Motion, Renderer, Selection, SyntaxEditor, SyntaxTheme,
8};
9
10pub use modit::{ViMode, ViParser};
11use unicode_segmentation::UnicodeSegmentation;
12
13fn undo_2_action<'buffer, E: Edit<'buffer>>(
14    editor: &mut E,
15    action: cosmic_undo_2::Action<&Change>,
16) {
17    match action {
18        cosmic_undo_2::Action::Do(change) => {
19            editor.apply_change(change);
20        }
21        cosmic_undo_2::Action::Undo(change) => {
22            //TODO: make this more efficient
23            let mut reversed = change.clone();
24            reversed.reverse();
25            editor.apply_change(&reversed);
26        }
27    }
28}
29
30fn finish_change<'buffer, E: Edit<'buffer>>(
31    editor: &mut E,
32    commands: &mut cosmic_undo_2::Commands<Change>,
33    changed: &mut bool,
34    pivot: Option<usize>,
35) -> Option<Change> {
36    //TODO: join changes together
37    match editor.finish_change() {
38        Some(change) => {
39            if !change.items.is_empty() {
40                commands.push(change.clone());
41                *changed = eval_changed(commands, pivot);
42            }
43            Some(change)
44        }
45        None => None,
46    }
47}
48
49/// Evaluate if an [`ViEditor`] changed based on its last saved state.
50fn eval_changed(commands: &cosmic_undo_2::Commands<Change>, pivot: Option<usize>) -> bool {
51    // Editors are considered modified if the current change index is unequal to the last
52    // saved index or if `pivot` is None.
53    // The latter case handles a never saved editor with a current command index of None.
54    // Check the unit tests for an example.
55    match (commands.current_command_index(), pivot) {
56        (Some(current), Some(pivot)) => current != pivot,
57        // Edge case for an editor with neither a save point nor any changes.
58        // This could be a new editor or an editor without a save point where undo() is called
59        // until the editor is fresh.
60        (None, None) => false,
61        // Default to true because it's safer to assume a buffer has been modified so as to not
62        // lose changes
63        _ => true,
64    }
65}
66
67fn search<'buffer, E: Edit<'buffer>>(editor: &mut E, value: &str, forwards: bool) -> bool {
68    let mut cursor = editor.cursor();
69    let start_line = cursor.line;
70    if forwards {
71        while cursor.line < editor.with_buffer(|buffer| buffer.lines.len()) {
72            if let Some(index) = editor.with_buffer(|buffer| {
73                buffer.lines[cursor.line]
74                    .text()
75                    .match_indices(value)
76                    .filter_map(|(i, _)| {
77                        if cursor.line != start_line || i > cursor.index {
78                            Some(i)
79                        } else {
80                            None
81                        }
82                    })
83                    .next()
84            }) {
85                cursor.index = index;
86                editor.set_cursor(cursor);
87                return true;
88            }
89
90            cursor.line += 1;
91        }
92    } else {
93        cursor.line += 1;
94        while cursor.line > 0 {
95            cursor.line -= 1;
96
97            if let Some(index) = editor.with_buffer(|buffer| {
98                buffer.lines[cursor.line]
99                    .text()
100                    .rmatch_indices(value)
101                    .filter_map(|(i, _)| {
102                        if cursor.line != start_line || i < cursor.index {
103                            Some(i)
104                        } else {
105                            None
106                        }
107                    })
108                    .next()
109            }) {
110                cursor.index = index;
111                editor.set_cursor(cursor);
112                return true;
113            }
114        }
115    }
116    false
117}
118
119fn select_in<'buffer, E: Edit<'buffer>>(editor: &mut E, start_c: char, end_c: char, include: bool) {
120    // Find the largest encompasing object, or if there is none, find the next one.
121    let cursor = editor.cursor();
122    let (start, end) = editor.with_buffer(|buffer| {
123        // Search forwards for isolated end character, counting start and end characters found
124        let mut end = cursor;
125        let mut starts = 0;
126        let mut ends = 0;
127        'find_end: loop {
128            let line = &buffer.lines[end.line];
129            let text = line.text();
130            for (i, c) in text[end.index..].char_indices() {
131                if c == end_c {
132                    ends += 1;
133                } else if c == start_c {
134                    starts += 1;
135                }
136                if ends > starts {
137                    end.index += if include { i + c.len_utf8() } else { i };
138                    break 'find_end;
139                }
140            }
141            if end.line + 1 < buffer.lines.len() {
142                end.line += 1;
143                end.index = 0;
144            } else {
145                break 'find_end;
146            }
147        }
148
149        // Search backwards to resolve starts and ends
150        let mut start = cursor;
151        'find_start: loop {
152            let line = &buffer.lines[start.line];
153            let text = line.text();
154            for (i, c) in text[..start.index].char_indices().rev() {
155                if c == start_c {
156                    starts += 1;
157                } else if c == end_c {
158                    ends += 1;
159                }
160                if starts >= ends {
161                    start.index = if include { i } else { i + c.len_utf8() };
162                    break 'find_start;
163                }
164            }
165            if start.line > 0 {
166                start.line -= 1;
167                start.index = buffer.lines[start.line].text().len();
168            } else {
169                break 'find_start;
170            }
171        }
172
173        (start, end)
174    });
175
176    editor.set_selection(Selection::Normal(start));
177    editor.set_cursor(end);
178}
179
180#[derive(Debug)]
181pub struct ViEditor<'syntax_system, 'buffer> {
182    editor: SyntaxEditor<'syntax_system, 'buffer>,
183    parser: ViParser,
184    passthrough: bool,
185    registers: BTreeMap<char, (Selection, String)>,
186    search_opt: Option<(String, bool)>,
187    commands: cosmic_undo_2::Commands<Change>,
188    changed: bool,
189    save_pivot: Option<usize>,
190}
191
192impl<'syntax_system, 'buffer> ViEditor<'syntax_system, 'buffer> {
193    pub fn new(editor: SyntaxEditor<'syntax_system, 'buffer>) -> Self {
194        Self {
195            editor,
196            parser: ViParser::new(),
197            passthrough: false,
198            registers: BTreeMap::new(),
199            search_opt: None,
200            commands: cosmic_undo_2::Commands::new(),
201            changed: false,
202            save_pivot: None,
203        }
204    }
205
206    /// Modifies the theme of the [`SyntaxEditor`], returning false if the theme is missing
207    pub fn update_theme(&mut self, theme_name: &str) -> bool {
208        self.editor.update_theme(theme_name)
209    }
210
211    /// Load text from a file, and also set syntax to the best option
212    ///
213    /// ## Errors
214    /// Returns an `io::Error` if reading the file fails
215    #[cfg(feature = "std")]
216    pub fn load_text<P: AsRef<std::path::Path>>(
217        &mut self,
218        font_system: &mut FontSystem,
219        path: P,
220        attrs: crate::Attrs,
221    ) -> std::io::Result<()> {
222        self.editor.load_text(font_system, path, attrs)
223    }
224
225    /// Get the default background color
226    pub fn background_color(&self) -> Color {
227        self.editor.background_color()
228    }
229
230    /// Get the default foreground (text) color
231    pub fn foreground_color(&self) -> Color {
232        self.editor.foreground_color()
233    }
234
235    /// Get the default cursor color
236    pub fn cursor_color(&self) -> Color {
237        self.editor.cursor_color()
238    }
239
240    /// Get the default selection color
241    pub fn selection_color(&self) -> Color {
242        self.editor.selection_color()
243    }
244
245    /// Get the current syntect theme
246    pub fn theme(&self) -> &SyntaxTheme {
247        self.editor.theme()
248    }
249
250    /// Get changed flag
251    pub fn changed(&self) -> bool {
252        self.changed
253    }
254
255    /// Set changed flag
256    pub fn set_changed(&mut self, changed: bool) {
257        self.changed = changed;
258    }
259
260    /// Set current change as the save (or pivot) point.
261    ///
262    /// A pivot point is the last saved index. Anything before or after the pivot indicates that
263    /// the editor has been changed or is unsaved.
264    ///
265    /// Undoing changes down to the pivot point sets the editor as unchanged.
266    /// Redoing changes up to the pivot point sets the editor as unchanged.
267    ///
268    /// Undoing or redoing changes beyond the pivot point sets the editor to changed.
269    pub fn save_point(&mut self) {
270        self.save_pivot = Some(self.commands.current_command_index().unwrap_or_default());
271        self.changed = false;
272    }
273
274    /// Set passthrough mode (true will turn off vi features)
275    pub fn set_passthrough(&mut self, passthrough: bool) {
276        if passthrough != self.passthrough {
277            self.passthrough = passthrough;
278            self.with_buffer_mut(|buffer| buffer.set_redraw(true));
279        }
280    }
281
282    /// Get current vi parser
283    pub fn parser(&self) -> &ViParser {
284        &self.parser
285    }
286
287    /// Redo a change
288    pub fn redo(&mut self) {
289        log::debug!("Redo");
290        for action in self.commands.redo() {
291            undo_2_action(&mut self.editor, action);
292        }
293        self.changed = eval_changed(&self.commands, self.save_pivot);
294    }
295
296    /// Undo a change
297    pub fn undo(&mut self) {
298        log::debug!("Undo");
299        for action in self.commands.undo() {
300            undo_2_action(&mut self.editor, action);
301        }
302        self.changed = eval_changed(&self.commands, self.save_pivot);
303    }
304
305    #[cfg(feature = "swash")]
306    pub fn draw<F>(&self, font_system: &mut FontSystem, cache: &mut crate::SwashCache, callback: F)
307    where
308        F: FnMut(i32, i32, u32, u32, Color),
309    {
310        let mut renderer = crate::LegacyRenderer {
311            font_system,
312            cache,
313            callback,
314        };
315        self.render(&mut renderer);
316    }
317
318    pub fn render<R: Renderer>(&self, renderer: &mut R) {
319        let background_color = self.background_color();
320        let foreground_color = self.foreground_color();
321        let cursor_color = self.cursor_color();
322        let selection_color = self.selection_color();
323        self.with_buffer(|buffer| {
324            let size = buffer.size();
325            if let Some(width) = size.0 {
326                if let Some(height) = size.1 {
327                    renderer.rectangle(0, 0, width as u32, height as u32, background_color);
328                }
329            }
330            let font_size = buffer.metrics().font_size;
331            for run in buffer.layout_runs() {
332                let line_i = run.line_i;
333                let line_y = run.line_y;
334                let line_top = run.line_top;
335                let line_height = run.line_height;
336
337                let cursor_glyph_opt = |cursor: &Cursor| -> Option<(usize, f32, f32)> {
338                    //TODO: better calculation of width
339                    let default_width = font_size / 2.0;
340                    if cursor.line == line_i {
341                        for (glyph_i, glyph) in run.glyphs.iter().enumerate() {
342                            if cursor.index >= glyph.start && cursor.index < glyph.end {
343                                // Guess x offset based on characters
344                                let mut before = 0;
345                                let mut total = 0;
346
347                                let cluster = &run.text[glyph.start..glyph.end];
348                                for (i, _) in cluster.grapheme_indices(true) {
349                                    if glyph.start + i < cursor.index {
350                                        before += 1;
351                                    }
352                                    total += 1;
353                                }
354
355                                let width = glyph.w / (total as f32);
356                                let offset = (before as f32) * width;
357                                return Some((glyph_i, offset, width));
358                            }
359                        }
360                        match run.glyphs.last() {
361                            Some(glyph) => {
362                                if cursor.index == glyph.end {
363                                    return Some((run.glyphs.len(), 0.0, default_width));
364                                }
365                            }
366                            None => {
367                                return Some((0, 0.0, default_width));
368                            }
369                        }
370                    }
371                    None
372                };
373
374                // Highlight selection
375                if let Some((start, end)) = self.selection_bounds() {
376                    if line_i >= start.line && line_i <= end.line {
377                        let mut range_opt = None;
378                        for glyph in run.glyphs.iter() {
379                            // Guess x offset based on characters
380                            let cluster = &run.text[glyph.start..glyph.end];
381                            let total = cluster.grapheme_indices(true).count();
382                            let mut c_x = glyph.x;
383                            let c_w = glyph.w / total as f32;
384                            for (i, c) in cluster.grapheme_indices(true) {
385                                let c_start = glyph.start + i;
386                                let c_end = glyph.start + i + c.len();
387                                if (start.line != line_i || c_end > start.index)
388                                    && (end.line != line_i || c_start < end.index)
389                                {
390                                    range_opt = match range_opt.take() {
391                                        Some((min, max)) => Some((
392                                            cmp::min(min, c_x as i32),
393                                            cmp::max(max, (c_x + c_w) as i32),
394                                        )),
395                                        None => Some((c_x as i32, (c_x + c_w) as i32)),
396                                    };
397                                } else if let Some((min, max)) = range_opt.take() {
398                                    renderer.rectangle(
399                                        min,
400                                        line_top as i32,
401                                        cmp::max(0, max - min) as u32,
402                                        line_height as u32,
403                                        selection_color,
404                                    );
405                                }
406                                c_x += c_w;
407                            }
408                        }
409
410                        if run.glyphs.is_empty() && end.line > line_i {
411                            // Highlight all of internal empty lines
412                            range_opt = Some((0, buffer.size().0.unwrap_or(0.0) as i32));
413                        }
414
415                        if let Some((mut min, mut max)) = range_opt.take() {
416                            if end.line > line_i {
417                                // Draw to end of line
418                                if run.rtl {
419                                    min = 0;
420                                } else {
421                                    max = buffer.size().0.unwrap_or(0.0) as i32;
422                                }
423                            }
424                            renderer.rectangle(
425                                min,
426                                line_top as i32,
427                                cmp::max(0, max - min) as u32,
428                                line_height as u32,
429                                selection_color,
430                            );
431                        }
432                    }
433                }
434
435                // Draw cursor
436                if let Some((cursor_glyph, cursor_glyph_offset, cursor_glyph_width)) =
437                    cursor_glyph_opt(&self.cursor())
438                {
439                    let block_cursor = if self.passthrough {
440                        false
441                    } else {
442                        match self.parser.mode {
443                            ViMode::Insert | ViMode::Replace => false,
444                            _ => true, /*TODO: determine block cursor in other modes*/
445                        }
446                    };
447
448                    let (start_x, end_x) = match run.glyphs.get(cursor_glyph) {
449                        Some(glyph) => {
450                            // Start of detected glyph
451                            if glyph.level.is_rtl() {
452                                (
453                                    (glyph.x + glyph.w - cursor_glyph_offset) as i32,
454                                    (glyph.x + glyph.w - cursor_glyph_offset - cursor_glyph_width)
455                                        as i32,
456                                )
457                            } else {
458                                (
459                                    (glyph.x + cursor_glyph_offset) as i32,
460                                    (glyph.x + cursor_glyph_offset + cursor_glyph_width) as i32,
461                                )
462                            }
463                        }
464                        None => match run.glyphs.last() {
465                            Some(glyph) => {
466                                // End of last glyph
467                                if glyph.level.is_rtl() {
468                                    (glyph.x as i32, (glyph.x - cursor_glyph_width) as i32)
469                                } else {
470                                    (
471                                        (glyph.x + glyph.w) as i32,
472                                        (glyph.x + glyph.w + cursor_glyph_width) as i32,
473                                    )
474                                }
475                            }
476                            None => {
477                                // Start of empty line
478                                (0, cursor_glyph_width as i32)
479                            }
480                        },
481                    };
482
483                    if block_cursor {
484                        let left_x = cmp::min(start_x, end_x);
485                        let right_x = cmp::max(start_x, end_x);
486                        renderer.rectangle(
487                            left_x,
488                            line_top as i32,
489                            (right_x - left_x) as u32,
490                            line_height as u32,
491                            selection_color,
492                        );
493                    } else {
494                        renderer.rectangle(
495                            start_x,
496                            line_top as i32,
497                            1,
498                            line_height as u32,
499                            cursor_color,
500                        );
501                    }
502                }
503
504                for glyph in run.glyphs.iter() {
505                    let physical_glyph = glyph.physical((0., line_y), 1.0);
506
507                    let glyph_color = match glyph.color_opt {
508                        Some(some) => some,
509                        None => foreground_color,
510                    };
511
512                    renderer.glyph(physical_glyph, glyph_color);
513                }
514            }
515        });
516    }
517}
518
519impl<'buffer> Edit<'buffer> for ViEditor<'_, 'buffer> {
520    fn buffer_ref(&self) -> &BufferRef<'buffer> {
521        self.editor.buffer_ref()
522    }
523
524    fn buffer_ref_mut(&mut self) -> &mut BufferRef<'buffer> {
525        self.editor.buffer_ref_mut()
526    }
527
528    fn cursor(&self) -> Cursor {
529        self.editor.cursor()
530    }
531
532    fn set_cursor(&mut self, cursor: Cursor) {
533        self.editor.set_cursor(cursor);
534    }
535
536    fn selection(&self) -> Selection {
537        self.editor.selection()
538    }
539
540    fn set_selection(&mut self, selection: Selection) {
541        self.editor.set_selection(selection);
542    }
543
544    fn auto_indent(&self) -> bool {
545        self.editor.auto_indent()
546    }
547
548    fn set_auto_indent(&mut self, auto_indent: bool) {
549        self.editor.set_auto_indent(auto_indent);
550    }
551
552    fn tab_width(&self) -> u16 {
553        self.editor.tab_width()
554    }
555
556    fn set_tab_width(&mut self, font_system: &mut FontSystem, tab_width: u16) {
557        self.editor.set_tab_width(font_system, tab_width);
558    }
559
560    fn shape_as_needed(&mut self, font_system: &mut FontSystem, prune: bool) {
561        self.editor.shape_as_needed(font_system, prune);
562    }
563
564    fn delete_range(&mut self, start: Cursor, end: Cursor) {
565        self.editor.delete_range(start, end);
566    }
567
568    fn insert_at(&mut self, cursor: Cursor, data: &str, attrs_list: Option<AttrsList>) -> Cursor {
569        self.editor.insert_at(cursor, data, attrs_list)
570    }
571
572    fn copy_selection(&self) -> Option<String> {
573        self.editor.copy_selection()
574    }
575
576    fn delete_selection(&mut self) -> bool {
577        self.editor.delete_selection()
578    }
579
580    fn apply_change(&mut self, change: &Change) -> bool {
581        self.editor.apply_change(change)
582    }
583
584    fn start_change(&mut self) {
585        self.editor.start_change();
586    }
587
588    fn finish_change(&mut self) -> Option<Change> {
589        finish_change(
590            &mut self.editor,
591            &mut self.commands,
592            &mut self.changed,
593            self.save_pivot,
594        )
595    }
596
597    fn action(&mut self, font_system: &mut FontSystem, action: Action) {
598        log::debug!("Action {action:?}");
599
600        let editor = &mut self.editor;
601
602        // Ensure a change is always started
603        editor.start_change();
604
605        if self.passthrough {
606            editor.action(font_system, action);
607            // Always finish change when passing through (TODO: group changes)
608            finish_change(
609                editor,
610                &mut self.commands,
611                &mut self.changed,
612                self.save_pivot,
613            );
614            return;
615        }
616
617        let key = match action {
618            //TODO: this leaves lots of room for issues in translation, should we directly accept Key?
619            Action::Backspace => Key::Backspace,
620            Action::Delete => Key::Delete,
621            Action::Motion(Motion::Down) => Key::Down,
622            Action::Motion(Motion::End) => Key::End,
623            Action::Enter => Key::Enter,
624            Action::Escape => Key::Escape,
625            Action::Motion(Motion::Home) => Key::Home,
626            Action::Indent => Key::Tab,
627            Action::Insert(c) => Key::Char(c),
628            Action::Motion(Motion::Left) => Key::Left,
629            Action::Motion(Motion::PageDown) => Key::PageDown,
630            Action::Motion(Motion::PageUp) => Key::PageUp,
631            Action::Motion(Motion::Right) => Key::Right,
632            Action::Unindent => Key::Backtab,
633            Action::Motion(Motion::Up) => Key::Up,
634            _ => {
635                log::debug!("Pass through action {action:?}");
636                editor.action(font_system, action);
637                // Always finish change when passing through (TODO: group changes)
638                finish_change(
639                    editor,
640                    &mut self.commands,
641                    &mut self.changed,
642                    self.save_pivot,
643                );
644                return;
645            }
646        };
647
648        let has_selection = !matches!(editor.selection(), Selection::None);
649
650        self.parser.parse(key, has_selection, |event| {
651            log::debug!("  Event {event:?}");
652            let action = match event {
653                Event::AutoIndent => {
654                    log::info!("TODO: AutoIndent");
655                    return;
656                }
657                Event::Backspace => Action::Backspace,
658                Event::BackspaceInLine => {
659                    let cursor = editor.cursor();
660                    if cursor.index > 0 {
661                        Action::Backspace
662                    } else {
663                        return;
664                    }
665                }
666                Event::ChangeStart => {
667                    editor.start_change();
668                    return;
669                }
670                Event::ChangeFinish => {
671                    finish_change(
672                        editor,
673                        &mut self.commands,
674                        &mut self.changed,
675                        self.save_pivot,
676                    );
677                    return;
678                }
679                Event::Delete => Action::Delete,
680                Event::DeleteInLine => {
681                    let cursor = editor.cursor();
682                    if cursor.index
683                        < editor.with_buffer(|buffer| buffer.lines[cursor.line].text().len())
684                    {
685                        Action::Delete
686                    } else {
687                        return;
688                    }
689                }
690                Event::Escape => Action::Escape,
691                Event::Insert(c) => Action::Insert(c),
692                Event::NewLine => Action::Enter,
693                Event::Put { register, after } => {
694                    if let Some((selection, data)) = self.registers.get(&register) {
695                        editor.start_change();
696                        if editor.delete_selection() {
697                            editor.insert_string(data, None);
698                        } else {
699                            match selection {
700                                Selection::None | Selection::Normal(_) | Selection::Word(_) => {
701                                    let mut cursor = editor.cursor();
702                                    if after {
703                                        editor.with_buffer(|buffer| {
704                                            let text = buffer.lines[cursor.line].text();
705                                            if let Some(c) = text[cursor.index..].chars().next() {
706                                                cursor.index += c.len_utf8();
707                                            }
708                                        });
709                                        editor.set_cursor(cursor);
710                                    }
711                                    editor.insert_at(cursor, data, None);
712                                }
713                                Selection::Line(_) => {
714                                    let mut cursor = editor.cursor();
715                                    if after {
716                                        // Insert at next line
717                                        cursor.line += 1;
718                                    } else {
719                                        // Previous line will be moved down, so set cursor to next line
720                                        cursor.line += 1;
721                                        editor.set_cursor(cursor);
722                                        cursor.line -= 1;
723                                    }
724                                    // Insert at start of line
725                                    cursor.index = 0;
726
727                                    // Insert text
728                                    editor.insert_at(cursor, "\n", None);
729                                    editor.insert_at(cursor, data, None);
730
731                                    //TODO: Hack to allow immediate up/down
732                                    editor.shape_as_needed(font_system, false);
733
734                                    // Move to inserted line, preserving cursor x position
735                                    if after {
736                                        editor.action(font_system, Action::Motion(Motion::Down));
737                                    } else {
738                                        editor.action(font_system, Action::Motion(Motion::Up));
739                                    }
740                                }
741                            }
742                        }
743                        finish_change(
744                            editor,
745                            &mut self.commands,
746                            &mut self.changed,
747                            self.save_pivot,
748                        );
749                    }
750                    return;
751                }
752                Event::Redraw => {
753                    editor.with_buffer_mut(|buffer| buffer.set_redraw(true));
754                    return;
755                }
756                Event::SelectClear => {
757                    editor.set_selection(Selection::None);
758                    return;
759                }
760                Event::SelectStart => {
761                    let cursor = editor.cursor();
762                    editor.set_selection(Selection::Normal(cursor));
763                    return;
764                }
765                Event::SelectLineStart => {
766                    let cursor = editor.cursor();
767                    editor.set_selection(Selection::Line(cursor));
768                    return;
769                }
770                Event::SelectTextObject(text_object, include) => {
771                    match text_object {
772                        TextObject::AngleBrackets => select_in(editor, '<', '>', include),
773                        TextObject::CurlyBrackets => select_in(editor, '{', '}', include),
774                        TextObject::DoubleQuotes => select_in(editor, '"', '"', include),
775                        TextObject::Parentheses => select_in(editor, '(', ')', include),
776                        TextObject::Search { forwards } => {
777                            if let Some((value, _)) = &self.search_opt {
778                                if search(editor, value, forwards) {
779                                    let mut cursor = editor.cursor();
780                                    editor.set_selection(Selection::Normal(cursor));
781                                    //TODO: traverse lines if necessary
782                                    cursor.index += value.len();
783                                    editor.set_cursor(cursor);
784                                }
785                            }
786                        }
787                        TextObject::SingleQuotes => select_in(editor, '\'', '\'', include),
788                        TextObject::SquareBrackets => select_in(editor, '[', ']', include),
789                        TextObject::Ticks => select_in(editor, '`', '`', include),
790                        TextObject::Word(word) => {
791                            let mut cursor = editor.cursor();
792                            let mut selection = editor.selection();
793                            editor.with_buffer(|buffer| {
794                                let text = buffer.lines[cursor.line].text();
795                                match WordIter::new(text, word)
796                                    .find(|&(i, w)| i <= cursor.index && i + w.len() > cursor.index)
797                                {
798                                    Some((i, w)) => {
799                                        cursor.index = i;
800                                        selection = Selection::Normal(cursor);
801                                        cursor.index += w.len();
802                                    }
803                                    None => {
804                                        //TODO
805                                    }
806                                }
807                            });
808                            editor.set_selection(selection);
809                            editor.set_cursor(cursor);
810                        }
811                        _ => {
812                            log::info!("TODO: {text_object:?}");
813                        }
814                    }
815                    return;
816                }
817                Event::SetSearch(value, forwards) => {
818                    self.search_opt = Some((value, forwards));
819                    return;
820                }
821                Event::ShiftLeft => Action::Unindent,
822                Event::ShiftRight => Action::Indent,
823                Event::SwapCase => {
824                    log::info!("TODO: SwapCase");
825                    return;
826                }
827                Event::Undo => {
828                    for action in self.commands.undo() {
829                        undo_2_action(editor, action);
830                    }
831                    return;
832                }
833                Event::Yank { register } => {
834                    if let Some(data) = editor.copy_selection() {
835                        self.registers.insert(register, (editor.selection(), data));
836                    }
837                    return;
838                }
839                Event::Motion(motion) => {
840                    match motion {
841                        modit::Motion::Around => {
842                            //TODO: what to do for this psuedo-motion?
843                            return;
844                        }
845                        modit::Motion::Down => Action::Motion(Motion::Down),
846                        modit::Motion::End => Action::Motion(Motion::End),
847                        modit::Motion::GotoLine(line) => {
848                            Action::Motion(Motion::GotoLine(line.saturating_sub(1)))
849                        }
850                        modit::Motion::GotoEof => Action::Motion(Motion::GotoLine(
851                            editor.with_buffer(|buffer| buffer.lines.len().saturating_sub(1)),
852                        )),
853                        modit::Motion::Home => Action::Motion(Motion::Home),
854                        modit::Motion::Inside => {
855                            //TODO: what to do for this psuedo-motion?
856                            return;
857                        }
858                        modit::Motion::Left => Action::Motion(Motion::Left),
859                        modit::Motion::LeftInLine => {
860                            let cursor = editor.cursor();
861                            if cursor.index > 0 {
862                                Action::Motion(Motion::Left)
863                            } else {
864                                return;
865                            }
866                        }
867                        modit::Motion::Line => {
868                            //TODO: what to do for this psuedo-motion?
869                            return;
870                        }
871                        modit::Motion::NextChar(find_c) => {
872                            let mut cursor = editor.cursor();
873                            editor.with_buffer(|buffer| {
874                                let text = buffer.lines[cursor.line].text();
875                                if cursor.index < text.len() {
876                                    if let Some((i, _)) = text[cursor.index..]
877                                        .char_indices()
878                                        .find(|&(i, c)| i > 0 && c == find_c)
879                                    {
880                                        cursor.index += i;
881                                    }
882                                }
883                            });
884                            editor.set_cursor(cursor);
885                            return;
886                        }
887                        modit::Motion::NextCharTill(find_c) => {
888                            let mut cursor = editor.cursor();
889                            editor.with_buffer(|buffer| {
890                                let text = buffer.lines[cursor.line].text();
891                                if cursor.index < text.len() {
892                                    let mut last_i = 0;
893                                    for (i, c) in text[cursor.index..].char_indices() {
894                                        if last_i > 0 && c == find_c {
895                                            cursor.index += last_i;
896                                            break;
897                                        } else {
898                                            last_i = i;
899                                        }
900                                    }
901                                }
902                            });
903                            editor.set_cursor(cursor);
904                            return;
905                        }
906                        modit::Motion::NextSearch => match &self.search_opt {
907                            Some((value, forwards)) => {
908                                search(editor, value, *forwards);
909                                return;
910                            }
911                            None => return,
912                        },
913                        modit::Motion::NextWordEnd(word) => {
914                            let mut cursor = editor.cursor();
915                            editor.with_buffer(|buffer| {
916                                loop {
917                                    let text = buffer.lines[cursor.line].text();
918                                    if cursor.index < text.len() {
919                                        cursor.index = WordIter::new(text, word)
920                                            .map(|(i, w)| {
921                                                i + w
922                                                    .char_indices()
923                                                    .last()
924                                                    .map(|(i, _)| i)
925                                                    .unwrap_or(0)
926                                            })
927                                            .find(|&i| i > cursor.index)
928                                            .unwrap_or(text.len());
929                                        if cursor.index == text.len() {
930                                            // Try again, searching next line
931                                            continue;
932                                        }
933                                    } else if cursor.line + 1 < buffer.lines.len() {
934                                        // Go to next line and rerun loop
935                                        cursor.line += 1;
936                                        cursor.index = 0;
937                                        continue;
938                                    }
939                                    break;
940                                }
941                            });
942                            editor.set_cursor(cursor);
943                            return;
944                        }
945                        modit::Motion::NextWordStart(word) => {
946                            let mut cursor = editor.cursor();
947                            editor.with_buffer(|buffer| {
948                                loop {
949                                    let text = buffer.lines[cursor.line].text();
950                                    if cursor.index < text.len() {
951                                        cursor.index = WordIter::new(text, word)
952                                            .map(|(i, _)| i)
953                                            .find(|&i| i > cursor.index)
954                                            .unwrap_or(text.len());
955                                        if cursor.index == text.len() {
956                                            // Try again, searching next line
957                                            continue;
958                                        }
959                                    } else if cursor.line + 1 < buffer.lines.len() {
960                                        // Go to next line and rerun loop
961                                        cursor.line += 1;
962                                        cursor.index = 0;
963                                        continue;
964                                    }
965                                    break;
966                                }
967                            });
968                            editor.set_cursor(cursor);
969                            return;
970                        }
971                        modit::Motion::PageDown => Action::Motion(Motion::PageDown),
972                        modit::Motion::PageUp => Action::Motion(Motion::PageUp),
973                        modit::Motion::PreviousChar(find_c) => {
974                            let mut cursor = editor.cursor();
975                            editor.with_buffer(|buffer| {
976                                let text = buffer.lines[cursor.line].text();
977                                if cursor.index > 0 {
978                                    if let Some((i, _)) = text[..cursor.index]
979                                        .char_indices()
980                                        .rfind(|&(_, c)| c == find_c)
981                                    {
982                                        cursor.index = i;
983                                    }
984                                }
985                            });
986                            editor.set_cursor(cursor);
987                            return;
988                        }
989                        modit::Motion::PreviousCharTill(find_c) => {
990                            let mut cursor = editor.cursor();
991                            editor.with_buffer(|buffer| {
992                                let text = buffer.lines[cursor.line].text();
993                                if cursor.index > 0 {
994                                    if let Some(i) = text[..cursor.index]
995                                        .char_indices()
996                                        .filter_map(|(i, c)| {
997                                            if c == find_c {
998                                                let end = i + c.len_utf8();
999                                                if end < cursor.index {
1000                                                    return Some(end);
1001                                                }
1002                                            }
1003                                            None
1004                                        })
1005                                        .next_back()
1006                                    {
1007                                        cursor.index = i;
1008                                    }
1009                                }
1010                            });
1011                            editor.set_cursor(cursor);
1012                            return;
1013                        }
1014                        modit::Motion::PreviousSearch => match &self.search_opt {
1015                            Some((value, forwards)) => {
1016                                search(editor, value, !*forwards);
1017                                return;
1018                            }
1019                            None => return,
1020                        },
1021                        modit::Motion::PreviousWordEnd(word) => {
1022                            let mut cursor = editor.cursor();
1023                            editor.with_buffer(|buffer| {
1024                                loop {
1025                                    let text = buffer.lines[cursor.line].text();
1026                                    if cursor.index > 0 {
1027                                        cursor.index = WordIter::new(text, word)
1028                                            .map(|(i, w)| {
1029                                                i + w
1030                                                    .char_indices()
1031                                                    .last()
1032                                                    .map(|(i, _)| i)
1033                                                    .unwrap_or(0)
1034                                            })
1035                                            .filter(|&i| i < cursor.index)
1036                                            .last()
1037                                            .unwrap_or(0);
1038                                        if cursor.index == 0 {
1039                                            // Try again, searching previous line
1040                                            continue;
1041                                        }
1042                                    } else if cursor.line > 0 {
1043                                        // Go to previous line and rerun loop
1044                                        cursor.line -= 1;
1045                                        cursor.index = buffer.lines[cursor.line].text().len();
1046                                        continue;
1047                                    }
1048                                    break;
1049                                }
1050                            });
1051                            editor.set_cursor(cursor);
1052                            return;
1053                        }
1054                        modit::Motion::PreviousWordStart(word) => {
1055                            let mut cursor = editor.cursor();
1056                            editor.with_buffer(|buffer| {
1057                                loop {
1058                                    let text = buffer.lines[cursor.line].text();
1059                                    if cursor.index > 0 {
1060                                        cursor.index = WordIter::new(text, word)
1061                                            .map(|(i, _)| i)
1062                                            .filter(|&i| i < cursor.index)
1063                                            .last()
1064                                            .unwrap_or(0);
1065                                        if cursor.index == 0 {
1066                                            // Try again, searching previous line
1067                                            continue;
1068                                        }
1069                                    } else if cursor.line > 0 {
1070                                        // Go to previous line and rerun loop
1071                                        cursor.line -= 1;
1072                                        cursor.index = buffer.lines[cursor.line].text().len();
1073                                        continue;
1074                                    }
1075                                    break;
1076                                }
1077                            });
1078                            editor.set_cursor(cursor);
1079                            return;
1080                        }
1081                        modit::Motion::Right => Action::Motion(Motion::Right),
1082                        modit::Motion::RightInLine => {
1083                            let cursor = editor.cursor();
1084                            if cursor.index
1085                                < editor
1086                                    .with_buffer(|buffer| buffer.lines[cursor.line].text().len())
1087                            {
1088                                Action::Motion(Motion::Right)
1089                            } else {
1090                                return;
1091                            }
1092                        }
1093                        modit::Motion::ScreenHigh => {
1094                            //TODO: is this efficient?
1095                            if let Some(line_i) = editor.with_buffer(|buffer| {
1096                                buffer.layout_runs().next().map(|first| first.line_i)
1097                            }) {
1098                                Action::Motion(Motion::GotoLine(line_i))
1099                            } else {
1100                                return;
1101                            }
1102                        }
1103                        modit::Motion::ScreenLow => {
1104                            //TODO: is this efficient?
1105                            if let Some(line_i) = editor.with_buffer(|buffer| {
1106                                buffer.layout_runs().last().map(|last| last.line_i)
1107                            }) {
1108                                Action::Motion(Motion::GotoLine(line_i))
1109                            } else {
1110                                return;
1111                            }
1112                        }
1113                        modit::Motion::ScreenMiddle => {
1114                            //TODO: is this efficient?
1115                            let action_opt = editor.with_buffer(|buffer| {
1116                                let mut layout_runs = buffer.layout_runs();
1117
1118                                match (layout_runs.next(), layout_runs.last()) {
1119                                    (Some(first), Some(last)) => Some(Action::Motion(
1120                                        Motion::GotoLine((last.line_i + first.line_i) / 2),
1121                                    )),
1122                                    _ => None,
1123                                }
1124                            });
1125                            match action_opt {
1126                                Some(action) => action,
1127                                None => return,
1128                            }
1129                        }
1130                        modit::Motion::Selection => {
1131                            //TODO: what to do for this psuedo-motion?
1132                            return;
1133                        }
1134                        modit::Motion::SoftHome => Action::Motion(Motion::SoftHome),
1135                        modit::Motion::Up => Action::Motion(Motion::Up),
1136                    }
1137                }
1138            };
1139            editor.action(font_system, action);
1140        });
1141    }
1142
1143    fn cursor_position(&self) -> Option<(i32, i32)> {
1144        self.editor.cursor_position()
1145    }
1146}
1147
1148impl BorrowedWithFontSystem<'_, ViEditor<'_, '_>> {
1149    /// Load text from a file, and also set syntax to the best option
1150    ///
1151    /// ## Errors
1152    /// Returns an `io::Error` if reading the file fails
1153    #[cfg(feature = "std")]
1154    pub fn load_text<P: AsRef<std::path::Path>>(
1155        &mut self,
1156        path: P,
1157        attrs: crate::Attrs,
1158    ) -> std::io::Result<()> {
1159        self.inner.load_text(self.font_system, path, attrs)
1160    }
1161
1162    #[cfg(feature = "swash")]
1163    pub fn draw<F>(&mut self, cache: &mut crate::SwashCache, f: F)
1164    where
1165        F: FnMut(i32, i32, u32, u32, Color),
1166    {
1167        self.inner.draw(self.font_system, cache, f);
1168    }
1169}