textual 1.0.0-dev

A reactive TUI framework inspired by the Python Textual library
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
use crossterm::event::{KeyCode, KeyModifiers};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

use crate::keys::KeyEventData;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MoveUnit {
    Grapheme,
    Word,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EditCommand {
    InsertChar(char),
    InsertNewline,
    Submit,
    Copy,
    Cut,
    Paste,
    MoveLeft {
        select: bool,
        unit: MoveUnit,
    },
    MoveRight {
        select: bool,
        unit: MoveUnit,
    },
    MoveUp {
        select: bool,
    },
    MoveDown {
        select: bool,
    },
    MoveHome {
        select: bool,
    },
    MoveEnd {
        select: bool,
    },
    Backspace {
        unit: MoveUnit,
    },
    Delete {
        unit: MoveUnit,
    },
    DeleteToStart,
    DeleteToEnd,
    DeleteLine,
    SelectAll,
    /// Used in text_area pattern matching for line selection.
    #[allow(dead_code)]
    SelectLine,
    Undo,
    Redo,
}

pub(crate) fn edit_command_from_key(key: &KeyEventData, multiline: bool) -> Option<EditCommand> {
    let mut mods_without_shift = key.modifiers;
    mods_without_shift.remove(KeyModifiers::SHIFT);

    let has_extra_modifiers =
        mods_without_shift.intersects(KeyModifiers::ALT | KeyModifiers::HYPER | KeyModifiers::META);
    let ctrl_shortcut = !has_extra_modifiers && mods_without_shift == KeyModifiers::CONTROL;
    let super_shortcut = !has_extra_modifiers && mods_without_shift == KeyModifiers::SUPER;
    let plain_or_shift = !has_extra_modifiers && mods_without_shift.is_empty();
    let has_text_blocking_modifier = key.modifiers.intersects(
        KeyModifiers::CONTROL
            | KeyModifiers::SUPER
            | KeyModifiers::ALT
            | KeyModifiers::HYPER
            | KeyModifiers::META,
    );
    let shift = key.modifiers.contains(KeyModifiers::SHIFT);

    match key.code {
        KeyCode::Char('u') if ctrl_shortcut => Some(EditCommand::DeleteToStart),
        KeyCode::Char('d') if ctrl_shortcut => Some(EditCommand::Delete {
            unit: MoveUnit::Grapheme,
        }),
        KeyCode::Char('k') if ctrl_shortcut && !shift => Some(EditCommand::DeleteToEnd),
        KeyCode::Char('k') if ctrl_shortcut && shift => Some(EditCommand::DeleteLine),
        KeyCode::Char('f') if ctrl_shortcut => Some(EditCommand::MoveRight {
            select: shift,
            unit: MoveUnit::Grapheme,
        }),
        KeyCode::Char('a') if ctrl_shortcut => Some(EditCommand::SelectAll),
        KeyCode::Char('z') if ctrl_shortcut && !shift => Some(EditCommand::Undo),
        KeyCode::Char('z') if ctrl_shortcut && shift => Some(EditCommand::Redo),
        KeyCode::Char('y') if ctrl_shortcut => Some(EditCommand::Redo),
        KeyCode::Char(ch) if (ctrl_shortcut || super_shortcut) && ch.eq_ignore_ascii_case(&'x') => {
            Some(EditCommand::Cut)
        }
        KeyCode::Char(ch) if (ctrl_shortcut || super_shortcut) && ch.eq_ignore_ascii_case(&'c') => {
            Some(EditCommand::Copy)
        }
        KeyCode::Char(ch) if (ctrl_shortcut || super_shortcut) && ch.eq_ignore_ascii_case(&'v') => {
            Some(EditCommand::Paste)
        }
        KeyCode::Char(ch) if super_shortcut && ch.eq_ignore_ascii_case(&'a') => {
            Some(EditCommand::MoveHome { select: shift })
        }
        KeyCode::Char(ch) if super_shortcut && ch.eq_ignore_ascii_case(&'e') => {
            Some(EditCommand::MoveEnd { select: shift })
        }
        KeyCode::Char(_) if !has_text_blocking_modifier => key
            .character
            .filter(|_| key.is_printable)
            .map(EditCommand::InsertChar),
        KeyCode::Enter if plain_or_shift && multiline => Some(EditCommand::InsertNewline),
        KeyCode::Enter if plain_or_shift => Some(EditCommand::Submit),
        KeyCode::Insert if ctrl_shortcut => Some(EditCommand::Copy),
        KeyCode::Insert if shift && plain_or_shift => Some(EditCommand::Paste),
        KeyCode::Delete if shift && plain_or_shift => Some(EditCommand::Cut),
        KeyCode::Backspace if super_shortcut && !multiline => Some(EditCommand::DeleteToStart),
        KeyCode::Backspace if ctrl_shortcut => Some(EditCommand::Backspace {
            unit: MoveUnit::Word,
        }),
        KeyCode::Backspace
            if key.modifiers == KeyModifiers::ALT
                || key.modifiers == (KeyModifiers::ALT | KeyModifiers::SHIFT) =>
        {
            Some(EditCommand::Backspace {
                unit: MoveUnit::Word,
            })
        }
        KeyCode::Backspace if plain_or_shift => Some(EditCommand::Backspace {
            unit: MoveUnit::Grapheme,
        }),
        KeyCode::Delete if ctrl_shortcut => Some(EditCommand::Delete {
            unit: MoveUnit::Word,
        }),
        KeyCode::Delete
            if key.modifiers == KeyModifiers::ALT
                || key.modifiers == (KeyModifiers::ALT | KeyModifiers::SHIFT) =>
        {
            Some(EditCommand::Delete {
                unit: MoveUnit::Word,
            })
        }
        KeyCode::Delete if plain_or_shift => Some(EditCommand::Delete {
            unit: MoveUnit::Grapheme,
        }),
        KeyCode::Left if ctrl_shortcut => Some(EditCommand::MoveLeft {
            select: shift,
            unit: MoveUnit::Word,
        }),
        KeyCode::Left if plain_or_shift => Some(EditCommand::MoveLeft {
            select: shift,
            unit: MoveUnit::Grapheme,
        }),
        KeyCode::Left if super_shortcut => Some(EditCommand::MoveHome { select: shift }),
        KeyCode::Left
            if key.modifiers == KeyModifiers::ALT
                || key.modifiers == (KeyModifiers::ALT | KeyModifiers::SHIFT) =>
        {
            Some(EditCommand::MoveLeft {
                select: shift,
                unit: MoveUnit::Word,
            })
        }
        KeyCode::Right if ctrl_shortcut => Some(EditCommand::MoveRight {
            select: shift,
            unit: MoveUnit::Word,
        }),
        KeyCode::Right if plain_or_shift => Some(EditCommand::MoveRight {
            select: shift,
            unit: MoveUnit::Grapheme,
        }),
        KeyCode::Right if super_shortcut => Some(EditCommand::MoveEnd { select: shift }),
        KeyCode::Right
            if key.modifiers == KeyModifiers::ALT
                || key.modifiers == (KeyModifiers::ALT | KeyModifiers::SHIFT) =>
        {
            Some(EditCommand::MoveRight {
                select: shift,
                unit: MoveUnit::Word,
            })
        }
        KeyCode::Up if plain_or_shift => Some(EditCommand::MoveUp { select: shift }),
        KeyCode::Down if plain_or_shift => Some(EditCommand::MoveDown { select: shift }),
        KeyCode::Home if plain_or_shift => Some(EditCommand::MoveHome { select: shift }),
        KeyCode::End if plain_or_shift => Some(EditCommand::MoveEnd { select: shift }),
        _ => None,
    }
}

pub(crate) fn first_clipboard_line(text: &str) -> Option<&str> {
    let line_end = text.find(['\n', '\r']).unwrap_or(text.len());
    if line_end == 0 {
        return None;
    }
    text.get(..line_end)
}

pub(crate) fn prev_grapheme_boundary(s: &str, idx: usize) -> usize {
    let idx = idx.min(s.len());
    let idx = if s.is_char_boundary(idx) {
        idx
    } else {
        prev_char_boundary(s, idx)
    };
    let mut prev = 0usize;
    for boundary in grapheme_boundaries(s) {
        if boundary >= idx {
            break;
        }
        prev = boundary;
    }
    prev
}

pub(crate) fn next_grapheme_boundary(s: &str, idx: usize) -> usize {
    let idx = idx.min(s.len());
    if idx >= s.len() {
        return s.len();
    }
    let idx = if s.is_char_boundary(idx) {
        idx
    } else {
        next_char_boundary(s, idx)
    };
    for boundary in grapheme_boundaries(s) {
        if boundary > idx {
            return boundary;
        }
    }
    s.len()
}

pub(crate) fn clamp_grapheme_boundary(s: &str, idx: usize) -> usize {
    if idx >= s.len() {
        return s.len();
    }
    let idx = if s.is_char_boundary(idx) {
        idx
    } else {
        prev_char_boundary(s, idx)
    };
    let mut clamped = 0usize;
    for boundary in grapheme_boundaries(s) {
        if boundary > idx {
            break;
        }
        clamped = boundary;
    }
    clamped
}

pub(crate) fn cell_len_prefix(s: &str, byte_end: usize) -> usize {
    let mut cells = 0usize;
    let end = byte_end.min(s.len());
    for (start, grapheme) in s.grapheme_indices(true) {
        if start >= end {
            break;
        }
        cells = cells.saturating_add(grapheme_cell_width(grapheme));
    }
    cells
}

pub(crate) fn byte_index_from_cell_x(s: &str, target_cell: usize) -> usize {
    let mut cells = 0usize;
    let mut last = 0usize;
    for (start, grapheme) in s.grapheme_indices(true) {
        let width = grapheme_cell_width(grapheme);
        let mid = cells.saturating_add(width / 2);
        if target_cell <= mid {
            return start;
        }
        cells = cells.saturating_add(width);
        last = start + grapheme.len();
        if target_cell < cells {
            return last;
        }
    }
    last
}

pub(crate) fn grapheme_cell_width(grapheme: &str) -> usize {
    UnicodeWidthStr::width(grapheme).max(1)
}

pub(crate) fn prev_word_boundary(s: &str, idx: usize) -> usize {
    if s.is_empty() {
        return 0;
    }
    let mut cursor = clamp_grapheme_boundary(s, idx);
    while cursor > 0 {
        let prev = prev_grapheme_boundary(s, cursor);
        if !s[prev..cursor].chars().all(char::is_whitespace) {
            break;
        }
        cursor = prev;
    }
    while cursor > 0 {
        let prev = prev_grapheme_boundary(s, cursor);
        if s[prev..cursor].chars().all(char::is_whitespace) {
            break;
        }
        cursor = prev;
    }
    cursor
}

pub(crate) fn next_word_boundary(s: &str, idx: usize) -> usize {
    if s.is_empty() {
        return 0;
    }
    let mut cursor = clamp_grapheme_boundary(s, idx);
    while cursor < s.len() {
        let next = next_grapheme_boundary(s, cursor);
        if !s[cursor..next].chars().all(char::is_whitespace) {
            break;
        }
        cursor = next;
    }
    while cursor < s.len() {
        let next = next_grapheme_boundary(s, cursor);
        if s[cursor..next].chars().all(char::is_whitespace) {
            break;
        }
        cursor = next;
    }
    cursor
}

fn prev_char_boundary(s: &str, mut idx: usize) -> usize {
    idx = idx.min(s.len());
    while idx > 0 && !s.is_char_boundary(idx) {
        idx -= 1;
    }
    idx
}

fn next_char_boundary(s: &str, mut idx: usize) -> usize {
    idx = idx.min(s.len());
    if idx >= s.len() {
        return s.len();
    }
    idx += 1;
    while idx < s.len() && !s.is_char_boundary(idx) {
        idx += 1;
    }
    idx.min(s.len())
}

fn grapheme_boundaries(s: &str) -> impl Iterator<Item = usize> + '_ {
    s.grapheme_indices(true)
        .map(|(start, _)| start)
        .chain(std::iter::once(s.len()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    #[test]
    fn boundaries_follow_grapheme_clusters() {
        let s = "a\u{0301}👩‍🚀z";
        let a_acute_end = "a\u{0301}".len();
        let astronaut_start = a_acute_end;
        let astronaut_end = astronaut_start + "👩‍🚀".len();

        assert_eq!(next_grapheme_boundary(s, 0), a_acute_end);
        assert_eq!(next_grapheme_boundary(s, astronaut_start), astronaut_end);
        assert_eq!(prev_grapheme_boundary(s, astronaut_end), astronaut_start);
    }

    #[test]
    fn cell_x_maps_to_grapheme_boundaries() {
        let s = "a\u{0301}👩‍🚀b";
        let astr_start = "a\u{0301}".len();
        let astr_end = astr_start + "👩‍🚀".len();

        assert_eq!(byte_index_from_cell_x(s, 0), 0);
        assert_eq!(byte_index_from_cell_x(s, 1), astr_start);
        assert_eq!(byte_index_from_cell_x(s, 2), astr_start);
        assert_eq!(byte_index_from_cell_x(s, 3), astr_end);
    }

    #[test]
    fn word_boundaries_skip_whitespace_and_clusters() {
        let s = "go  a\u{0301} 👩‍🚀 end";
        let end_word_start = s.find("end").unwrap();
        assert_eq!(prev_word_boundary(s, s.len()), end_word_start);
        assert_eq!(next_word_boundary(s, 0), 2);
        assert_eq!(next_word_boundary(s, 2), 7);
    }

    #[test]
    fn key_mapping_handles_word_and_selection_commands() {
        let left_word = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Left,
                KeyModifiers::CONTROL | KeyModifiers::SHIFT,
            )),
            false,
        );
        assert_eq!(
            left_word,
            Some(EditCommand::MoveLeft {
                select: true,
                unit: MoveUnit::Word
            })
        );
        let ctrl_u = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Char('u'),
                KeyModifiers::CONTROL,
            )),
            false,
        );
        assert_eq!(ctrl_u, Some(EditCommand::DeleteToStart));
    }

    #[test]
    fn key_mapping_includes_clipboard_commands() {
        let copy = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Char('c'),
                KeyModifiers::CONTROL,
            )),
            false,
        );
        assert_eq!(copy, Some(EditCommand::Copy));

        let cut = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Char('x'),
                KeyModifiers::CONTROL,
            )),
            false,
        );
        assert_eq!(cut, Some(EditCommand::Cut));

        let paste = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Char('v'),
                KeyModifiers::CONTROL,
            )),
            false,
        );
        assert_eq!(paste, Some(EditCommand::Paste));

        let cut_super = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Char('x'),
                KeyModifiers::SUPER,
            )),
            false,
        );
        assert_eq!(cut_super, Some(EditCommand::Cut));

        let paste_super = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Char('v'),
                KeyModifiers::SUPER,
            )),
            false,
        );
        assert_eq!(paste_super, Some(EditCommand::Paste));
    }

    #[test]
    fn key_mapping_ignores_clipboard_chords_with_extra_modifiers() {
        let alt_ctrl_v = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Char('v'),
                KeyModifiers::CONTROL | KeyModifiers::ALT,
            )),
            false,
        );
        assert_eq!(alt_ctrl_v, None);

        let ctrl_super_c = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Char('c'),
                KeyModifiers::CONTROL | KeyModifiers::SUPER,
            )),
            false,
        );
        assert_eq!(ctrl_super_c, None);
    }

    #[test]
    fn first_clipboard_line_handles_newline_variants() {
        assert_eq!(first_clipboard_line("hello\nworld"), Some("hello"));
        assert_eq!(first_clipboard_line("hello\r\nworld"), Some("hello"));
        assert_eq!(first_clipboard_line("hello\rworld"), Some("hello"));
        assert_eq!(first_clipboard_line("\nworld"), None);
        assert_eq!(first_clipboard_line(""), None);
    }

    #[test]
    fn key_mapping_supports_insert_delete_clipboard_chords() {
        let copy = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Insert,
                KeyModifiers::CONTROL,
            )),
            false,
        );
        assert_eq!(copy, Some(EditCommand::Copy));

        let paste = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Insert,
                KeyModifiers::SHIFT,
            )),
            false,
        );
        assert_eq!(paste, Some(EditCommand::Paste));

        let cut = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Delete,
                KeyModifiers::SHIFT,
            )),
            false,
        );
        assert_eq!(cut, Some(EditCommand::Cut));
    }

    #[test]
    fn key_mapping_supports_alt_and_super_navigation_shortcuts() {
        let alt_left = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Left,
                KeyModifiers::ALT,
            )),
            false,
        );
        assert_eq!(
            alt_left,
            Some(EditCommand::MoveLeft {
                select: false,
                unit: MoveUnit::Word
            })
        );

        let super_left = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Left,
                KeyModifiers::SUPER,
            )),
            false,
        );
        assert_eq!(super_left, Some(EditCommand::MoveHome { select: false }));

        let super_backspace = edit_command_from_key(
            &crate::keys::KeyEventData::from_crossterm(KeyEvent::new(
                KeyCode::Backspace,
                KeyModifiers::SUPER,
            )),
            false,
        );
        assert_eq!(super_backspace, Some(EditCommand::DeleteToStart));
    }
}