reedline 0.49.0

A readline-like crate for CLI text input
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
use crate::core_editor::graphemes::{next_grapheme_boundary, prev_grapheme_boundary};

/// The direction a cursor extends in.
///
/// `Forward` when `head >= anchor`, `Backward` when `head < anchor`.
///
// Part of the selection vocabulary that lands incrementally: no caller until
// selection-aware motions (Vi visual / Helix) are wired through `Cursor`.
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction {
    /// Head is at or after anchor.
    Forward,
    /// Head is before anchor.
    Backward,
}

/// Selection intent of a motion — whether it carries the anchor along or drops
/// it. Mirrors Helix's `Movement`; the readable face of `put_cursor`'s old
/// `extend: bool`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Movement {
    /// Collapse to a point at the target — an ordinary (non-selecting) motion.
    Move,
    /// Keep the anchor fixed and move only the head — extend the selection.
    Extend,
}

impl Movement {
    /// `Extend` when selecting, `Move` otherwise — the bridge from the boolean
    /// `select` flag the edit commands still carry.
    pub(crate) fn select(select: bool) -> Self {
        if select {
            Movement::Extend
        } else {
            Movement::Move
        }
    }
}

/// Where the caret sits relative to a grapheme — the geometry axis shared by
/// motion resolution ([`resolve_motion`](super::resolve_motion)) and selection
/// extension ([`Cursor::put_cursor`]).
///
/// - `Block` (vi normal / visual): the caret sits *on* a grapheme. A forward
///   word-end lands on the last char, and an inclusive motion's operator or
///   selection covers it.
/// - `Bar` (emacs / vi-insert): the caret sits *between* graphemes, on the
///   trailing boundary, so the same motion is exclusive.
///
/// The readable face of the `block`/`inclusive` boolean that used to thread
/// through the motion path under three different names.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CaretGeometry {
    Block,
    Bar,
}

impl CaretGeometry {
    /// `true` for `Block` — the caret is on a grapheme, so inclusive motions
    /// cover it. The boolean the geometry-sensitive internals still branch on.
    pub(crate) fn is_inclusive(self) -> bool {
        matches!(self, CaretGeometry::Block)
    }
}

/// A cursor as a (possibly empty) range over a buffer.
///
/// Uses gap indexing — `anchor` and `head` represent positions *between* bytes,
/// not bytes themselves. The range covered is left-inclusive and right-
/// exclusive, regardless of anchor/head ordering.
///
/// A "point" cursor (`anchor == head`) is the degenerate empty range and
/// behaves like a plain insertion point. Wider cursors model selections.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Cursor {
    /// The anchor of the cursor: the side that doesn't move when extending.
    anchor: usize,
    /// The head of the cursor: moved when extending or moving.
    head: usize,
}

impl Cursor {
    /// Construct a cursor with explicit anchor and head positions.
    pub fn new(anchor: usize, head: usize) -> Self {
        Self { anchor, head }
    }

    /// A zero-width cursor at `head`.
    pub fn point(head: usize) -> Self {
        Self::new(head, head)
    }

    /// The anchor position.
    pub fn anchor(&self) -> usize {
        self.anchor
    }

    /// The head position. This is what most callers think of as "the cursor".
    pub fn head(&self) -> usize {
        self.head
    }

    /// Start of the range.
    pub fn start(&self) -> usize {
        self.anchor.min(self.head)
    }

    /// End of the range.
    pub fn end(&self) -> usize {
        self.anchor.max(self.head)
    }

    /// `true` when anchor and head are at the same position.
    pub fn is_empty(&self) -> bool {
        self.anchor == self.head
    }
}

/// Range algebra that selection-aware motions need but the current point-cursor
/// callers don't yet exercise. Lands incrementally with its callers (Vi visual /
/// Helix selection); kept here, fully tested, so the primitive is complete.
#[allow(dead_code)]
impl Cursor {
    /// `(start, end)` as a `Range<usize>`, for consumers that want it.
    pub fn to_range(self) -> std::ops::Range<usize> {
        self.start()..self.end()
    }

    /// Total byte length of the range.
    pub fn len(&self) -> usize {
        self.end() - self.start()
    }

    /// `Forward` when `head >= anchor`, `Backward` otherwise.
    pub fn direction(&self) -> Direction {
        if self.head < self.anchor {
            Direction::Backward
        } else {
            Direction::Forward
        }
    }

    /// Swap anchor and head.
    pub fn flip(self) -> Self {
        Self {
            anchor: self.head,
            head: self.anchor,
        }
    }

    /// Return the cursor if it already points in `direction`, otherwise flip it.
    pub fn with_direction(self, direction: Direction) -> Self {
        if self.direction() == direction {
            self
        } else {
            self.flip()
        }
    }

    /// Move head to `new_head`, preserving anchor. Used for selecting motions.
    pub fn move_head(self, new_head: usize) -> Self {
        Self {
            anchor: self.anchor,
            head: new_head,
        }
    }

    /// Collapse to a point at `head`. Used for non-selecting motions.
    pub fn collapse_to(self, head: usize) -> Self {
        Self::point(head)
    }

    /// Collapse to a point at the current head position.
    pub fn collapse(self) -> Self {
        Self::point(self.head)
    }

    /// Grow the range to cover at least `[from, to]`, preserving anchor/head
    /// ordering.
    ///
    /// If the cursor is currently `Forward`, the anchor can only move left and
    /// the head can only move right. If `Backward`, the roles are inverted.
    pub fn extend(self, from: usize, to: usize) -> Self {
        debug_assert!(from <= to);
        if self.anchor <= self.head {
            Self {
                anchor: self.anchor.min(from),
                head: self.head.max(to),
            }
        } else {
            Self {
                anchor: self.anchor.max(to),
                head: self.head.min(from),
            }
        }
    }

    /// `true` if `pos` lies inside the range (left-inclusive, right-exclusive).
    pub fn contains(&self, pos: usize) -> bool {
        self.start() <= pos && pos < self.end()
    }

    /// The visible caret position
    pub fn caret(&self, buf: &str) -> usize {
        if self.head > self.anchor {
            prev_grapheme_boundary(buf, self.head)
        } else {
            self.head
        }
    }

    /// Move the caret to land on the grapheme at byte `target`, returning the new
    /// cursor. Mirrors Helix's `Range::put_cursor`.
    ///
    /// [`Movement::Move`] collapses to a point at `target` (the commit boundary's
    /// `Block` policy then widens it to a 1-grapheme block). [`Movement::Extend`]
    /// keeps the anchor side — but **flips the anchor onto the other edge of its
    /// grapheme when the selection changes direction**, so the grapheme the
    /// selection started on stays covered (see the type docs / convergence note).
    ///
    /// `geometry` is the per-mode selection geometry: when extending *forward*, a
    /// `Block` (vi-normal) cursor places the head one grapheme past `target` so
    /// `target`'s grapheme is covered; a `Bar` (emacs / Between) cursor places the
    /// head exactly on `target`. It only affects the forward head — a backward
    /// range already covers `target` at its low end, and a collapse ignores it.
    pub fn put_cursor(
        self,
        buf: &str,
        target: usize,
        movement: Movement,
        geometry: CaretGeometry,
    ) -> Self {
        if movement == Movement::Move {
            return Self::point(target);
        }
        let inclusive = geometry.is_inclusive();

        // Flip the anchor onto the far edge of its grapheme when the direction
        // changes, so the grapheme the selection started on stays covered (Helix
        // `Range::put_cursor`). This is *inclusive* (block) behavior; an exclusive
        // (Between / emacs) selection is half-open `[min, max)`, so its anchor
        // never moves on reversal.
        let anchor: usize = if !inclusive {
            self.anchor
        } else if self.head >= self.anchor && target < self.anchor {
            next_grapheme_boundary(buf, self.anchor)
        } else if self.head < self.anchor && target >= self.anchor {
            prev_grapheme_boundary(buf, self.anchor)
        } else {
            self.anchor
        };

        // Place the head so `caret()` lands back on `target`'s grapheme: forward
        // *and inclusive* → head on the far edge; otherwise → head *is* `target`.
        let head = if anchor <= target && inclusive {
            next_grapheme_boundary(buf, target)
        } else {
            target
        };

        Self::new(anchor, head)
    }
}

impl Default for Cursor {
    fn default() -> Self {
        Self::point(0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn contains() {
        let range = Cursor::new(10, 12);

        assert!(!range.contains(9));
        assert!(range.contains(10));
        assert!(range.contains(11));
        assert!(!range.contains(12));
        assert!(!range.contains(13));

        let range = Cursor::new(9, 6);
        assert!(!range.contains(9));
        assert!(range.contains(7));
        assert!(range.contains(6));
    }

    #[test]
    fn point_constructs_empty_range_at_head() {
        let range = Cursor::point(5);
        assert_eq!(range.start(), 5);
        assert_eq!(range.end(), 5);
        assert!(range.is_empty());
    }

    #[test]
    fn new_preserves_anchor_and_head_order() {
        let forward = Cursor::new(2, 5);
        assert_eq!(forward.direction(), Direction::Forward);

        let backward = Cursor::new(5, 2);
        assert_eq!(backward.direction(), Direction::Backward);
    }

    #[test]
    fn start_returns_lower_of_anchor_and_head() {
        assert_eq!(Cursor::new(2, 5).start(), 2);
        assert_eq!(Cursor::new(5, 2).start(), 2);
    }

    #[test]
    fn end_returns_higher_of_anchor_and_head() {
        assert_eq!(Cursor::new(2, 5).end(), 5);
        assert_eq!(Cursor::new(5, 2).end(), 5);
    }

    #[test]
    fn start_and_end_agree_for_empty_range() {
        let range = Cursor::point(7);
        assert_eq!(range.start(), range.end());
    }

    #[test]
    fn len_is_zero_for_empty_range() {
        assert_eq!(Cursor::point(7).len(), 0);
    }

    #[test]
    fn len_ignores_direction() {
        assert_eq!(Cursor::new(2, 5).len(), 3);
        assert_eq!(Cursor::new(5, 2).len(), 3);
    }

    #[test]
    fn is_empty_true_when_anchor_equals_head() {
        assert!(Cursor::new(5, 5).is_empty());
        assert!(Cursor::point(0).is_empty());
    }

    #[test]
    fn is_empty_false_for_nonzero_width() {
        assert!(!Cursor::new(2, 5).is_empty());
        assert!(!Cursor::new(5, 2).is_empty());
    }

    #[test]
    fn direction_forward_when_head_greater_than_anchor() {
        assert_eq!(Cursor::new(2, 5).direction(), Direction::Forward);
    }

    #[test]
    fn direction_backward_when_head_less_than_anchor() {
        assert_eq!(Cursor::new(5, 2).direction(), Direction::Backward);
    }

    #[test]
    fn direction_forward_for_empty_range() {
        assert_eq!(Cursor::point(5).direction(), Direction::Forward);
    }

    #[test]
    fn flip_swaps_anchor_and_head() {
        let flipped = Cursor::new(2, 5).flip();
        assert_eq!(flipped, Cursor::new(5, 2));
    }

    #[test]
    fn flip_twice_returns_original() {
        let range = Cursor::new(2, 5);
        assert_eq!(range.flip().flip(), range);
    }

    #[test]
    fn flip_of_empty_range_is_unchanged() {
        let range = Cursor::point(5);
        assert_eq!(range.flip(), range);
    }

    #[test]
    fn with_direction_noop_when_already_forward() {
        let range = Cursor::new(2, 5);
        assert_eq!(range.with_direction(Direction::Forward), range);
    }

    #[test]
    fn with_direction_noop_when_already_backward() {
        let range = Cursor::new(5, 2);
        assert_eq!(range.with_direction(Direction::Backward), range);
    }

    #[test]
    fn with_direction_flips_forward_to_backward() {
        let range = Cursor::new(2, 5);
        assert_eq!(range.with_direction(Direction::Backward), Cursor::new(5, 2));
    }

    #[test]
    fn with_direction_flips_backward_to_forward() {
        let range = Cursor::new(5, 2);
        assert_eq!(range.with_direction(Direction::Forward), Cursor::new(2, 5));
    }

    #[test]
    fn with_direction_on_empty_range_stays_forward() {
        let range = Cursor::point(5);
        assert_eq!(range.with_direction(Direction::Forward), range);
        // Empty range is already Forward; asking for Backward flips it to
        // the same point (anchor == head).
        assert_eq!(range.with_direction(Direction::Backward), range);
    }

    #[test]
    fn extend_forward_shrinks_anchor_left() {
        let range = Cursor::new(5, 8);
        assert_eq!(range.extend(2, 3), Cursor::new(2, 8));
    }

    #[test]
    fn extend_forward_grows_head_right() {
        let range = Cursor::new(2, 5);
        assert_eq!(range.extend(6, 8), Cursor::new(2, 8));
    }

    #[test]
    fn extend_forward_grows_both_sides() {
        let range = Cursor::new(4, 6);
        assert_eq!(range.extend(2, 8), Cursor::new(2, 8));
    }

    #[test]
    fn extend_forward_noop_when_range_already_covers() {
        let range = Cursor::new(1, 9);
        assert_eq!(range.extend(3, 5), range);
    }

    #[test]
    fn extend_backward_preserves_direction() {
        let range = Cursor::new(8, 2);
        let result = range.extend(4, 6);
        assert_eq!(result.direction(), Direction::Backward);
    }

    #[test]
    fn extend_backward_grows_head_left() {
        let range = Cursor::new(8, 5);
        assert_eq!(range.extend(2, 3), Cursor::new(8, 2));
    }

    #[test]
    fn extend_backward_grows_anchor_right() {
        let range = Cursor::new(5, 2);
        assert_eq!(range.extend(6, 8), Cursor::new(8, 2));
    }

    #[test]
    fn extend_from_empty_range_stays_forward() {
        let range = Cursor::point(5);
        let result = range.extend(3, 7);
        assert_eq!(result.direction(), Direction::Forward);
        assert_eq!(result, Cursor::new(3, 7));
    }

    #[test]
    fn extend_with_zero_width_target_is_safe() {
        let range = Cursor::new(2, 5);
        assert_eq!(range.extend(3, 3), range);
    }

    #[test]
    fn contains_false_for_empty_range() {
        let range = Cursor::point(5);
        assert!(!range.contains(5));
        assert!(!range.contains(4));
        assert!(!range.contains(6));
    }

    #[test]
    fn contains_is_direction_agnostic() {
        let forward = Cursor::new(2, 5);
        let backward = Cursor::new(5, 2);
        for pos in 0..=6 {
            assert_eq!(
                forward.contains(pos),
                backward.contains(pos),
                "mismatch at {pos}"
            );
        }
    }

    // --- new accessors and movement helpers ---

    #[test]
    fn anchor_and_head_accessors() {
        let range = Cursor::new(3, 7);
        assert_eq!(range.anchor(), 3);
        assert_eq!(range.head(), 7);
    }

    #[test]
    fn to_range_returns_start_to_end() {
        assert_eq!(Cursor::new(2, 5).to_range(), 2..5);
        assert_eq!(Cursor::new(5, 2).to_range(), 2..5);
        assert_eq!(Cursor::point(4).to_range(), 4..4);
    }

    #[test]
    fn move_head_preserves_anchor() {
        let range = Cursor::new(2, 5);
        assert_eq!(range.move_head(8), Cursor::new(2, 8));
        assert_eq!(range.move_head(0), Cursor::new(2, 0));
    }

    #[test]
    fn move_head_from_point_creates_range() {
        assert_eq!(Cursor::point(3).move_head(7), Cursor::new(3, 7));
    }

    #[test]
    fn collapse_to_drops_anchor_and_moves_head() {
        let range = Cursor::new(2, 5);
        assert_eq!(range.collapse_to(8), Cursor::point(8));
    }

    #[test]
    fn collapse_drops_anchor_at_current_head() {
        let range = Cursor::new(2, 5);
        assert_eq!(range.collapse(), Cursor::point(5));
    }

    #[test]
    fn collapse_on_point_is_noop() {
        let range = Cursor::point(5);
        assert_eq!(range.collapse(), range);
    }

    #[test]
    fn default_is_point_at_zero() {
        assert_eq!(Cursor::default(), Cursor::point(0));
    }

    // --- caret (block-cursor display position) -------------------------------

    #[test]
    fn caret_of_point_is_head() {
        assert_eq!(Cursor::point(2).caret("hello"), 2);
        assert_eq!(Cursor::point(0).caret("hello"), 0);
    }

    #[test]
    fn caret_of_forward_block_retreats_one_grapheme() {
        assert_eq!(Cursor::new(0, 3).caret("hello"), 2);
    }

    #[test]
    fn caret_of_backward_range_is_head() {
        assert_eq!(Cursor::new(5, 2).caret("hello"), 2);
    }

    #[test]
    fn caret_retreats_past_multibyte_grapheme() {
        assert_eq!(Cursor::new(0, 5).caret("café"), 3);
    }

    #[test]
    fn caret_retreats_past_zwj_emoji_as_one() {
        let buf = "a👨‍👩‍👧";
        assert_eq!(Cursor::new(0, buf.len()).caret(buf), 1);
    }

    #[test]
    fn caret_of_empty_buffer_point_is_zero() {
        assert_eq!(Cursor::point(0).caret(""), 0);
    }

    // --- put_cursor (block-cursor caret placement) ---------------------------

    #[test]
    fn put_cursor_non_extend_collapses_to_point() {
        assert_eq!(
            Cursor::new(2, 4).put_cursor("hello", 3, Movement::Move, CaretGeometry::Block),
            Cursor::point(3)
        );
    }

    #[test]
    fn put_cursor_extend_forward_places_head_on_far_edge() {
        // [0,1) extend to byte 2 → [0,3); caret retreats to 2 (the 'l')
        let c = Cursor::new(0, 1).put_cursor("hello", 2, Movement::Extend, CaretGeometry::Block);
        assert_eq!(c, Cursor::new(0, 3));
        assert_eq!(c.caret("hello"), 2);
    }

    #[test]
    fn put_cursor_extend_no_flip_stays_backward() {
        // backward [4,2) extend further left to 1, no crossing → [4,1)
        let c = Cursor::new(4, 2).put_cursor("hello", 1, Movement::Extend, CaretGeometry::Block);
        assert_eq!(c, Cursor::new(4, 1));
        assert_eq!(c.caret("hello"), 1);
    }

    #[test]
    fn put_cursor_extend_flip_forward_to_backward_keeps_anchor_grapheme() {
        // the worked example: [2,4) drag caret to 0 → anchor hops 2→3 → [3,0),
        // so the 'l' at byte 2 (the start grapheme) stays covered.
        let c = Cursor::new(2, 4).put_cursor("hello", 0, Movement::Extend, CaretGeometry::Block);
        assert_eq!(c, Cursor::new(3, 0));
        assert_eq!(c.caret("hello"), 0);
        assert!(c.contains(2)); // start grapheme survived the turn
    }

    #[test]
    fn put_cursor_extend_flip_backward_to_forward_keeps_anchor_grapheme() {
        // backward [4,2) drag caret right to 5 → anchor hops 4→3 → [3,5)
        let c = Cursor::new(4, 2).put_cursor("hello", 5, Movement::Extend, CaretGeometry::Block);
        assert_eq!(c, Cursor::new(3, 5));
        assert_eq!(c.caret("hello"), 4);
        assert!(c.contains(3)); // the 'l' at 3 (start grapheme) survived
    }

    #[test]
    fn put_cursor_extend_flip_across_multibyte_anchor() {
        // "café": é is [3,5). forward [3,5) (on é) drag caret to 0 → anchor hops
        // 3→5 (far edge of é) → [5,0); the whole é stays covered.
        let c = Cursor::new(3, 5).put_cursor("café", 0, Movement::Extend, CaretGeometry::Block);
        assert_eq!(c, Cursor::new(5, 0));
        assert!(c.contains(3) && c.contains(4)); // both bytes of é covered
    }
}