typ-panel-editor 0.2.4

Editor panel for the TYPE terminal IDE
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
//! `Action` → editor behavior.
//!
//! Every mutation of the editor lives here or is called from here. Nothing in
//! `handle_key` touches the buffer, which is what keeps the keymap, the future
//! command palette, and the future vim layer able to reach the same behavior.

use unicode_segmentation::UnicodeSegmentation;

use typ_buffer::{
    EditKind, Position, Selection, Shift, TextBuffer, clipboard, display_to_grapheme_col,
    grapheme_to_display_col, next_word_boundary, previous_word_boundary,
};
use typ_core::{Action, Direction, Motion, PanelEvent};

use crate::{EditorPanel, TAB_WIDTH};

impl EditorPanel {
    /// Move one selection according to a motion.
    ///
    /// `extend` decides whether the anchor follows. A plain move from a
    /// non-empty selection collapses toward the direction of travel rather
    /// than moving from the head, which is the behavior everyone arriving from
    /// a GUI editor has in their fingers.
    fn move_selection(&self, selection: Selection, motion: Motion, extend: bool) -> Selection {
        if !extend && !selection.is_empty() {
            let collapse_to = match motion {
                Motion::Left | Motion::WordLeft | Motion::LineStart | Motion::DocumentStart => {
                    Some(selection.range().0)
                }
                Motion::Right | Motion::WordRight | Motion::LineEnd | Motion::DocumentEnd => {
                    Some(selection.range().1)
                }
                // Vertical motions move from the head rather than collapsing to
                // an end: up and down have no "direction of travel" along the
                // selection to collapse toward.
                _ => None,
            };
            if let Some(target) = collapse_to {
                return Selection::caret(target);
            }
        }

        let head = self.moved_position(selection.head, motion);
        Selection {
            anchor: if extend { selection.anchor } else { head },
            head,
        }
    }

    fn moved_position(&self, from: Position, motion: Motion) -> Position {
        let last_line = self.last_line();

        match motion {
            Motion::Left => {
                if from.col > 0 {
                    Position {
                        line: from.line,
                        col: from.col - 1,
                    }
                } else if from.line > 0 {
                    Position {
                        line: from.line - 1,
                        col: self.line_grapheme_count(from.line - 1),
                    }
                } else {
                    from
                }
            }
            Motion::Right => {
                if from.col < self.line_grapheme_count(from.line) {
                    Position {
                        line: from.line,
                        col: from.col + 1,
                    }
                } else if from.line < last_line {
                    Position {
                        line: from.line + 1,
                        col: 0,
                    }
                } else {
                    from
                }
            }
            Motion::Up => self.vertical(from, -1),
            Motion::Down => self.vertical(from, 1),
            Motion::PageUp => self.vertical(from, -(self.page() as i64)),
            Motion::PageDown => self.vertical(from, self.page() as i64),
            Motion::WordLeft => {
                if from.col == 0 {
                    if from.line == 0 {
                        from
                    } else {
                        Position {
                            line: from.line - 1,
                            col: self.line_grapheme_count(from.line - 1),
                        }
                    }
                } else {
                    let text = self.buffer.line_text(from.line);
                    Position {
                        line: from.line,
                        col: previous_word_boundary(&text, from.col),
                    }
                }
            }
            Motion::WordRight => {
                if from.col >= self.line_grapheme_count(from.line) {
                    if from.line >= last_line {
                        from
                    } else {
                        Position {
                            line: from.line + 1,
                            col: 0,
                        }
                    }
                } else {
                    let text = self.buffer.line_text(from.line);
                    Position {
                        line: from.line,
                        col: next_word_boundary(&text, from.col),
                    }
                }
            }
            Motion::LineStart => Position {
                line: from.line,
                col: 0,
            },
            Motion::LineEnd => Position {
                line: from.line,
                col: self.line_grapheme_count(from.line),
            },
            Motion::DocumentStart => Position { line: 0, col: 0 },
            Motion::DocumentEnd => Position {
                line: last_line,
                col: self.line_grapheme_count(last_line),
            },
        }
    }

    /// Vertical movement, preserving the goal column through short lines.
    fn vertical(&self, from: Position, delta: i64) -> Position {
        let goal = self.goal_col.unwrap_or_else(|| {
            grapheme_to_display_col(&self.buffer.line_text(from.line), from.col, TAB_WIDTH)
        });
        let line = (from.line as i64 + delta).clamp(0, self.last_line() as i64) as usize;
        let col = display_to_grapheme_col(&self.buffer.line_text(line), goal, TAB_WIDTH);
        Position { line, col }
    }

    /// Every selection's text, joined by newlines.
    ///
    /// Newlines rather than nothing, because the counterpart paste splits on
    /// them to hand one line back to each cursor. Joining with the empty string
    /// would make a three-cursor copy indistinguishable from one long word.
    fn selected_text(&self) -> String {
        self.selections
            .iter()
            .filter(|s| !s.is_empty())
            .map(|s| {
                let (start, end) = s.range();
                self.buffer.text_in_range(start, end)
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Replace the selection set, preserving order and the primary.
    pub(crate) fn set_selections(&mut self, list: Vec<Selection>) {
        let mut iter = list.into_iter();
        let first = iter.next().expect("selections are never empty");
        self.selections.set_single(first);
        for selection in iter {
            self.selections.push(selection);
        }
    }

    /// Apply one described edit per selection, keeping every other selection
    /// pointing at the text it was aimed at.
    ///
    /// The closure *describes* an edit as a range plus its replacement rather
    /// than performing it. That is what makes multi-cursor correct: an edit
    /// shifts every position after it, so the positions a later selection was
    /// built from are stale the moment an earlier edit lands. Describing first
    /// lets this function apply the edits in order and carry the accumulated
    /// shift forward, which is the same job a text editor's change-mapping does
    /// and is not something each action should reimplement.
    fn edit_at_each_selection(
        &mut self,
        kind: EditKind,
        describe: impl Fn(Selection, &TextBuffer) -> Edit,
    ) -> Option<Vec<PanelEvent>> {
        // Describing happens entirely before the first mutation, so the closure
        // can borrow the buffer directly. The previous version copied every line
        // in the file into a Vec<String> to dodge a borrow that was never a
        // conflict — 50k allocations per keystroke to avoid a compile error that
        // does not occur.
        let described: Vec<Edit> = self
            .selections
            .iter()
            .map(|s| describe(*s, &self.buffer))
            .collect();

        // One snapshot for the whole group, so a thirty-caret edit is one undo
        // step rather than thirty — and consecutive edits of the same kind fold
        // into the run already open, so typing a word is one step too.
        self.buffer.begin_edit_group(kind, &self.selections);

        let mut shift = Shift::default();
        let mut heads: Vec<Position> = Vec::with_capacity(described.len());
        for edit in described {
            let start = shift.apply(edit.start);
            let end = shift.apply(edit.end);
            self.buffer.replace_range(start, end, &edit.text);

            let after = position_after(start, &edit.text);
            shift.record(edit.end.line, end, after);
            heads.push(after);
        }

        self.buffer.end_edit_group();

        self.set_selections(heads.into_iter().map(Selection::caret).collect());
        self.goal_col = None;
        self.scroll_to_cursor();
        Some(vec![PanelEvent::NeedsRedraw])
    }

    /// Add or remove one indent level on every line a selection touches.
    ///
    /// This does not go through `edit_at_each_selection`, and the reason is the
    /// difference between the two operations. That one edits *at* each
    /// selection and collapses the result to carets, which is right for typing
    /// and wrong here: an indent must leave the selection standing so the user
    /// can press Tab again. It also works per *line* rather than per selection,
    /// so two cursors on one line indent it once.
    ///
    /// Edits run last line first, so every earlier line's offsets stay valid
    /// without a shift map — the edits are disjoint and each sits at the start
    /// of its own line, which is a much smaller problem than the general one.
    fn shift_lines(&mut self, indent: bool) -> Option<Vec<PanelEvent>> {
        let mut lines: Vec<usize> = Vec::new();
        for selection in self.selections.iter() {
            let (start, end) = selection.range();
            // A selection ending at column 0 has nothing of that line in it, so
            // the line is not part of the block. Including it is the classic
            // off-by-one that indents a line the user cannot see selected.
            let last = if end.col == 0 && end.line > start.line {
                end.line - 1
            } else {
                end.line
            };
            lines.extend(start.line..=last);
        }
        lines.sort_unstable();
        lines.dedup();

        // How each line's columns move. Only affected lines appear.
        let mut deltas: Vec<(usize, isize)> = Vec::new();
        for &line in &lines {
            let delta = self.buffer.with_line_str(line, |text| {
                if indent {
                    // Indenting a blank line leaves trailing whitespace and
                    // achieves nothing else.
                    if text.trim().is_empty() {
                        return 0;
                    }
                    TAB_WIDTH as isize
                } else if text.starts_with('\t') {
                    -1
                } else {
                    // A partial level goes to zero rather than to minus one.
                    -(text
                        .chars()
                        .take(TAB_WIDTH)
                        .take_while(|c| *c == ' ')
                        .count() as isize)
                }
            });
            if delta != 0 {
                deltas.push((line, delta));
            }
        }

        if deltas.is_empty() {
            // Handled, nothing to do — not "unhandled", which would send the
            // action on to the app and eventually to a raw key.
            return Some(Vec::new());
        }

        // `Other`: an indent is never part of a typing run.
        self.buffer
            .begin_edit_group(EditKind::Other, &self.selections);
        for &(line, delta) in deltas.iter().rev() {
            let start = Position { line, col: 0 };
            if delta > 0 {
                self.buffer
                    .replace_range(start, start, &" ".repeat(delta as usize));
            } else {
                let end = Position {
                    line,
                    col: (-delta) as usize,
                };
                self.buffer.replace_range(start, end, "");
            }
        }
        self.buffer.end_edit_group();

        // Move every selection by its own line's delta, so the selection ends
        // up around the same text it started around.
        let shifted: Vec<Selection> = self
            .selections
            .iter()
            .map(|selection| {
                let move_position = |p: Position| {
                    let delta = deltas
                        .iter()
                        .find(|(line, _)| *line == p.line)
                        .map_or(0, |(_, d)| *d);
                    Position {
                        line: p.line,
                        col: p.col.saturating_add_signed(delta),
                    }
                };
                Selection {
                    anchor: move_position(selection.anchor),
                    head: move_position(selection.head),
                }
            })
            .collect();
        self.set_selections(shifted);
        self.goal_col = None;
        self.scroll_to_cursor();
        Some(vec![PanelEvent::NeedsRedraw])
    }

    /// The entry point every consumer uses. `None` means this panel does not
    /// handle the action, so the app should try it.
    pub fn perform(&mut self, action: Action) -> Option<Vec<PanelEvent>> {
        // Anything that is not an edit ends the undo run. "Undo what I just
        // typed" means the text typed since the cursor last moved, so the
        // boundary belongs on every action that is not itself an edit — one
        // place, rather than remembered at each of them.
        if !matches!(
            action,
            Action::InsertChar(_) | Action::InsertNewline | Action::Delete { .. }
        ) {
            self.buffer.undo_boundary();
        }

        match action {
            Action::Move { motion, extend } => {
                let vertical = matches!(
                    motion,
                    Motion::Up | Motion::Down | Motion::PageUp | Motion::PageDown
                );
                if vertical {
                    // Latch the goal from where the cursor is *now*, before
                    // moving. Recomputing it afterwards would store the column
                    // the motion just clamped to, so one pass through a short
                    // line would narrow the goal permanently — the exact bug
                    // this field exists to prevent.
                    if self.goal_col.is_none() {
                        let cursor = self.cursor();
                        self.goal_col = Some(grapheme_to_display_col(
                            &self.buffer.line_text(cursor.line),
                            cursor.col,
                            TAB_WIDTH,
                        ));
                    }
                } else {
                    self.goal_col = None;
                }

                // Read every selection before writing any: `move_selection`
                // borrows self immutably, and the write needs it mutably.
                let moved: Vec<Selection> = self
                    .selections
                    .iter()
                    .map(|s| self.move_selection(*s, motion, extend))
                    .collect();
                self.set_selections(moved);
                self.scroll_to_cursor();
                Some(vec![PanelEvent::NeedsRedraw])
            }
            Action::InsertChar(c) => {
                let text = c.to_string();
                self.edit_at_each_selection(EditKind::Insert, move |selection, _buffer| {
                    let (start, end) = selection.range();
                    Edit {
                        start,
                        end,
                        text: text.clone(),
                    }
                })
            }

            // `Other`, not `Insert`: a newline ends the typing run, so undo
            // after Enter takes back the line rather than the paragraph.
            Action::InsertNewline => {
                self.edit_at_each_selection(EditKind::Other, |selection, _buffer| {
                    let (start, end) = selection.range();
                    Edit {
                        start,
                        end,
                        text: "\n".to_string(),
                    }
                })
            }

            Action::Delete { direction, by_word } => {
                self.edit_at_each_selection(EditKind::Delete, move |selection, buffer| {
                    // A non-empty selection is the target, whichever key was
                    // pressed.
                    if !selection.is_empty() {
                        let (start, end) = selection.range();
                        return Edit::delete(start, end);
                    }

                    let head = selection.head;
                    // One line, not every line: a word boundary never reaches
                    // past the line it is on.
                    let line_len = buffer.line_grapheme_count(head.line);

                    match direction {
                        Direction::Backward => {
                            if head.col > 0 {
                                let target = if by_word {
                                    buffer.with_line_str(head.line, |line| {
                                        previous_word_boundary(line, head.col)
                                    })
                                } else {
                                    head.col - 1
                                };
                                Edit::delete(
                                    Position {
                                        line: head.line,
                                        col: target,
                                    },
                                    head,
                                )
                            } else if head.line > 0 {
                                // Join with the previous line: delete the
                                // newline between them.
                                let previous = head.line - 1;
                                let col = buffer.line_grapheme_count(previous);
                                Edit::delete(
                                    Position {
                                        line: previous,
                                        col,
                                    },
                                    head,
                                )
                            } else {
                                Edit::nothing(head)
                            }
                        }
                        Direction::Forward => {
                            if head.col < line_len {
                                let target = if by_word {
                                    buffer.with_line_str(head.line, |line| {
                                        next_word_boundary(line, head.col)
                                    })
                                } else {
                                    head.col + 1
                                };
                                Edit::delete(
                                    head,
                                    Position {
                                        line: head.line,
                                        col: target,
                                    },
                                )
                            } else if head.line + 1 < buffer.line_count() {
                                // At the end of a line, pull the next one up.
                                Edit::delete(
                                    head,
                                    Position {
                                        line: head.line + 1,
                                        col: 0,
                                    },
                                )
                            } else {
                                Edit::nothing(head)
                            }
                        }
                    }
                })
            }

            Action::Undo => {
                // No clamping: these selections were valid against this exact
                // rope when they were recorded, which is also why undo puts the
                // cursor back where the edit was made rather than wherever the
                // clamp happened to land it.
                if let Some(restored) = self.buffer.undo(&self.selections) {
                    self.selections = restored;
                    self.goal_col = None;
                }
                self.scroll_to_cursor();
                Some(vec![PanelEvent::NeedsRedraw])
            }

            Action::Redo => {
                if let Some(restored) = self.buffer.redo(&self.selections) {
                    self.selections = restored;
                    self.goal_col = None;
                }
                self.scroll_to_cursor();
                Some(vec![PanelEvent::NeedsRedraw])
            }

            Action::SelectAll => {
                let last = self.last_line();
                self.selections.set_single(Selection {
                    anchor: Position { line: 0, col: 0 },
                    head: Position {
                        line: last,
                        col: self.line_grapheme_count(last),
                    },
                });
                self.goal_col = None;
                Some(vec![PanelEvent::NeedsRedraw])
            }

            Action::SelectLine => {
                let line = self.cursor().line;
                // Without the newline: selecting it would make the next
                // keystroke eat the line break, which is not what "select this
                // line" means to anyone.
                self.selections.set_single(Selection {
                    anchor: Position { line, col: 0 },
                    head: Position {
                        line,
                        col: self.line_grapheme_count(line),
                    },
                });
                self.goal_col = None;
                Some(vec![PanelEvent::NeedsRedraw])
            }

            Action::SelectNextOccurrence => self.select_next_occurrence(),
            Action::SelectAllOccurrences => self.select_all_occurrences(),

            Action::CollapseSelections => {
                self.selections.collapse_to_heads();
                self.goal_col = None;
                self.scroll_to_cursor();
                Some(vec![PanelEvent::NeedsRedraw])
            }

            Action::AddCursor(direction) => {
                let from = self.selections.primary().head;
                let target_line = match direction {
                    Direction::Backward => from.line.checked_sub(1),
                    Direction::Forward => {
                        let next = from.line + 1;
                        (next <= self.last_line()).then_some(next)
                    }
                };
                let Some(line) = target_line else {
                    // At the edge of the document there is nowhere to add one.
                    // Some(vec![]) rather than None: the action was handled and
                    // simply had nothing to do, so the app must not retry it as
                    // an app action.
                    return Some(Vec::new());
                };
                let col = from.col.min(self.line_grapheme_count(line));
                self.selections
                    .push(Selection::caret(Position { line, col }));
                self.scroll_to_cursor();
                Some(vec![PanelEvent::NeedsRedraw])
            }

            Action::Copy => {
                let text = self.selected_text();
                // Copying nothing must not wipe what is already held. Every
                // editor in the field either copies the whole line or does
                // nothing; doing nothing is the one that never surprises.
                if !text.is_empty() {
                    clipboard::set(&text);
                }
                Some(vec![PanelEvent::NeedsRedraw])
            }

            Action::Cut => {
                let text = self.selected_text();
                if text.is_empty() {
                    return Some(Vec::new());
                }
                clipboard::set(&text);
                // `Other`, so a cut always stands alone in the undo history
                // rather than folding into a run of typing on either side.
                self.edit_at_each_selection(EditKind::Other, |selection, _buffer| {
                    let (start, end) = selection.range();
                    Edit::delete(start, end)
                })
            }

            Action::Paste => {
                let text = clipboard::get();
                if text.is_empty() {
                    return Some(Vec::new());
                }

                // One clipboard line per cursor when the counts match, which is
                // what makes a multi-cursor copy round-trip through a paste.
                // VS Code and Sublime both do this, and without it a three-line
                // copy stamps all three lines at all three cursors.
                let lines: Vec<String> = text.lines().map(str::to_string).collect();
                let distribute = lines.len() == self.selections.len() && self.selections.len() > 1;

                let index = std::cell::Cell::new(0usize);
                self.edit_at_each_selection(EditKind::Other, move |selection, _buffer| {
                    let (start, end) = selection.range();
                    let piece = if distribute {
                        let i = index.get();
                        index.set(i + 1);
                        lines[i].clone()
                    } else {
                        text.clone()
                    };
                    Edit {
                        start,
                        end,
                        text: piece,
                    }
                })
            }

            // Tab is two behaviours behind one key, which is what every editor
            // in the field does. With nothing selected it inserts to the next
            // tab stop, the way typing does. With a selection it shifts every
            // line the selection touches, because that is what a block indent
            // means — and inserting there would replace the selection instead.
            Action::Indent => {
                if self.selections.iter().all(Selection::is_empty) {
                    self.edit_at_each_selection(EditKind::Other, |selection, buffer| {
                        let head = selection.head;
                        // From the *display* column, so a line containing tabs
                        // lands on the same stop the renderer draws.
                        let display = buffer.with_line_str(head.line, |line| {
                            grapheme_to_display_col(line, head.col, TAB_WIDTH)
                        });
                        Edit {
                            start: head,
                            end: head,
                            text: " ".repeat(TAB_WIDTH - (display % TAB_WIDTH)),
                        }
                    })
                } else {
                    self.shift_lines(true)
                }
            }

            // Outdent always works on lines. Shift+Tab at a bare caret means
            // "unindent this line", not "delete something to my left".
            Action::Outdent => self.shift_lines(false),

            // Not this panel's business. The app tries it next.
            _ => None,
        }
    }
}

/// One edit, described rather than performed: replace `start..end` with `text`.
///
/// An empty range inserts and an empty text deletes, so every editing action
/// reduces to this one shape and the position mapping only has to understand
/// one thing.
struct Edit {
    start: Position,
    end: Position,
    text: String,
}

impl Edit {
    fn delete(start: Position, end: Position) -> Self {
        Self {
            start,
            end,
            text: String::new(),
        }
    }

    /// An edit that changes nothing, for a caret with nowhere to go — the
    /// start of the buffer for backspace, the end for delete.
    fn nothing(at: Position) -> Self {
        Self {
            start: at,
            end: at,
            text: String::new(),
        }
    }
}

/// Where a position ends up once `text` has been inserted at `start`.
fn position_after(start: Position, text: &str) -> Position {
    let mut line = start.line;
    let mut col = start.col;
    for grapheme in text.graphemes(true) {
        if grapheme == "\n" || grapheme == "\r\n" {
            line += 1;
            col = 0;
        } else {
            col += 1;
        }
    }
    Position { line, col }
}