rustaco-core 0.3.0

Text model for the Rustaco editor: rope buffer, multi-cursor selections, change sets, undo history
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
//! Editing commands, applied to a shared [`TextModel`] on behalf of one editor's [`Cursors`].

use ropey::Rope;

use crate::change::{Assoc, ChangeSet, Edit, inside_crlf};
use crate::commands::{next_grapheme, prev_grapheme};
use crate::history::{EditKind, Transaction};
use crate::model::{Options, TextModel};
use crate::position::{Position, char_to_position, line_end, line_len, position_to_char};
use crate::selection::{Selection, Selections};

/// Identifies an editor among those showing one model.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct EditorId(pub u32);

/// One editor's selections, plus the model version they are valid for.
#[derive(Clone, Debug)]
pub struct Cursors {
    id: EditorId,
    pub(crate) selections: Selections,
    synced: u64,
    /// Earlier selections, for cursor undo (Ctrl+U); valid only until the text changes.
    cursor_history: Vec<Selections>,
    /// Selections before each expand-selection step, for shrinking back.
    pub(crate) expansions: Vec<Selections>,
    /// The snippet being filled in, if any.
    pub(crate) snippet: Option<crate::snippet::SnippetSession>,
}

/// Cursor states kept for cursor undo.
const CURSOR_HISTORY: usize = 50;

impl Cursors {
    pub fn new(id: EditorId, model: &TextModel) -> Self {
        Self {
            id,
            selections: Selections::single(Selection::cursor(0)),
            synced: model.version(),
            cursor_history: Vec::new(),
            expansions: Vec::new(),
            snippet: None,
        }
    }

    pub fn id(&self) -> EditorId {
        self.id
    }

    /// Whether a snippet is being filled in.
    pub fn snippet_active(&self) -> bool {
        self.snippet.is_some()
    }

    /// The selections as of the last [`Cursors::sync`]. Call `sync` first when another
    /// editor may have changed the model.
    pub fn selections(&self) -> &Selections {
        &self.selections
    }

    /// Moves the selections through every change made since they were last valid.
    /// A cursor at an insertion point stays before the inserted text.
    pub fn sync(&mut self, model: &TextModel) {
        if self.synced == model.version() {
            return;
        }
        if let Ok(changes) = model.changes_since(self.synced) {
            for cs in changes {
                self.selections = self.selections.map(|s| Selection {
                    anchor: cs.map(s.anchor, Assoc::Before),
                    head: cs.map(s.head, Assoc::Before),
                    goal_column: None,
                });
            }
        }
        self.selections = snap_selections(model.rope(), &self.selections);
        self.synced = model.version();
    }
}

/// Short-lived access to a model for one editor. Creating it syncs the cursors.
pub struct Editor<'a> {
    pub(crate) model: &'a mut TextModel,
    pub(crate) cursors: &'a mut Cursors,
}

impl<'a> Editor<'a> {
    pub fn new(model: &'a mut TextModel, cursors: &'a mut Cursors) -> Self {
        cursors.sync(model);
        Self { model, cursors }
    }

    /// The model being edited.
    pub fn model(&self) -> &TextModel {
        self.model
    }

    pub fn selections(&self) -> &Selections {
        &self.cursors.selections
    }

    pub fn set_selections(&mut self, selections: Selections) {
        let next = snap_selections(&self.model.rope, &selections);
        self.record_cursor_state(&next);
        self.cursors.selections = next;
        self.model.history.break_group();
    }

    /// Remembers the current selections before a cursor change, for [`Editor::cursor_undo`].
    fn record_cursor_state(&mut self, next: &Selections) {
        if *next != self.cursors.selections {
            let h = &mut self.cursors.cursor_history;
            h.push(self.cursors.selections.clone());
            if h.len() > CURSOR_HISTORY {
                h.remove(0);
            }
        }
    }

    /// Ctrl+U: goes back to the selections before the last cursor change. Text edits clear
    /// the history, since older positions would point into changed text.
    pub fn cursor_undo(&mut self) -> bool {
        match self.cursors.cursor_history.pop() {
            Some(prev) => {
                self.cursors.selections = snap_selections(&self.model.rope, &prev);
                self.model.history.break_group();
                true
            }
            None => false,
        }
    }

    // ---- core plumbing ----

    pub(crate) fn commit(&mut self, changes: ChangeSet, after: Selections, kind: EditKind) {
        if changes.is_empty() {
            self.cursors.selections = snap_selections(&self.model.rope, &after);
            return;
        }
        let before = self.cursors.selections.clone();
        self.cursors.cursor_history.clear();
        self.cursors.expansions.clear();
        let inverse = self.model.apply(&changes);
        self.cursors.selections = snap_selections(&self.model.rope, &after);
        self.cursors.synced = self.model.version();
        let tx =
            Transaction { changes, inverse, before, after: self.cursors.selections.clone(), origin: self.cursors.id };
        self.model.history.push(tx, kind);
    }

    /// Replaces every selection with the text `f` returns for it; carets land after the text.
    pub(crate) fn replace_each(&mut self, kind: EditKind, mut f: impl FnMut(&Rope, usize, &Selection) -> String) {
        self.replace_ranges(kind, |rope, i, sel| (sel.start(), sel.end(), f(rope, i, sel)));
    }

    /// Replaces the range `f` returns for each selection (ranges must not overlap and come
    /// in selection order) with its text; carets land after the inserted text.
    fn replace_ranges(
        &mut self,
        kind: EditKind,
        mut f: impl FnMut(&Rope, usize, &Selection) -> (usize, usize, String),
    ) {
        let mut edits = Vec::with_capacity(self.cursors.selections.len());
        let mut carets = Vec::with_capacity(self.cursors.selections.len());
        let mut delta = 0isize;
        for (i, sel) in self.cursors.selections.iter().enumerate() {
            let (start, end, text) = f(&self.model.rope, i, sel);
            let inserted = text.chars().count();
            carets.push(Selection::cursor(start.wrapping_add_signed(delta) + inserted));
            delta += inserted as isize - (end - start) as isize;
            edits.push(Edit::new(start, end, text));
        }
        let after = Selections::new(carets, self.cursors.selections.primary_index());
        self.commit(ChangeSet::new(edits).snap_crlf(&self.model.rope), after, kind);
    }

    /// Replaces the `before` chars ahead of each caret (or a selection, when there is one)
    /// with `text`: one step of an IME composition, which replaces what the previous step
    /// inserted. Steps undo together with the typing around them.
    pub fn compose(&mut self, before: usize, text: &str) {
        self.replace_ranges(EditKind::Typing, |_, _, sel| {
            if sel.is_empty() {
                (sel.head.saturating_sub(before), sel.head, text.to_owned())
            } else {
                (sel.start(), sel.end(), text.to_owned())
            }
        });
    }

    /// Pastes one piece per cursor, as copied from the same number of selections.
    pub fn paste_each(&mut self, pieces: &[String]) {
        if pieces.len() != self.cursors.selections.len() {
            return self.paste(&pieces.join(self.model.line_ending.as_str()));
        }
        self.replace_each(EditKind::Other, |_, i, _| pieces[i].clone());
        self.model.history.break_group();
    }

    /// The text of each non-empty selection, in order; for clipboard metadata.
    pub fn selection_texts(&self) -> Vec<String> {
        self.cursors
            .selections
            .iter()
            .filter(|s| !s.is_empty())
            .map(|s| self.model.rope.slice(s.start()..s.end()).to_string())
            .collect()
    }

    /// Deletes the range `f` returns for each selection; carets collapse to the range start.
    fn delete_each(&mut self, kind: EditKind, mut f: impl FnMut(&Rope, &Selection) -> (usize, usize)) {
        let edits = self
            .cursors
            .selections
            .iter()
            .map(|s| {
                let (start, end) = f(&self.model.rope, s);
                Edit::delete(start, end)
            })
            .collect();
        let changes = ChangeSet::new(edits).snap_crlf(&self.model.rope);
        let after = self.cursors.selections.map(|s| Selection::cursor(changes.map(s.start(), Assoc::Before)));
        self.commit(changes, after, kind);
    }

    pub(crate) fn delete_each_pub(&mut self, kind: EditKind, f: impl FnMut(&Rope, &Selection) -> (usize, usize)) {
        self.delete_each(kind, f);
    }

    /// Moves every caret to the head `f` returns, with its goal column; frontends use it for
    /// moves that depend on layout, such as stepping over folded lines.
    pub fn move_heads(&mut self, extend: bool, f: impl FnMut(&Rope, &Selection) -> (usize, Option<usize>)) {
        self.move_each(extend, f);
    }

    fn move_each(&mut self, extend: bool, mut f: impl FnMut(&Rope, &Selection) -> (usize, Option<usize>)) {
        let moved = self.cursors.selections.map(|s| {
            let (head, goal_column) = f(&self.model.rope, s);
            let anchor = if extend { s.anchor } else { head };
            Selection { anchor, head, goal_column }
        });
        let next = snap_selections(&self.model.rope, &moved);
        // Plain caret movement is not worth undoing step by step; selections are.
        if extend || self.cursors.selections.iter().any(|s| !s.is_empty()) {
            self.record_cursor_state(&next);
        }
        self.cursors.selections = next;
        self.model.history.break_group();
    }

    // ---- editing ----

    /// Types `text` at every selection, replacing selected text.
    pub fn insert(&mut self, text: &str) {
        let mut chars = text.chars();
        let single_char = matches!((chars.next(), chars.next()), (Some(c), None) if c != '\n' && c != '\r');
        let kind = if single_char { EditKind::Typing } else { EditKind::Other };
        self.replace_each(kind, |_, _, _| text.to_owned());
    }

    /// Inserts a line break and copies the current line's indentation up to the caret.
    pub fn newline(&mut self) {
        let eol = self.model.line_ending.as_str();
        let o = self.model.options;
        let unit = if o.insert_spaces { " ".repeat(o.tab_size) } else { "\t".to_owned() };
        let editing = self.model.editing.clone();
        // Where each caret lands inside its inserted text, when not at the end (between a
        // bracket pair the caret goes on the middle line).
        let mut caret_offsets: Vec<Option<usize>> = Vec::new();
        self.replace_each(EditKind::Other, |rope, _, sel| {
            let line = rope.char_to_line(sel.start());
            let line_start = rope.line_to_char(line);
            let indent: String =
                rope.slice(line_start..sel.start()).chars().take_while(|c| *c == ' ' || *c == '\t').collect();
            let before: String = rope.slice(line_start..sel.start()).to_string();
            let before = before.trim_end();
            let opens = editing.brackets.iter().find(|(open, _)| before.ends_with(open.as_str()));
            let after_starts = |close: &str| {
                rope.slice(sel.end()..rope.len_chars()).chars().take(close.chars().count()).eq(close.chars())
            };
            match opens {
                Some((_, close)) if after_starts(close) => {
                    let middle = format!("{eol}{indent}{unit}");
                    caret_offsets.push(Some(middle.chars().count()));
                    format!("{middle}{eol}{indent}")
                }
                Some(_) => {
                    caret_offsets.push(None);
                    format!("{eol}{indent}{unit}")
                }
                None if editing.indent_after.iter().any(|s| before.ends_with(s.as_str())) => {
                    caret_offsets.push(None);
                    format!("{eol}{indent}{unit}")
                }
                None => {
                    caret_offsets.push(None);
                    format!("{eol}{indent}")
                }
            }
        });
        if caret_offsets.iter().any(Option::is_some) {
            // replace_each put each caret after its inserted text; pull back the ones that
            // belong on the middle line of a bracket pair.
            let rope = &self.model.rope;
            let mut i = 0;
            let next = self.cursors.selections.map(|s| {
                let offset = caret_offsets.get(i).copied().flatten();
                i += 1;
                match offset {
                    Some(_) => {
                        // The caret sits after "\n{indent}"; the middle line ends one line up.
                        let line = rope.char_to_line(s.head);
                        Selection::cursor(crate::position::line_end(rope, line.saturating_sub(1)))
                    }
                    None => *s,
                }
            });
            self.cursors.selections = next;
        }
    }

    /// Inserts indentation up to the next tab stop at every cursor.
    pub fn indent(&mut self) {
        let Options { tab_size, insert_spaces } = self.model.options;
        self.replace_each(EditKind::Other, |rope, _, sel| {
            if !insert_spaces {
                return "\t".to_owned();
            }
            let column = char_to_position(rope, sel.start()).column;
            " ".repeat(tab_size - column % tab_size)
        });
    }

    /// Backspace: deletes the selection, or the char before each cursor.
    pub fn delete_backward(&mut self) {
        self.delete_each(EditKind::Deleting, |rope, s| {
            if s.is_empty() { (prev_grapheme(rope, s.head), s.head) } else { (s.start(), s.end()) }
        });
    }

    /// Delete: deletes the selection, or the char after each cursor.
    pub fn delete_forward(&mut self) {
        self.delete_each(EditKind::Deleting, |rope, s| {
            if s.is_empty() { (s.head, next_grapheme(rope, s.head)) } else { (s.start(), s.end()) }
        });
    }

    /// Ctrl+Backspace: deletes the selection, or back to the previous word start.
    pub fn delete_word_backward(&mut self) {
        self.delete_each(EditKind::Other, |rope, s| {
            if s.is_empty() { (word_left(rope, s.head), s.head) } else { (s.start(), s.end()) }
        });
    }

    /// Ctrl+Delete: deletes the selection, or forward to the next word end.
    pub fn delete_word_forward(&mut self) {
        self.delete_each(EditKind::Other, |rope, s| {
            if s.is_empty() { (s.head, word_right(rope, s.head)) } else { (s.start(), s.end()) }
        });
    }

    /// Applies edits that did not come from typing, such as LSP text edits or formatting.
    /// Selections follow the text around them.
    pub fn apply_edits(&mut self, edits: Vec<Edit>) {
        let len = self.model.rope.len_chars();
        let edits = edits.into_iter().map(|e| Edit::new(e.start.min(len), e.end.min(len), e.text)).collect();
        let changes = ChangeSet::new(edits).snap_crlf(&self.model.rope);
        let after = self.cursors.selections.map(|s| Selection {
            anchor: changes.map(s.anchor, Assoc::After),
            head: changes.map(s.head, Assoc::After),
            goal_column: None,
        });
        self.commit(changes, after, EditKind::Other);
        self.model.history.break_group();
    }

    // ---- clipboard ----

    /// Text for the clipboard. With only empty cursors, copies their whole lines.
    pub fn copy(&self) -> String {
        if self.cursors.selections.iter().all(Selection::is_empty) {
            let mut out = String::new();
            let mut last_line = None;
            for s in self.cursors.selections.iter() {
                let line = self.model.rope.char_to_line(s.head);
                if last_line == Some(line) {
                    continue;
                }
                last_line = Some(line);
                out.push_str(&self.model.rope.line(line).to_string());
                if line + 1 == self.model.rope.len_lines() {
                    out.push_str(self.model.line_ending.as_str());
                }
            }
            return out;
        }
        let parts: Vec<String> = self
            .cursors
            .selections
            .iter()
            .filter(|s| !s.is_empty())
            .map(|s| self.model.rope.slice(s.start()..s.end()).to_string())
            .collect();
        parts.join(self.model.line_ending.as_str())
    }

    /// Copies, then deletes what was copied.
    pub fn cut(&mut self) -> String {
        let text = self.copy();
        if self.cursors.selections.iter().all(Selection::is_empty) {
            self.delete_each(EditKind::Other, |rope, s| {
                let line = rope.char_to_line(s.head);
                (rope.line_to_char(line), rope.line_to_char(line + 1))
            });
        } else {
            self.delete_each(EditKind::Other, |_, s| (s.start(), s.end()));
        }
        text
    }

    /// Pastes `text`. When it has exactly one line per cursor, each cursor gets its own line.
    pub fn paste(&mut self, text: &str) {
        let lines: Vec<&str> = text.lines().collect();
        let spread = self.cursors.selections.len() > 1 && lines.len() == self.cursors.selections.len();
        self.replace_each(EditKind::Other, |_, i, _| if spread { lines[i].to_owned() } else { text.to_owned() });
        self.model.history.break_group();
    }

    // ---- movement ----

    pub fn move_left(&mut self, extend: bool) {
        self.move_each(extend, |rope, s| {
            if !extend && !s.is_empty() { (s.start(), None) } else { (prev_grapheme(rope, s.head), None) }
        });
    }

    pub fn move_right(&mut self, extend: bool) {
        self.move_each(extend, |rope, s| {
            if !extend && !s.is_empty() { (s.end(), None) } else { (next_grapheme(rope, s.head), None) }
        });
    }

    pub fn move_word_left(&mut self, extend: bool) {
        self.move_each(extend, |rope, s| (word_left(rope, s.head), None));
    }

    pub fn move_word_right(&mut self, extend: bool) {
        self.move_each(extend, |rope, s| (word_right(rope, s.head), None));
    }

    pub fn move_up(&mut self, extend: bool) {
        self.move_vertical(-1, extend);
    }

    pub fn move_down(&mut self, extend: bool) {
        self.move_vertical(1, extend);
    }

    /// Moves every caret `lines` lines up (negative) or down, keeping the goal column.
    pub fn move_vertical(&mut self, lines: isize, extend: bool) {
        self.move_each(extend, |rope, s| vertical_target(rope, s, lines));
    }

    /// Home: toggles between the first non-whitespace char and column 0.
    pub fn move_line_start(&mut self, extend: bool) {
        self.move_each(extend, |rope, s| {
            let line = rope.char_to_line(s.head);
            let start = rope.line_to_char(line);
            let indent = rope.line(line).chars().take(line_len(rope, line)).take_while(|c| c.is_whitespace()).count();
            let target = if s.head == start + indent { start } else { start + indent };
            (target, None)
        });
    }

    pub fn move_line_end(&mut self, extend: bool) {
        self.move_each(extend, |rope, s| (line_end(rope, rope.char_to_line(s.head)), None));
    }

    pub fn move_document_start(&mut self, extend: bool) {
        self.move_each(extend, |_, _| (0, None));
    }

    pub fn move_document_end(&mut self, extend: bool) {
        self.move_each(extend, |rope, _| (rope.len_chars(), None));
    }

    pub fn select_all(&mut self) {
        self.set_selections(Selections::single(Selection::new(0, self.model.rope.len_chars())));
    }

    /// Adds a cursor one line below the last cursor (or above the first one) and makes it primary.
    pub fn add_cursor_vertical(&mut self, below: bool) {
        let sels = self.cursors.selections.as_slice();
        let source = if below { sels[sels.len() - 1] } else { sels[0] };
        let (head, goal_column) =
            vertical_target(&self.model.rope, &Selection::cursor(source.head), if below { 1 } else { -1 });
        let line = self.model.rope.char_to_line(source.head);
        let at_edge = if below { line + 1 >= self.model.rope.len_lines() } else { line == 0 };
        if at_edge {
            return;
        }
        let mut ranges = sels.to_vec();
        ranges.push(Selection { anchor: head, head, goal_column });
        let primary = ranges.len() - 1;
        self.set_selections(Selections::new(ranges, primary));
    }

    // ---- history ----

    /// Undoes the last step in the model, whichever editor made it. The editor that made it
    /// gets its selections back; any other editor's cursors follow the text.
    pub fn undo(&mut self) -> bool {
        let Some(step) = self.model.history.pop_undo() else { return false };
        for tx in step.transactions.iter().rev() {
            self.model.apply(&tx.inverse);
        }
        let first = &step.transactions[0];
        if first.origin == self.cursors.id {
            self.cursors.selections = snap_selections(&self.model.rope, &first.before);
            self.cursors.synced = self.model.version();
        } else {
            self.cursors.sync(self.model);
        }
        self.model.history.push_redo(step);
        true
    }

    pub fn redo(&mut self) -> bool {
        let Some(step) = self.model.history.pop_redo() else { return false };
        for tx in &step.transactions {
            self.model.apply(&tx.changes);
        }
        let last = &step.transactions[step.transactions.len() - 1];
        if last.origin == self.cursors.id {
            self.cursors.selections = snap_selections(&self.model.rope, &last.after);
            self.cursors.synced = self.model.version();
        } else {
            self.cursors.sync(self.model);
        }
        self.model.history.push_undo(step);
        true
    }
}

/// Clamps selections into the document and moves endpoints out of CRLF pairs.
fn snap_selections(rope: &Rope, selections: &Selections) -> Selections {
    let len = rope.len_chars();
    let snap = |p: usize| {
        let p = p.min(len);
        if inside_crlf(rope, p) { p - 1 } else { p }
    };
    selections.map(|s| Selection { anchor: snap(s.anchor), head: snap(s.head), goal_column: s.goal_column })
}

/// Char offset one step left, treating `\r\n` as a single step.
fn prev_boundary(rope: &Rope, pos: usize) -> usize {
    if pos >= 2 && rope.char(pos - 1) == '\n' && rope.char(pos - 2) == '\r' { pos - 2 } else { pos.saturating_sub(1) }
}

/// Char offset one step right, treating `\r\n` as a single step.
fn next_boundary(rope: &Rope, pos: usize) -> usize {
    let len = rope.len_chars();
    if pos + 1 < len && rope.char(pos) == '\r' && rope.char(pos + 1) == '\n' { pos + 2 } else { (pos + 1).min(len) }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum CharClass {
    Word,
    Space,
    Newline,
    Punct,
}

fn char_class(c: char) -> CharClass {
    match c {
        '\n' | '\r' => CharClass::Newline,
        c if c.is_whitespace() => CharClass::Space,
        c if c.is_alphanumeric() || c == '_' => CharClass::Word,
        _ => CharClass::Punct,
    }
}

/// Ctrl+Right: skips spaces, then one run of word or punctuation chars. Stops at line ends.
pub(crate) fn word_right(rope: &Rope, mut pos: usize) -> usize {
    let len = rope.len_chars();
    if pos < len && char_class(rope.char(pos)) == CharClass::Newline {
        return next_boundary(rope, pos);
    }
    while pos < len && char_class(rope.char(pos)) == CharClass::Space {
        pos += 1;
    }
    if pos < len {
        let class = char_class(rope.char(pos));
        if class != CharClass::Newline {
            while pos < len && char_class(rope.char(pos)) == class {
                pos += 1;
            }
        }
    }
    pos
}

/// Ctrl+Left: mirror of [`word_right`].
pub(crate) fn word_left(rope: &Rope, mut pos: usize) -> usize {
    if pos > 0 && char_class(rope.char(pos - 1)) == CharClass::Newline {
        return prev_boundary(rope, pos);
    }
    while pos > 0 && char_class(rope.char(pos - 1)) == CharClass::Space {
        pos -= 1;
    }
    if pos > 0 {
        let class = char_class(rope.char(pos - 1));
        if class != CharClass::Newline {
            while pos > 0 && char_class(rope.char(pos - 1)) == class {
                pos -= 1;
            }
        }
    }
    pos
}

/// The run of same-class chars around `pos`, preferring a word on either side. Used by double-click.
pub fn word_at(rope: &Rope, pos: usize) -> (usize, usize) {
    let len = rope.len_chars();
    let class_at = |i: usize| (i < len).then(|| char_class(rope.char(i)));
    let class = match (class_at(pos), pos.checked_sub(1).and_then(class_at)) {
        (Some(CharClass::Word), _) => CharClass::Word,
        (_, Some(CharClass::Word)) => CharClass::Word,
        (Some(c), _) if c != CharClass::Newline => c,
        (_, Some(c)) if c != CharClass::Newline => c,
        _ => return (pos, pos),
    };
    let (mut start, mut end) = (pos, pos);
    while start > 0 && char_class(rope.char(start - 1)) == class {
        start -= 1;
    }
    while end < len && char_class(rope.char(end)) == class {
        end += 1;
    }
    (start, end)
}

fn vertical_target(rope: &Rope, s: &Selection, lines: isize) -> (usize, Option<usize>) {
    let pos = char_to_position(rope, s.head);
    let goal = s.goal_column.unwrap_or(pos.column);
    let target = pos.line as isize + lines;
    if target < 0 {
        return (0, None);
    }
    if target as usize >= rope.len_lines() {
        return (rope.len_chars(), None);
    }
    (position_to_char(rope, Position::new(target as usize, goal)), Some(goal))
}