idet-core 0.4.1

Editing logic for text editors, without a frontend
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
//! An egui text-editing widget wrapping `egui::TextEdit`.
//!
//! Adds the shared editing behavior from [`crate::lineops`],
//! [`crate::wordops`], [`crate::edits`] and [`crate::completion`]:
//! move-line, swap-word, indent/dedent, auto-indent on enter, word
//! autocomplete and find.
//!
//! The widget owns no application state beyond the text buffer it is given
//! each frame — no save/undo/reload, no window chrome. Those stay the
//! host application's responsibility.

mod search;
mod suggest;

use std::ops::Range;

use egui::{
    Color32, Context, FontId, Id, Key, Modifiers, ScrollArea, TextEdit as EguiTextEdit, TextFormat,
    TextStyle, Ui,
    text::{CCursor, CCursorRange, LayoutJob, LayoutSection, TextWrapping},
};
use search::Search;
use suggest::Suggest;

use crate::{
    carets, completion, edits,
    lineops::{self, LineMove, Segment},
    options::Options,
    syntax::{Class, Syntax},
    wordops::{self, WordSwap},
};

fn mark_match(
    ui: &Ui,
    output: &egui::text_edit::TextEditOutput,
    (start, end): (usize, usize),
    follow: bool,
) {
    let offset = output.galley_pos.to_vec2();
    let galley = &output.galley;
    let from = galley
        .pos_from_cursor(CCursor::new(start.min(end)))
        .translate(offset);
    let to = galley
        .pos_from_cursor(CCursor::new(start.max(end)))
        .translate(offset);
    let rect = from.union(to);
    let selection = ui.visuals().selection;
    ui.painter().rect(
        rect,
        2.0,
        selection.bg_fill.gamma_multiply(0.5),
        egui::Stroke::new(1.0, selection.stroke.color),
        egui::StrokeKind::Inside,
    );
    if follow {
        ui.scroll_to_rect(rect, Some(egui::Align::Center));
    }
}

fn mark_carets(ui: &Ui, output: &egui::text_edit::TextEditOutput, carets: &[usize]) {
    if carets.is_empty() {
        return;
    }
    let offset = output.galley_pos.to_vec2();
    let stroke = ui.visuals().text_cursor.stroke;
    for caret in carets {
        let rect = output
            .galley
            .pos_from_cursor(CCursor::new(*caret))
            .translate(offset);
        ui.painter()
            .line_segment([rect.left_top(), rect.left_bottom()], stroke);
    }
}

fn page_step(ctx: &Context) -> Option<(f32, bool)> {
    for (key, direction) in [(Key::PageDown, 1.0), (Key::PageUp, -1.0)] {
        if ctx.input_mut(|input| input.consume_key(Modifiers::NONE, key)) {
            return Some((direction, false));
        }
        if ctx.input_mut(|input| input.consume_key(Modifiers::SHIFT, key)) {
            return Some((direction, true));
        }
    }
    None
}

fn page_move(
    ui: &Ui,
    output: &egui::text_edit::TextEditOutput,
    direction: f32,
    height: f32,
) -> Option<usize> {
    let galley = &output.galley;
    let primary = output.cursor_range?.primary;
    let here = galley.pos_from_cursor(primary).center();
    let moved = galley.cursor_from_pos(egui::vec2(here.x, direction.mul_add(height, here.y)));
    let rect = galley
        .pos_from_cursor(moved)
        .translate(output.galley_pos.to_vec2());
    ui.scroll_to_rect(rect, None);
    Some(moved.index.into())
}

const fn shift_ctrl() -> Modifiers {
    Modifiers {
        ctrl: true,
        shift: true,
        ..Modifiers::NONE
    }
}

const fn alt_shift() -> Modifiers {
    Modifiers {
        alt: true,
        shift: true,
        ..Modifiers::NONE
    }
}

const fn alt_ctrl() -> Modifiers {
    Modifiers {
        alt: true,
        ctrl: true,
        ..Modifiers::NONE
    }
}

const fn alt_shift_ctrl() -> Modifiers {
    Modifiers {
        alt: true,
        shift: true,
        ctrl: true,
        ..Modifiers::NONE
    }
}

/// A multi-line text editor widget with move-line, swap-word,
/// indent/dedent, auto-indent, word autocomplete and find, built on top of
/// `egui::TextEdit`.
///
/// Create one per editable document and keep it alive across frames — it
/// tracks the cursor, the selection anchor, the word list for autocomplete
/// and the find prompt.
pub struct TextEditor {
    id: u64,
    cursor: usize,
    anchor: usize,
    extra: Vec<usize>,
    words: Vec<(String, usize)>,
    suggest: Suggest,
    search: Search,
    pending_external: Option<(usize, usize)>,
    options: Options,
    autofocus: bool,
    syntax: Option<Syntax>,
    rows: Option<usize>,
}

const fn class_color(class: Class) -> Color32 {
    match class {
        Class::Comment => Color32::GRAY,
        Class::String => Color32::from_rgb(140, 200, 120),
        Class::Keyword => Color32::from_rgb(200, 140, 220),
        Class::Type => Color32::from_rgb(120, 190, 200),
        Class::Number => Color32::from_rgb(220, 200, 120),
    }
}

fn layout_job(ui: &Ui, text: &str, syntax: Option<&Syntax>, wrap_width: f32) -> LayoutJob {
    let font = ui
        .style()
        .text_styles
        .get(&TextStyle::Monospace)
        .cloned()
        .unwrap_or_else(|| FontId::monospace(12.0));
    let plain = ui.visuals().text_color();
    let format = |color| TextFormat {
        font_id: font.clone(),
        color,
        ..TextFormat::default()
    };
    let mut job = LayoutJob {
        text: text.to_owned(),
        wrap: TextWrapping {
            max_width: wrap_width,
            ..TextWrapping::default()
        },
        ..LayoutJob::default()
    };
    let mut section = |byte_range: Range<usize>, color| {
        job.sections.push(LayoutSection {
            leading_space: 0.0,
            byte_range: byte_range.start.into()..byte_range.end.into(),
            format: format(color),
        });
    };
    let mut index = 0;
    for (range, class) in syntax.map(|syntax| syntax.spans(text)).unwrap_or_default() {
        if range.start > index {
            section(index..range.start, plain);
        }
        index = range.end;
        section(range, class_color(class));
    }
    if index < text.len() {
        section(index..text.len(), plain);
    }
    job
}

/// What happened to the text buffer during a [`TextEditor::show`] call.
#[derive(Default)]
pub struct TextEditorOutput {
    /// Whether the buffer's contents changed this frame.
    pub changed: bool,
}

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

impl TextEditor {
    /// Creates a text editor with the given identity, used to key its egui
    /// widgets. Two editors sharing an id would fight over the same egui
    /// memory slots, so pick something stable and unique per document (a
    /// document id, a tab index, ...).
    #[must_use]
    pub fn new(id: u64) -> Self {
        Self {
            id,
            cursor: 0,
            anchor: 0,
            extra: Vec::new(),
            words: Vec::new(),
            suggest: Suggest::default(),
            search: Search::default(),
            pending_external: None,
            options: Options {
                wrap: false,
                ..Options::default()
            },
            autofocus: true,
            syntax: None,
            rows: None,
        }
    }

    /// Fixes the editor to `rows` text rows instead of filling the height it
    /// is given. A fixed-height editor drops the scroll area around the text,
    /// so a single-row editor takes exactly one row of space — what a form
    /// field or a line-per-widget layout needs, where the scroll area's
    /// minimum height would otherwise space the rows far apart.
    #[must_use]
    pub const fn rows(mut self, rows: usize) -> Self {
        self.rows = Some(rows);
        self
    }

    /// Whether the editor takes the keyboard focus when nothing else holds
    /// it. On by default, so a window whose only widget is an editor is
    /// typable straight away. Turn it off wherever the editor shares its
    /// window with something that reads the keyboard on its own — a tree
    /// with arrow-key navigation, a list with a type-ahead — which would
    /// otherwise never see a key press again once an editor is on screen.
    #[must_use]
    pub const fn autofocus(mut self, autofocus: bool) -> Self {
        self.autofocus = autofocus;
        self
    }

    /// Colours the text by the rules of `syntax`, or leaves it plain when
    /// given [`None`]. Set it whenever the document's path changes, from
    /// [`crate::syntax::for_path`].
    pub fn set_syntax(&mut self, syntax: Option<Syntax>) {
        self.syntax = syntax;
    }

    /// Wraps long lines to the available width instead of scrolling
    /// horizontally. Off by default, matching a code editor's usual
    /// behavior; turn it on for prose-like content.
    #[must_use]
    pub const fn wrap(mut self, wrap: bool) -> Self {
        self.options.wrap = wrap;
        self
    }

    /// Adopts the user's shared [`Options`], overriding what the builder set.
    /// For an application that lets the user change wrapping or indentation
    /// while it runs, and calls this whenever they do.
    pub const fn set_options(&mut self, options: Options) {
        self.options = options;
    }

    /// Opens the find window, or the find-and-replace window when `replacing`
    /// is set. The counterpart to `Ctrl+F` and `Ctrl+H` for a host that offers
    /// the same from a menu.
    pub fn open_find(&mut self, replacing: bool) {
        self.search.open(String::new(), replacing);
    }

    /// Closes the find window if it is up. For a host that keeps one search
    /// for the whole application and has to put down the one it left behind.
    pub const fn close_find(&mut self) {
        self.search.open = false;
    }

    /// Whether the find window is up, so a host that shares the search term
    /// between several editors knows which one the user is typing in.
    #[must_use]
    pub const fn searching(&self) -> bool {
        self.search.open
    }

    /// What this editor last searched for and what it would replace it with.
    #[must_use]
    pub fn search_terms(&self) -> (&str, &str) {
        (&self.search.term, &self.search.replacement)
    }

    /// Hands this editor a search term and replacement from elsewhere, so a
    /// find opened here starts from what was searched for last rather than
    /// from nothing. `Ctrl+G` repeats it as well.
    pub fn set_search_terms(&mut self, term: &str, replacement: &str) {
        term.clone_into(&mut self.search.term);
        replacement.clone_into(&mut self.search.replacement);
        if !term.is_empty() {
            self.search.last_term = Some(term.to_owned());
        }
    }

    /// Rebuilds the word list used for autocomplete from the current text.
    /// Call this after the text changes from outside this widget (loading a
    /// file, undo/redo, an external edit) so suggestions stay in sync.
    pub fn refresh_words(&mut self, text: &str) {
        self.words = completion::collect_words(text);
    }

    /// Clamps the cursor and selection to the bounds of `text`. Call this
    /// after replacing the text buffer wholesale (loading a file, undo/redo,
    /// a disk reload) so the cursor doesn't point past the end.
    pub fn clamp_cursor(&mut self, text: &str) {
        self.cursor = self.cursor.min(text.chars().count());
        self.anchor = self.cursor;
    }

    /// Moves the cursor (and, if `anchor` differs from `cursor`, selects the
    /// range between them) on the next [`TextEditor::show`] call. For host
    /// features outside this widget's scope that still need to reposition
    /// the cursor — a go-to-line prompt, a search results panel.
    pub const fn set_cursor(&mut self, cursor: usize, anchor: usize) {
        self.pending_external = Some((cursor, anchor));
    }

    /// Moves the cursor to the match after the one it sits on, or the one
    /// before it when `forward` is false, and selects it. Does nothing until
    /// something has been searched for.
    ///
    /// The same step `Ctrl+G` and `Ctrl+Shift+G` take, for a host that binds
    /// those keys itself — a menu bar owning the search verbs — and needs to
    /// ask for the step rather than let the widget answer the key.
    pub fn step_match(&mut self, text: &str, forward: bool) {
        if let Some((start, end)) =
            self.search
                .jump_to_match(text, self.cursor, self.anchor, forward)
        {
            self.pending_external = Some((end, start));
        }
    }

    /// Where the cursor sat after the last [`TextEditor::show`], as a
    /// character index into the buffer. The counterpart to
    /// [`TextEditor::set_cursor`], for a host that has to know whether the
    /// cursor is at an edge — moving focus to a neighbouring editor when the
    /// caret leaves this one, for instance.
    #[must_use]
    pub const fn cursor(&self) -> usize {
        self.cursor
    }

    /// Where the selection's other end sat after the last
    /// [`TextEditor::show`]. Equal to [`TextEditor::cursor`] when nothing is
    /// selected.
    #[must_use]
    pub const fn anchor(&self) -> usize {
        self.anchor
    }

    /// Whether this editor holds the keyboard focus. Read it before acting on
    /// a key the editor did not consume, so a host does not react to typing
    /// meant for another widget.
    #[must_use]
    pub fn has_focus(&self, ctx: &Context) -> bool {
        ctx.memory(|memory| memory.has_focus(self.editor_id()))
    }

    /// Gives this editor the keyboard focus. The counterpart to
    /// [`TextEditor::has_focus`], for a host that moves the caret between
    /// editors itself — a row list, a table of one-line fields. Call it
    /// outside the pass that draws the editors, so the widget already holds
    /// the focus when the next frame's key events are handed out and nothing
    /// typed in between is dropped.
    pub fn request_focus(&self, ctx: &Context) {
        ctx.memory_mut(|memory| memory.request_focus(self.editor_id()));
    }

    /// Whether the word-completion popup is open. Read it before acting on
    /// the arrow keys, which the popup uses to walk its list.
    #[must_use]
    pub const fn suggesting(&self) -> bool {
        self.suggest.visible()
    }

    fn editor_id(&self) -> Id {
        Id::new(("idet-core-text-editor", self.id))
    }

    fn draw_text(
        &self,
        ui: &mut Ui,
        text: &mut String,
        editor_id: Id,
        marked: Option<(usize, usize)>,
        follow: bool,
        page: Option<f32>,
    ) -> (egui::text_edit::TextEditOutput, Option<usize>) {
        let syntax = self.syntax.as_ref();
        let row_height = ui.text_style_height(&TextStyle::Monospace);
        let height = self
            .rows
            .map_or_else(|| ui.available_height(), |rows| rows as f32 * row_height);
        let wrap = self.options.wrap;
        let mut draw = |ui: &mut Ui, rows: usize| {
            let desired_width = if wrap {
                ui.available_width()
            } else {
                f32::INFINITY
            };
            let mut layouter = |ui: &Ui, buffer: &dyn egui::TextBuffer, wrap_width: f32| {
                ui.fonts_mut(|fonts| {
                    fonts.layout_job(layout_job(ui, buffer.as_str(), syntax, wrap_width))
                })
            };
            let output = EguiTextEdit::multiline(text)
                .id(editor_id)
                .code_editor()
                .desired_width(desired_width)
                .desired_rows(rows)
                .layouter(&mut layouter)
                .show(ui);
            if let Some(range) = marked {
                mark_match(ui, &output, range, follow);
            }
            mark_carets(ui, &output, &self.extra);
            let paged = page.and_then(|direction| page_move(ui, &output, direction, height));
            (output, paged)
        };
        if let Some(rows) = self.rows {
            return draw(ui, rows);
        }
        let rows = (height / row_height).max(1.0) as usize;
        ScrollArea::vertical()
            .auto_shrink(false)
            .show(ui, |ui| draw(ui, rows))
            .inner
    }

    fn handle_move_and_swap(
        &self,
        ctx: &Context,
        text: &mut String,
        has_focus: bool,
    ) -> (Option<(usize, usize)>, bool) {
        let mut pending = None;
        let mut edited = false;

        if !has_focus {
            return (pending, edited);
        }

        for (modifiers, segment) in [
            (alt_shift_ctrl(), Segment::Section),
            (alt_ctrl(), Segment::Section),
            (alt_shift(), Segment::Block),
            (Modifiers::ALT, Segment::Line),
        ] {
            for (key, direction) in [
                (Key::ArrowUp, LineMove::Up),
                (Key::ArrowDown, LineMove::Down),
            ] {
                if !ctx.input_mut(|i| i.consume_key(modifiers, key)) {
                    continue;
                }
                if self.anchor != self.cursor {
                    if let Some((new_text, (from, to))) =
                        lineops::move_segments(text, (self.anchor, self.cursor), segment, direction)
                    {
                        *text = new_text;
                        pending = Some(if self.anchor <= self.cursor {
                            (from, to)
                        } else {
                            (to, from)
                        });
                        edited = true;
                    }
                } else if let Some((new_text, cursor)) =
                    lineops::move_segment(text, self.cursor, segment, direction)
                {
                    *text = new_text;
                    pending = Some((cursor, cursor));
                    edited = true;
                }
            }
        }

        let selection = (self.cursor, self.anchor);
        if ctx.input_mut(|i| i.consume_key(Modifiers::ALT, Key::ArrowLeft))
            && let Some((new_text, range)) = wordops::swap(text, selection, WordSwap::Prev)
        {
            *text = new_text;
            pending = Some(range);
            edited = true;
        }
        if ctx.input_mut(|i| i.consume_key(Modifiers::ALT, Key::ArrowRight))
            && let Some((new_text, range)) = wordops::swap(text, selection, WordSwap::Next)
        {
            *text = new_text;
            pending = Some(range);
            edited = true;
        }

        (pending, edited)
    }

    fn selected_text(&self, text: &str) -> String {
        if self.anchor == self.cursor {
            return String::new();
        }
        let start = self.cursor.min(self.anchor);
        let end = self.cursor.max(self.anchor);
        text.chars().skip(start).take(end - start).collect()
    }

    fn handle_search_shortcuts(
        &mut self,
        ctx: &Context,
        text: &str,
        has_focus: bool,
    ) -> Option<(usize, usize)> {
        let reachable = has_focus || self.search.open;
        if reachable && ctx.input_mut(|i| i.consume_key(Modifiers::CTRL, Key::F)) {
            let selected = self.selected_text(text);
            self.search.open(selected, false);
        }
        if reachable && ctx.input_mut(|i| i.consume_key(Modifiers::CTRL, Key::H)) {
            let selected = self.selected_text(text);
            self.search.open(selected, true);
        }
        if has_focus && ctx.input_mut(|i| i.consume_key(shift_ctrl(), Key::G)) {
            return self
                .search
                .jump_to_match(text, self.cursor, self.anchor, false);
        }
        if has_focus && ctx.input_mut(|i| i.consume_key(Modifiers::CTRL, Key::G)) {
            return self
                .search
                .jump_to_match(text, self.cursor, self.anchor, true);
        }
        None
    }

    fn stacked(&self, text: &str, down: bool) -> Option<usize> {
        let carets = self.extra.iter().copied().chain([self.cursor]);
        let furthest = if down { carets.max() } else { carets.min() }?;
        let start = edits::line_start_char(text, furthest);
        let column = furthest - start;
        if down {
            let end = edits::line_end_char(text, furthest);
            if end >= text.chars().count() {
                return None;
            }
            let next = end + 1;
            Some((next + column).min(edits::line_end_char(text, next)))
        } else {
            if start == 0 {
                return None;
            }
            let end = start - 1;
            Some((edits::line_start_char(text, end) + column).min(end))
        }
    }

    fn add_caret(&mut self, position: usize) {
        self.extra.push(position);
        self.extra.sort_unstable();
        self.extra.dedup();
    }

    fn repeat_edit(
        &mut self,
        ctx: &Context,
        text: &mut String,
        was: Option<String>,
        before: usize,
        output: &egui::text_edit::TextEditOutput,
        editor_id: Id,
    ) -> bool {
        let Some(edit) = was.and_then(|was| carets::taken(&was, text)) else {
            return false;
        };
        let moved = carets::spread(text, &edit, before, self.cursor, &mut self.extra);
        let mut state = output.state.clone();
        state
            .cursor
            .set_char_range(Some(CCursorRange::one(CCursor::new(moved))));
        state.store(ctx, editor_id);
        self.cursor = moved;
        self.anchor = moved;
        true
    }

    fn handle_caret_shortcuts(&mut self, ctx: &Context, text: &str, has_focus: bool) {
        if !self.extra.is_empty()
            && !self.suggest.visible()
            && ctx.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape))
        {
            self.extra.clear();
            return;
        }
        if !has_focus {
            return;
        }
        for (key, down) in [(Key::ArrowDown, true), (Key::ArrowUp, false)] {
            if ctx.input_mut(|input| input.consume_key(shift_ctrl(), key))
                && let Some(position) = self.stacked(text, down)
            {
                self.add_caret(position);
            }
        }
    }

    fn handle_suggest_navigation(&mut self, ctx: &Context, has_focus: bool) {
        if !has_focus || !self.suggest.visible() {
            return;
        }
        let length = self.suggest.matches.len();
        if self.suggest.selected == 0
            && ctx.input(|i| i.key_pressed(Key::ArrowUp))
            && !ctx.input(|i| i.modifiers.any())
        {
            ctx.input_mut(|i| {
                i.consume_key(Modifiers::NONE, Key::ArrowUp);
            });
            self.suggest.open = false;
            self.suggest.suppressed = true;
        } else if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::ArrowUp)) {
            self.suggest.selected = self.suggest.selected.saturating_sub(1);
        }
        if self.suggest.selected + 1 == length
            && ctx.input(|i| i.key_pressed(Key::ArrowDown))
            && !ctx.input(|i| i.modifiers.any())
        {
            ctx.input_mut(|i| {
                i.consume_key(Modifiers::NONE, Key::ArrowDown);
            });
            self.suggest.open = false;
            self.suggest.suppressed = true;
        } else if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::ArrowDown)) {
            self.suggest.selected += 1;
        }
    }

    fn handle_indent_and_suggest(
        &mut self,
        ctx: &Context,
        text: &mut String,
        has_focus: bool,
    ) -> (Option<(usize, usize)>, bool) {
        let mut pending = None;
        let mut edited = false;

        self.handle_suggest_navigation(ctx, has_focus);

        if !has_focus {
            return (pending, edited);
        }

        if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
            self.suggest.open = false;
            self.suggest.suppressed = true;
        } else if ctx.input(|i| {
            i.events
                .iter()
                .any(|event| matches!(event, egui::Event::Text(_)))
        }) {
            self.suggest.suppressed = false;
        }

        let popup = self.suggest.visible();

        if ctx.input_mut(|i| i.consume_key(Modifiers::CTRL, Key::Tab)) {
            let (new_text, cursor) = edits::dedent_line(text, self.cursor, self.options.tab_width);
            *text = new_text;
            pending = Some((cursor, cursor));
            edited = true;
        } else if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab)) {
            pending = if popup {
                self.suggest.accept(text, self.cursor)
            } else {
                let (new_text, cursor) =
                    edits::indent_line(text, self.cursor, self.options.tab_width);
                *text = new_text;
                edited = true;
                Some((cursor, cursor))
            };
        }

        if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) {
            pending = if popup {
                self.suggest.accept(text, self.cursor)
            } else {
                let (new_text, cursor) = edits::newline_indent(text, self.cursor);
                *text = new_text;
                edited = true;
                Some((cursor, cursor))
            };
        }

        (pending, edited)
    }

    fn page_target(
        &self,
        output: &egui::text_edit::TextEditOutput,
        paged: Option<usize>,
        page: Option<(f32, bool)>,
    ) -> Option<(usize, usize)> {
        let moved = paged?;
        let (_, extend) = page?;
        let anchor = if extend {
            output
                .cursor_range
                .map_or(self.anchor, |range| range.secondary.index.into())
        } else {
            moved
        };
        Some((anchor, moved))
    }

    fn place_cursor(
        &mut self,
        ctx: &Context,
        editor_id: Id,
        output: &egui::text_edit::TextEditOutput,
        pending: Option<(usize, usize)>,
    ) {
        if let Some((start, end)) = pending {
            let mut state = output.state.clone();
            let range = if start == end {
                CCursorRange::one(CCursor::new(start))
            } else {
                CCursorRange::two(CCursor::new(start), CCursor::new(end))
            };
            state.cursor.set_char_range(Some(range));
            state.store(ctx, editor_id);
            self.cursor = end;
            self.anchor = start;
        } else if let Some(range) = output.cursor_range {
            self.cursor = range.primary.index.into();
            self.anchor = range.secondary.index.into();
        }
    }

    /// Draws the editor for one frame and applies any shortcut it consumed.
    /// `text` is the buffer being edited; it is mutated in place by
    /// move-line, swap-word, indent/dedent, auto-indent and accepted
    /// completions. Returns the underlying `egui::Response` from the text
    /// widget alongside whether the buffer changed this frame.
    pub fn show(&mut self, ui: &mut Ui, text: &mut String) -> (egui::Response, TextEditorOutput) {
        let ctx = ui.ctx().clone();
        let mut pending = None;
        let mut edited = false;

        let editor_id = self.editor_id();
        let has_focus = ctx.memory(|memory| memory.has_focus(editor_id));
        let typed = ctx.input(|i| {
            i.events
                .iter()
                .any(|event| matches!(event, egui::Event::Text(_)))
        });

        if let Some(range) = self.handle_search_shortcuts(&ctx, text, has_focus) {
            pending = Some(range);
        }
        self.handle_caret_shortcuts(&ctx, text, has_focus);
        let (move_pending, move_edited) = self.handle_move_and_swap(&ctx, text, has_focus);
        if let Some(range) = move_pending {
            pending = Some(range);
        }
        edited |= move_edited;
        let (indent_pending, indent_edited) = self.handle_indent_and_suggest(&ctx, text, has_focus);
        if let Some(range) = indent_pending {
            pending = Some(range);
        }
        edited |= indent_edited;

        let search = self
            .search
            .draw(&ctx, text, self.cursor, self.anchor, self.id);
        if let Some(range) = search.cursor {
            pending = Some(range);
        }
        edited |= search.edited;
        if let Some((first, rest)) = search.carets.split_first() {
            pending = Some((*first, *first));
            self.extra = rest.to_vec();
        }

        if let Some((cursor, anchor)) = self.pending_external.take() {
            pending = Some((anchor, cursor));
        }

        let marked = (self.search.open && !has_focus)
            .then(|| {
                pending
                    .or_else(|| (self.cursor != self.anchor).then_some((self.anchor, self.cursor)))
            })
            .flatten();
        let before = self.cursor;
        let was = (!self.extra.is_empty()).then(|| text.clone());
        let page = has_focus.then(|| page_step(&ctx)).flatten();
        let (output, paged) = self.draw_text(
            ui,
            text,
            editor_id,
            marked,
            pending.is_some(),
            page.map(|(direction, _)| direction),
        );
        if let Some(range) = self.page_target(&output, paged, page) {
            pending = Some(range);
        }

        let response = output.response.response.clone();
        if self.autofocus && ui.ctx().memory(|m| m.focused().is_none()) {
            response.request_focus();
        }

        let changed = response.changed();
        self.place_cursor(&ctx, editor_id, &output, pending);

        if response.clicked() && ctx.input(|input| input.modifiers.alt) {
            self.add_caret(before);
        }
        edited |= self.repeat_edit(&ctx, text, was, before, &output, editor_id);

        if changed || edited {
            self.refresh_words(text);
        }

        if changed && typed {
            self.suggest.refresh(text, self.cursor, &self.words);
        } else if changed || edited {
            self.suggest.open = false;
        }
        if !response.has_focus() {
            self.suggest.open = false;
        }
        if self.suggest.visible() {
            self.suggest.draw(
                ui.ctx(),
                &output.galley,
                output.galley_pos,
                self.cursor,
                self.id,
            );
        }

        (
            response,
            TextEditorOutput {
                changed: changed || edited,
            },
        )
    }
}