reedline 0.50.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
use std::cmp::Ordering;

use crate::core_editor::{
    graphemes::{
        ensure_grapheme_boundary_next, ensure_grapheme_boundary_prev, next_grapheme_boundary,
        prev_grapheme_boundary,
    },
    Cursor,
};

/// Where the cursor's head may *rest* after an edit, per editor paradigm.
///
/// Applied at the single commit boundary by [`commit`], layered on top of the
/// universal coherence pass ([`recohere`]). Each edit mode maps to one variant;
/// the core never inspects the mode, only the resulting policy.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RestPolicy {
    /// The head may rest anywhere between graphemes, including past the last one
    /// (at `buf.len()`). Emacs / Vi insert — the ordinary text caret.
    Between,
    /// The head may not rest past the last grapheme: a head at the end is pulled
    /// back onto the final grapheme. Vi normal mode — the cursor invariant
    /// enforced structurally here instead of by a maintenance command.
    OnGrapheme,
    /// The resting cursor always covers exactly one grapheme: a point is widened
    /// onto the grapheme to its right, or — at the buffer end, where there is
    /// none — onto the grapheme to its left. Mirrors Helix's `Range::min_width_1`.
    /// The policy for Vi visual mode, whose selection is always at least the
    /// grapheme it sits on. A line terminator is not a cell: the cursor covers
    /// the last grapheme of the line instead, like vim.
    Block,
    /// [`Block`](RestPolicy::Block) with the terminator counted as a cell, so
    /// `l` walks onto the `\n` and an operator there joins the lines. Helix
    /// normal / select, whose `Range` is over the newline like any other char.
    #[cfg(feature = "helix")]
    BlockOverNewline,
}

impl RestPolicy {
    /// Whether the resting cursor covers exactly one grapheme (either block
    /// policy).
    pub(crate) fn is_block(self) -> bool {
        match self {
            RestPolicy::Block => true,
            #[cfg(feature = "helix")]
            RestPolicy::BlockOverNewline => true,
            RestPolicy::Between | RestPolicy::OnGrapheme => false,
        }
    }

    /// Whether a line terminator is a cell the caret may rest on. Helix only;
    /// every other mode steps over or clamps before it.
    pub(crate) fn covers_terminator(self) -> bool {
        match self {
            RestPolicy::Between | RestPolicy::OnGrapheme | RestPolicy::Block => false,
            #[cfg(feature = "helix")]
            RestPolicy::BlockOverNewline => true,
        }
    }
}

/// Make a cursor *coherent* for `buf`: clamp both ends into `[0, buf.len()]` and
/// snap them to grapheme boundaries, expanding outward so whole graphemes stay
/// covered — the low end floors, the high end ceils, and a point floors while
/// staying a point.
///
/// Universal across edit modes and idempotent, so it is safe to run after any
/// edit. The mode-specific resting rule is layered on top by [`commit`].
pub(crate) fn recohere(buf: &str, c: Cursor) -> Cursor {
    let len = buf.len();

    let head = c.head().min(len);
    let anchor = c.anchor().min(len);

    let (anchor, head) = match anchor.cmp(&head) {
        // point: both floor to keep it a point
        Ordering::Equal => {
            let pos = ensure_grapheme_boundary_prev(buf, anchor);
            (pos, pos)
        }
        // forward: anchor (low) floors, head (high) ceils
        Ordering::Less => (
            ensure_grapheme_boundary_prev(buf, anchor),
            ensure_grapheme_boundary_next(buf, head),
        ),
        // backward: anchor (high) ceils, head (low) floors
        Ordering::Greater => (
            ensure_grapheme_boundary_next(buf, anchor),
            ensure_grapheme_boundary_prev(buf, head),
        ),
    };

    Cursor::new(anchor, head)
}

/// Normalize a cursor at the one commit boundary: first [`recohere`] it (universal
/// coherence), then apply the mode's [`RestPolicy`] resting rule.
///
/// Total and idempotent — `commit(buf, commit(buf, c, p), p) == commit(buf, c, p)`
/// for every input — so it can run after every command without the cursor drifting.
pub(crate) fn commit(buf: &str, c: Cursor, policy: RestPolicy) -> Cursor {
    let c = recohere(buf, c);
    let len = buf.len();
    match policy {
        RestPolicy::Between => c,
        RestPolicy::OnGrapheme => {
            // A *bare* cursor (an empty point) may not rest past the last grapheme
            // of its line: pull it back off the line terminator (or the buffer end)
            // onto that grapheme. Skip when the line is empty — the char before is
            // itself a terminator (or the buffer start), so column 0 is the only
            // cell and pulling back would cross into the previous line. A selection
            // may legitimately cover the final grapheme (head at the boundary,
            // caret one grapheme inward), so its head is left alone — inclusivity
            // is geometric now, not a query-time `+1`.
            let head = c.head();
            let past_last_grapheme = head == len || buf[head..].starts_with(['\n', '\r']);
            let line_has_grapheme = head > 0 && !buf[..head].ends_with(['\n', '\r']);
            if c.is_empty() && past_last_grapheme && line_has_grapheme {
                Cursor::point(prev_grapheme_boundary(buf, head))
            } else {
                c
            }
        }
        RestPolicy::Block => block(buf, c, false),
        #[cfg(feature = "helix")]
        RestPolicy::BlockOverNewline => block(buf, c, true),
    }
}

/// The block-caret resting rule, shared by [`RestPolicy::Block`] and the
/// helix-only `BlockOverNewline`.
fn block(buf: &str, c: Cursor, over_newline: bool) -> Cursor {
    // A block cursor always covers exactly one grapheme. Only a resting
    // *point* needs adjusting; an existing selection is already a range.
    if c.is_empty() {
        let head = c.head();
        let next = next_grapheme_boundary(buf, head);
        if next > head && (over_newline || !buf[head..].starts_with(['\n', '\r'])) {
            // widen forward onto the grapheme to the right: [head, next)
            c.move_head(next)
        } else if head > 0 && !buf[..head].ends_with(['\n', '\r']) {
            // at the buffer end there's nothing to the right, so cover the
            // last grapheme instead: [prev, head). Never crosses a line
            // boundary, in either policy — that would move the caret up a
            // line rather than widen it.
            Cursor::new(prev_grapheme_boundary(buf, head), head)
        } else {
            // empty buffer, or an empty line (no grapheme to cover without
            // crossing the newline): stay a zero-width point
            c
        }
    } else {
        c
    }
}

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

    // Buffers used across tests:
    //   "hello"   — ASCII, len 5, grapheme starts 0,1,2,3,4
    //   "caf\u{e9}" — precomposed é (2 bytes), len 5, last grapheme starts at 3
    //   "ae\u{0301}" — e + combining acute, len 4; "é" grapheme is [1,4),
    //                  so byte 2 is a char boundary but *not* a grapheme boundary
    const MIXED: &str = "a日e\u{0301}👨‍👩‍👧"; // ASCII + CJK + combining + ZWJ emoji

    // --- recohere ------------------------------------------------------------

    #[test]
    fn recohere_is_identity_on_aligned_cursors() {
        let b = "hello";
        assert_eq!(recohere(b, Cursor::new(1, 3)), Cursor::new(1, 3));
        assert_eq!(recohere(b, Cursor::new(3, 1)), Cursor::new(3, 1));
        assert_eq!(recohere(b, Cursor::point(2)), Cursor::point(2));
    }

    #[test]
    fn recohere_clamps_past_end_to_point_at_len() {
        assert_eq!(recohere("hello", Cursor::new(10, 12)), Cursor::point(5));
    }

    #[test]
    fn recohere_floors_mid_grapheme_point() {
        // point at byte 2 sits inside "é" [1,4) → floors to its start, 1
        assert_eq!(recohere("ae\u{0301}", Cursor::point(2)), Cursor::point(1));
    }

    #[test]
    fn recohere_expands_selection_outward() {
        // anchor 0 (low) floors to 0, head 2 (high, mid-grapheme) ceils to 4
        assert_eq!(recohere("ae\u{0301}", Cursor::new(0, 2)), Cursor::new(0, 4));
    }

    #[test]
    fn recohere_is_idempotent() {
        for a in (0..=MIXED.len()).filter(|&i| MIXED.is_char_boundary(i)) {
            for h in (0..=MIXED.len()).filter(|&i| MIXED.is_char_boundary(i)) {
                let once = recohere(MIXED, Cursor::new(a, h));
                assert_eq!(recohere(MIXED, once), once, "anchor={a} head={h}");
            }
        }
    }

    // --- commit: Between -----------------------------------------------------

    #[test]
    fn between_leaves_head_past_last_grapheme() {
        assert_eq!(
            commit("hello", Cursor::point(5), RestPolicy::Between),
            Cursor::point(5)
        );
    }

    #[test]
    fn between_only_recoheres() {
        // mid-grapheme point still floors (that's recohere); the policy adds nothing
        assert_eq!(
            commit("ae\u{0301}", Cursor::point(2), RestPolicy::Between),
            Cursor::point(1)
        );
    }

    // --- commit: OnGrapheme --------------------------------------------------

    #[test]
    fn on_grapheme_pulls_point_back_from_end() {
        assert_eq!(
            commit("hello", Cursor::point(5), RestPolicy::OnGrapheme),
            Cursor::point(4)
        );
    }

    #[test]
    fn on_grapheme_pulls_back_over_multibyte_grapheme() {
        // "café": last grapheme é starts at byte 3
        assert_eq!(
            commit("caf\u{e9}", Cursor::point(5), RestPolicy::OnGrapheme),
            Cursor::point(3)
        );
    }

    #[test]
    fn on_grapheme_leaves_midbuffer_point() {
        assert_eq!(
            commit("hello", Cursor::point(2), RestPolicy::OnGrapheme),
            Cursor::point(2)
        );
    }

    #[test]
    fn on_grapheme_rests_on_trailing_empty_line() {
        // A buffer ending in `\n` has an empty last line; a head at `len` sits
        // on it and must NOT be pulled back over the newline. This is the
        // `dd`-on-the-last-line case: deleting the final line leaves the cursor
        // on the new (empty) last line rather than jumping up a line.
        assert_eq!(
            commit("a\n", Cursor::point(2), RestPolicy::OnGrapheme),
            Cursor::point(2)
        );
        assert_eq!(
            commit("hello\n", Cursor::point(6), RestPolicy::OnGrapheme),
            Cursor::point(6)
        );
    }

    #[test]
    fn on_grapheme_pulls_back_from_interior_line_end() {
        // A point past the last grapheme of an *interior* line (the gap before the
        // `\n`) is pulled back onto that grapheme, like at the buffer end — vi
        // normal's caret never sits on the terminator. "abc\ndef": gap 3 -> 'c' (2).
        assert_eq!(
            commit("abc\ndef", Cursor::point(3), RestPolicy::OnGrapheme),
            Cursor::point(2)
        );
        // `\r\n` terminator: pull back over the whole grapheme. "ab\r\ncd": gap 2 -> 'b' (1).
        assert_eq!(
            commit("ab\r\ncd", Cursor::point(2), RestPolicy::OnGrapheme),
            Cursor::point(1)
        );
    }

    #[test]
    fn on_grapheme_rests_on_interior_empty_line() {
        // An empty interior line ("abc\n\ndef": the byte-4 newline is that line's
        // column 0) keeps the point — pulling back would cross up a line.
        assert_eq!(
            commit("abc\n\ndef", Cursor::point(4), RestPolicy::OnGrapheme),
            Cursor::point(4)
        );
    }

    #[test]
    fn on_grapheme_empty_buffer_is_noop() {
        assert_eq!(
            commit("", Cursor::point(0), RestPolicy::OnGrapheme),
            Cursor::point(0)
        );
    }

    #[test]
    fn on_grapheme_leaves_selection_head_at_end() {
        // A selection may cover the final grapheme: its head at `len` is left
        // alone (inclusivity is geometric now). Only a bare *point* is pulled
        // back off the end — see `on_grapheme_pulls_back_from_end`.
        assert_eq!(
            commit("hello", Cursor::new(0, 5), RestPolicy::OnGrapheme),
            Cursor::new(0, 5)
        );
    }

    // --- commit: Block -------------------------------------------------------

    #[test]
    fn block_widens_point_to_one_grapheme() {
        assert_eq!(
            commit("hello", Cursor::point(2), RestPolicy::Block),
            Cursor::new(2, 3)
        );
    }

    #[test]
    fn block_widens_over_multibyte_grapheme() {
        // "café": point at start of é (byte 3) widens to cover it, (3,5)
        assert_eq!(
            commit("caf\u{e9}", Cursor::point(3), RestPolicy::Block),
            Cursor::new(3, 5)
        );
    }

    #[test]
    fn block_point_at_end_widens_backward() {
        // no grapheme to the right at the end, so the block covers the last one:
        // point(5) → [4,5), caret on the 'o'
        assert_eq!(
            commit("hello", Cursor::point(5), RestPolicy::Block),
            Cursor::new(4, 5)
        );
    }

    #[test]
    fn block_widens_backward_over_multibyte_at_end() {
        // "café": point at end (5) → block covers the 2-byte é → [3,5)
        assert_eq!(
            commit("caf\u{e9}", Cursor::point(5), RestPolicy::Block),
            Cursor::new(3, 5)
        );
    }

    #[test]
    fn block_empty_buffer_stays_empty() {
        assert_eq!(
            commit("", Cursor::point(0), RestPolicy::Block),
            Cursor::point(0)
        );
    }

    #[test]
    fn block_does_not_rest_on_crlf_terminator() {
        // A point on the `\r` of a CRLF terminator must not widen forward over
        // the line break; it covers the last real grapheme of the line instead.
        // Mirrors the `['\n','\r']` guard OnGrapheme already uses. "ab\r\ncd":
        // point at byte 2 (the `\r`) → block over 'b' at [1,2), not [2,4).
        assert_eq!(
            commit("ab\r\ncd", Cursor::point(2), RestPolicy::Block),
            Cursor::new(1, 2)
        );
    }

    #[test]
    fn block_leaves_existing_selection() {
        assert_eq!(
            commit("hello", Cursor::new(1, 3), RestPolicy::Block),
            Cursor::new(1, 3)
        );
    }

    // --- commit: BlockOverNewline --------------------------------------------

    #[cfg(feature = "helix")]
    #[test]
    fn block_over_newline_widens_onto_the_terminator() {
        // The one difference from `Block`: "ab\ncd" at the `\n` (byte 2) covers
        // it, where `Block` falls back onto 'b'.
        assert_eq!(
            commit("ab\ncd", Cursor::point(2), RestPolicy::BlockOverNewline),
            Cursor::new(2, 3)
        );
        assert_eq!(
            commit("ab\ncd", Cursor::point(2), RestPolicy::Block),
            Cursor::new(1, 2)
        );
    }

    #[cfg(feature = "helix")]
    #[test]
    fn block_over_newline_covers_a_whole_crlf() {
        // CRLF is one grapheme, so the cell is both bytes: "ab\r\ncd" at 2.
        assert_eq!(
            commit("ab\r\ncd", Cursor::point(2), RestPolicy::BlockOverNewline),
            Cursor::new(2, 4)
        );
    }

    #[cfg(feature = "helix")]
    #[test]
    fn block_over_newline_still_will_not_widen_across_a_line() {
        // The *backward* guard is kept: at the end of a buffer ending in `\n`
        // there is nothing on this line to cover, and reaching back would put
        // the caret on the previous line. Stays a zero-width point.
        assert_eq!(
            commit("abc\n", Cursor::point(4), RestPolicy::BlockOverNewline),
            Cursor::point(4)
        );
        // An empty interior line is the same case.
        assert_eq!(
            commit("a\n\nb", Cursor::point(2), RestPolicy::BlockOverNewline),
            Cursor::new(2, 3)
        );
    }

    #[cfg(feature = "helix")]
    #[test]
    fn block_over_newline_matches_block_away_from_terminators() {
        for (buf, pos) in [("hello", 2), ("caf\u{e9}", 3), ("hello", 5), ("", 0)] {
            assert_eq!(
                commit(buf, Cursor::point(pos), RestPolicy::BlockOverNewline),
                commit(buf, Cursor::point(pos), RestPolicy::Block),
                "buf={buf:?} pos={pos}"
            );
        }
    }

    // --- commit: idempotency across every policy and char boundary -----------

    #[test]
    fn commit_is_idempotent() {
        // `MULTILINE` carries LF, CRLF, an empty interior line and a trailing
        // terminator, which is where the policies differ on newlines.
        const MULTILINE: &str = "ab\ncd\r\n\n\n";
        for policy in [
            RestPolicy::Between,
            RestPolicy::OnGrapheme,
            RestPolicy::Block,
            #[cfg(feature = "helix")]
            RestPolicy::BlockOverNewline,
        ] {
            for buf in [MIXED, MULTILINE] {
                for a in (0..=buf.len()).filter(|&i| buf.is_char_boundary(i)) {
                    for h in (0..=buf.len()).filter(|&i| buf.is_char_boundary(i)) {
                        let once = commit(buf, Cursor::new(a, h), policy);
                        assert_eq!(
                            commit(buf, once, policy),
                            once,
                            "policy={policy:?} buf={buf:?} anchor={a} head={h}"
                        );
                    }
                }
            }
        }
    }
}