croft-software 0.2.132

VSCode-style TUI written in Rust
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
//! Single-line text editing around a caret: the pure functions every text
//! input shares (#1729).
//!
//! An input row in croft is a `String` plus a caret, and until now each one
//! edited by pushing to or popping from the end. These functions give them all
//! the same caret model without a new widget type, so a field keeps the
//! `String` the rest of the code already reads and adds one `usize`:
//!
//! - The caret is a **char index** (`0..=text.chars().count()`), the unit the
//!   commit box's `message_cursor` and the find bar already use. Every function
//!   clamps what it is given, so a caret left stale by a wholesale text
//!   replacement degrades to "at the end" instead of panicking.
//! - A single step (Left, Right, Backspace, Delete) moves by an extended
//!   grapheme cluster, so `é` written as two code points, an emoji with a
//!   skin-tone modifier or a Hangul syllable is one step. A word step walks
//!   word and non-word runs ([`crate::widgets::editor::is_word_char`]) and
//!   lands on a cluster boundary too.
//! - Editing functions return the new text and the new caret. They never
//!   touch a selection: a field with one deletes it first and edits at the
//!   point it left.
//! - [`window`] places the row's text on screen by display cells, scrolling a
//!   long text so the caret stays in view.

use unicode_segmentation::UnicodeSegmentation;

/// Number of chars in `text`: the unit of a caret.
pub fn char_len(text: &str) -> usize {
    text.chars().count()
}

/// `caret` limited to the text and moved back to the start of the grapheme
/// cluster it falls inside, so a stale or clicked caret never splits one.
pub fn clamp(text: &str, caret: usize) -> usize {
    cluster_floor(text, caret.min(char_len(text)))
}

/// Byte offset of char index `at` (the text's length for an index past it).
pub fn byte_of(text: &str, at: usize) -> usize {
    text.char_indices().nth(at).map_or(text.len(), |(i, _)| i)
}

/// Char index of byte offset `byte`, the inverse of [`byte_of`].
pub fn char_of(text: &str, byte: usize) -> usize {
    text[..byte.min(text.len())].chars().count()
}

/// Start (as a char index) of the grapheme cluster that ends at `at`: one
/// step left. `0` stays `0`.
fn cluster_before(text: &str, at: usize) -> usize {
    if text.is_ascii() {
        return at.saturating_sub(1);
    }
    let mut start = 0;
    let mut prev = 0;
    for g in text.graphemes(true) {
        if start >= at {
            break;
        }
        prev = start;
        start += g.chars().count();
    }
    prev
}

/// End (as a char index) of the grapheme cluster that starts at `at`: one
/// step right, saturating at the end of the text.
fn cluster_after(text: &str, at: usize) -> usize {
    if text.is_ascii() {
        return (at + 1).min(text.len());
    }
    let mut end = 0;
    for g in text.graphemes(true) {
        end += g.chars().count();
        if end > at {
            return end;
        }
    }
    end
}

/// `at` moved back to the start of the cluster it falls inside.
fn cluster_floor(text: &str, at: usize) -> usize {
    if text.is_ascii() {
        return at.min(text.len());
    }
    let mut start = 0;
    for g in text.graphemes(true) {
        let len = g.chars().count();
        if start + len > at {
            return start;
        }
        start += len;
    }
    start
}

/// Whether each char of `text` is part of a word. A combining mark or
/// variation selector takes the class of the char it follows, as in the
/// editor's `word_char_at`, so a word walk never stops between `e` and its
/// accent. One forward pass: asking `word_char_at` char by char rescans a run
/// of marks back to its base each time, which a long pasted run of them makes
/// quadratic.
fn word_flags(text: &str) -> Vec<bool> {
    let joins = |c: char| !c.is_control() && unicode_width::UnicodeWidthChar::width(c) == Some(0);
    let mut flags: Vec<bool> = Vec::with_capacity(text.len());
    for c in text.chars() {
        let flag = match flags.last() {
            Some(&prev) if joins(c) => prev,
            _ => crate::widgets::editor::is_word_char(c),
        };
        flags.push(flag);
    }
    flags
}

/// Where a word walk ends when moving left from `at`: back over a run of
/// non-word characters first, then over the word, as a text field walks.
fn word_start_before(text: &str, at: usize) -> usize {
    let word = word_flags(text);
    let mut i = at.min(word.len());
    while i > 0 && !word[i - 1] {
        i -= 1;
    }
    while i > 0 && word[i - 1] {
        i -= 1;
    }
    cluster_floor(text, i)
}

/// Where a word walk ends when moving right from `at`.
fn word_end_after(text: &str, at: usize) -> usize {
    let word = word_flags(text);
    let mut i = at.min(word.len());
    while i < word.len() && !word[i] {
        i += 1;
    }
    while i < word.len() && word[i] {
        i += 1;
    }
    cluster_floor(text, i).max(at.min(word.len()))
}

/// `caret` one step left in `text`, by a word when `word`.
pub fn caret_left(text: &str, caret: usize, word: bool) -> usize {
    let at = clamp(text, caret);
    if word {
        word_start_before(text, at)
    } else {
        cluster_before(text, at)
    }
}

/// `caret` one step right in `text`, by a word when `word`.
pub fn caret_right(text: &str, caret: usize, word: bool) -> usize {
    let at = clamp(text, caret);
    if word {
        word_end_after(text, at)
    } else {
        cluster_after(text, at)
    }
}

/// `text` with `add` inserted at `caret`, and the caret after it. Control
/// characters are dropped: an input row is one line, so a pasted newline or
/// tab must not enter it.
pub fn insert_at(text: &str, caret: usize, add: &str) -> (String, usize) {
    let at = clamp(text, caret);
    let added: String = add.chars().filter(|c| !c.is_control()).collect();
    if added.is_empty() {
        return (text.to_string(), at);
    }
    let b = byte_of(text, at);
    let mut out = String::with_capacity(text.len() + added.len());
    out.push_str(&text[..b]);
    out.push_str(&added);
    out.push_str(&text[b..]);
    // What was inserted can join the text after it into one cluster (an `e`
    // typed before a lone combining accent): the caret then goes after that
    // cluster, never inside it, where the next edit's clamp would pull it
    // back before the inserted text.
    let end = at + char_len(&added);
    let floor = cluster_floor(&out, end);
    let caret = if floor == end {
        end
    } else {
        cluster_after(&out, floor)
    };
    (out, caret)
}

/// `text` without the cluster (or, with `word`, the run) before `caret`, and
/// the caret where the cut began.
pub fn delete_before(text: &str, caret: usize, word: bool) -> (String, usize) {
    let at = clamp(text, caret);
    let from = caret_left(text, at, word);
    if from == at {
        return (text.to_string(), at);
    }
    (cut(text, from, at), from)
}

/// `text` without the cluster (or, with `word`, the run) at `caret` (Delete),
/// the caret unmoved.
pub fn delete_at(text: &str, caret: usize, word: bool) -> (String, usize) {
    let at = clamp(text, caret);
    let to = caret_right(text, at, word);
    if to == at {
        return (text.to_string(), at);
    }
    (cut(text, at, to), at)
}

/// `text` without the chars `from..to`.
fn cut(text: &str, from: usize, to: usize) -> String {
    let (a, b) = (byte_of(text, from), byte_of(text, to));
    let mut out = String::with_capacity(text.len() - (b - a));
    out.push_str(&text[..a]);
    out.push_str(&text[b..]);
    out
}

/// One grapheme cluster of a text: where it starts (a char index) and how
/// many cells the terminal draws it in. A cluster is
/// one glyph, so 👍🏽, a flag or a ZWJ emoji is one width, not the sum of its
/// code points'.
struct Cluster {
    start: usize,
    width: usize,
}

fn clusters(text: &str) -> Vec<Cluster> {
    let mut start = 0;
    text.graphemes(true)
        .map(|g| {
            let len = g.chars().count();
            let c = Cluster {
                start,
                width: unicode_width::UnicodeWidthStr::width(g),
            };
            start += len;
            c
        })
        .collect()
}

/// Which part of a row's text is on screen.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Window {
    /// First visible char (an index into the text).
    pub start: usize,
    /// One past the last visible char.
    pub end: usize,
    /// Cell the caret is drawn on, counted from the row's left edge. Always
    /// less than the row's width, so a caret after the last char still has a
    /// cell of its own.
    pub caret_cell: usize,
}

/// The slice of `text` to draw in `avail` cells so that `caret` is in view:
/// leading chars scroll off just far enough to give the caret a cell, and the
/// rest fills what is left. A wide character that would straddle the right
/// edge is left out, as it is in the editor.
pub fn window(text: &str, caret: usize, avail: usize) -> Window {
    let cl = clusters(text);
    let total = char_len(text);
    let caret = clamp(text, caret);
    let avail = avail.max(1);
    let at = cl.iter().position(|c| c.start >= caret).unwrap_or(cl.len());
    let before_w: usize = cl[..at].iter().map(|c| c.width).sum();
    let mut first = 0;
    let mut dropped = 0;
    while first < at && before_w - dropped >= avail {
        dropped += cl[first].width;
        first += 1;
    }
    let caret_cell = before_w - dropped;
    // The cluster under the caret takes its own cell (an end-of-text caret
    // gets one too), then whatever of the rest still fits.
    let mut used = caret_cell;
    let mut last = at;
    if last < cl.len() {
        let w = cl[last].width.max(1);
        if used + w <= avail {
            used += w;
            last += 1;
            while last < cl.len() {
                let w = cl[last].width;
                if used + w > avail {
                    break;
                }
                used += w;
                last += 1;
            }
        }
    }
    Window {
        start: cl.get(first).map_or(total, |c| c.start),
        end: cl.get(last).map_or(total, |c| c.start),
        caret_cell,
    }
}

/// The char of `text` under screen cell `cell`, counting from the row's left
/// edge when the row shows the text from char `start`: a click's caret. A
/// cell past the visible text is the end of the text; one on the second half
/// of a wide character is that character, and a click inside a cluster lands
/// on its start.
pub fn char_at_cell(text: &str, start: usize, cell: usize) -> usize {
    let mut at = 0;
    for c in clusters(text).iter().filter(|c| c.start >= start) {
        if cell < at + c.width {
            return c.start;
        }
        at += c.width;
    }
    char_len(text)
}

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

    #[test]
    fn a_click_cell_maps_to_the_char_under_it() {
        assert_eq!(char_at_cell("abc", 0, 0), 0);
        assert_eq!(char_at_cell("abc", 0, 2), 2);
        assert_eq!(char_at_cell("abc", 0, 9), 3, "past the end");
        assert_eq!(char_at_cell("abcdef", 2, 1), 3, "a scrolled row");
        // 日 is cells 0-1, 本 is 2-3.
        assert_eq!(char_at_cell("日本x", 0, 1), 0);
        assert_eq!(char_at_cell("日本x", 0, 2), 1);
        assert_eq!(char_at_cell("日本x", 0, 4), 2);
    }

    #[test]
    fn steps_move_by_cluster_not_by_code_point() {
        // `e` + combining acute is two chars, one cluster.
        let t = "ae\u{301}b";
        assert_eq!(caret_right(t, 1, false), 3, "over e + accent in one step");
        assert_eq!(caret_left(t, 3, false), 1);
        // A flag is two regional indicators, one cluster.
        let f = "x🇪🇸y";
        assert_eq!(caret_right(f, 1, false), 3);
        assert_eq!(caret_left(f, 3, false), 1);
        // Ends saturate.
        assert_eq!(caret_left("ab", 0, false), 0);
        assert_eq!(caret_right("ab", 2, false), 2);
        assert_eq!(caret_right("ab", 99, false), 2, "a stale caret clamps");
    }

    #[test]
    fn word_steps_skip_a_run_then_a_word() {
        let t = "foo  bar_baz, qux";
        assert_eq!(caret_left(t, 17, true), 14, "back over qux");
        assert_eq!(caret_left(t, 14, true), 5, "back over `, ` and bar_baz");
        assert_eq!(caret_left(t, 5, true), 0);
        assert_eq!(caret_right(t, 0, true), 3);
        assert_eq!(caret_right(t, 3, true), 12, "over the gap and bar_baz");
        assert_eq!(caret_right(t, 17, true), 17);
        // Cyrillic is word text.
        assert_eq!(caret_left("привет мир", 10, true), 7);
    }

    #[test]
    fn insert_lands_at_the_caret_and_drops_control_chars() {
        assert_eq!(insert_at("ac", 1, "b"), ("abc".to_string(), 2));
        assert_eq!(insert_at("ac", 9, "b"), ("acb".to_string(), 3));
        assert_eq!(insert_at("ac", 0, "x\ny\tz"), ("xyzac".to_string(), 3));
        assert_eq!(insert_at("ac", 1, "\n"), ("ac".to_string(), 1));
        assert_eq!(insert_at("日本", 1, "語"), ("日語本".to_string(), 2));
    }

    #[test]
    fn deletes_cut_a_cluster_or_a_word_and_keep_the_caret_honest() {
        assert_eq!(delete_before("abc", 2, false), ("ac".to_string(), 1));
        assert_eq!(delete_before("abc", 0, false), ("abc".to_string(), 0));
        assert_eq!(delete_at("abc", 1, false), ("ac".to_string(), 1));
        assert_eq!(delete_at("abc", 3, false), ("abc".to_string(), 3));
        // The whole `é` goes with one Backspace.
        assert_eq!(delete_before("ae\u{301}", 3, false), ("a".to_string(), 1));
        assert_eq!(delete_before("foo bar", 7, true), ("foo ".to_string(), 4));
        assert_eq!(delete_at("foo bar", 0, true), (" bar".to_string(), 0));
    }

    #[test]
    fn window_keeps_the_caret_in_view_and_inside_the_row() {
        // Fits: nothing scrolls, the caret sits after the text.
        let w = window("abc", 3, 10);
        assert_eq!((w.start, w.end, w.caret_cell), (0, 3, 3));
        // Caret mid-text of a fitting text.
        let w = window("abcdef", 2, 10);
        assert_eq!((w.start, w.end, w.caret_cell), (0, 6, 2));
        // Too long, caret at the end: leading chars scroll away, and the
        // caret's cell is the last one.
        let w = window("abcdefghij", 10, 5);
        assert_eq!((w.start, w.end, w.caret_cell), (6, 10, 4));
        // Caret at the start of a long text: the head shows.
        let w = window("abcdefghij", 0, 5);
        assert_eq!((w.start, w.end, w.caret_cell), (0, 5, 0));
        // Never a caret outside the row.
        for caret in 0..=10 {
            let w = window("abcdefghij", caret, 5);
            assert!(w.caret_cell < 5, "caret {caret}: {w:?}");
            assert!(w.start <= caret && caret <= w.end.max(caret));
        }
    }

    #[test]
    fn window_counts_wide_characters_in_cells() {
        // Each CJK char is two cells: five cells hold two and a half.
        let w = window("日本語", 0, 5);
        assert_eq!((w.start, w.end), (0, 2), "the third does not straddle");
        let w = window("日本語", 3, 5);
        assert!(w.caret_cell < 5);
        assert_eq!(w.start, 1, "one char scrolled off to fit the caret");
    }

    #[test]
    fn a_word_walk_keeps_a_combining_mark_with_its_base() {
        // "e" + U+0301 is one letter: Ctrl+Right from the start goes to the
        // end of "e\u{301}x", not to the middle of the first cluster.
        let t = "e\u{301}x y";
        assert_eq!(caret_right(t, 0, true), 3);
        assert_eq!(caret_left(t, 3, true), 0);
    }

    #[test]
    fn word_flags_classify_as_the_editor_does() {
        let t = "e\u{301}x \u{301}y-\u{FE0F}_z";
        let chars: Vec<char> = t.chars().collect();
        let want: Vec<bool> = (0..chars.len())
            .map(|i| crate::widgets::editor::word_char_at(&chars, i))
            .collect();
        assert_eq!(word_flags(t), want);
    }

    #[test]
    fn typing_before_a_lone_accent_puts_the_caret_after_the_cluster_it_makes() {
        // "e" typed before U+0301 becomes one cluster, "é": the caret goes
        // after it, so the next char lands after the accent, not before "e".
        let (t, c) = insert_at("\u{301}x", 0, "e");
        assert_eq!((t.as_str(), c), ("e\u{301}x", 2));
        let (t, c) = insert_at(&t, c, "d");
        assert_eq!((t.as_str(), c), ("e\u{301}dx", 3));
    }

    #[test]
    fn an_emoji_cluster_is_one_glyph_for_width_and_clicks() {
        // 👍🏽 is two code points drawn in two cells, not four.
        let t = "a\u{1F44D}\u{1F3FD}b";
        let w = window(t, 3, 4);
        assert_eq!((w.start, w.end, w.caret_cell), (0, 4, 3));
        // Cells: a=0, thumbs=1-2, b=3. A click on the second cell of the
        // emoji lands on its start, never on the modifier.
        assert_eq!(char_at_cell(t, 0, 2), 1);
        assert_eq!(char_at_cell(t, 0, 3), 3);
        // A caret inside the cluster snaps to its start.
        assert_eq!(clamp(t, 2), 1);
    }
}