idet-core 0.4.0

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
//! 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::{
    completion, edits,
    lineops::{self, LineMove, Segment},
    options::Options,
    syntax::{Class, Syntax},
    wordops::{self, WordSwap},
};

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,
    words: Vec<String>,
    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,
            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);
    }

    /// 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)
            .into_iter()
            .map(|(word, _)| word)
            .collect();
    }

    /// 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));
    }

    /// 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,
    ) -> egui::text_edit::TextEditOutput {
        let syntax = self.syntax.as_ref();
        let row_height = ui.text_style_height(&TextStyle::Monospace);
        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))
                })
            };
            EguiTextEdit::multiline(text)
                .id(editor_id)
                .code_editor()
                .desired_width(desired_width)
                .desired_rows(rows)
                .layouter(&mut layouter)
                .show(ui)
        };
        if let Some(rows) = self.rows {
            return draw(ui, rows);
        }
        let rows = (ui.available_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 [
            (Modifiers::ALT, Segment::Line),
            (alt_shift(), Segment::Block),
            (alt_ctrl(), Segment::Section),
            (alt_shift_ctrl(), Segment::Section),
        ] {
            for (key, direction) in [
                (Key::ArrowUp, LineMove::Up),
                (Key::ArrowDown, LineMove::Down),
            ] {
                if ctx.input_mut(|i| i.consume_key(modifiers, key))
                    && 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)> {
        if has_focus && ctx.input_mut(|i| i.consume_key(Modifiers::CTRL, Key::F)) {
            let selected = self.selected_text(text);
            self.search.open(selected, false);
        }
        if has_focus && 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(Modifiers::CTRL, Key::G)) {
            return self
                .search
                .jump_to_match(text, self.cursor, self.anchor, 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);
        }
        None
    }

    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)
    }

    /// 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);
        }
        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((cursor, anchor)) = self.pending_external.take() {
            pending = Some((anchor, cursor));
        }

        let output = self.draw_text(ui, text, editor_id);

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

        let changed = response.changed();
        if let Some((start, end)) = pending {
            let mut state = output.state;
            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(ui.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();
        }

        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,
            },
        )
    }
}