tui-input 0.15.2

TUI input library supporting multiple backends
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
//! Core logic for handling input.
//!
//! # Units
//!
//! A string has four different possible notions of length or position:
//!
//! - **bytes**:  indices into the UTF-8 encoding, used only internally.
//! - **codepoints**:  Unicode scalar values (what [`str::chars`] yields).
//!   This is what [`Input::cursor`] returns and what
//!   [`InputRequest::SetCursor`] accepts.
//! - **graphemes**:  user-perceived characters (per `unicode-segmentation`).
//!   Movement and deletion ([`InputRequest::GoToPrevChar`],
//!   [`InputRequest::GoToNextChar`], [`InputRequest::DeletePrevChar`],
//!   [`InputRequest::DeleteNextChar`], [`InputRequest::GoToPrevWord`],
//!   [`InputRequest::GoToNextWord`], [`InputRequest::DeletePrevWord`],
//!   [`InputRequest::DeleteNextWord`]) step one *grapheme* or *word*
//!   at a time, which may span multiple codepoints.
//! - **display columns**:  terminal cell width (per `unicode-width`).
//!   Returned by [`Input::visual_cursor`] and [`Input::visual_scroll`].
//!
//! All four can differ for one string.  For example, `🤦🏼‍♂️` is
//! actually `"🤦🏼\u{200D}♂\u{FE0F}"`, which is 17 bytes, 5 codepoints,
//! 1 grapheme, 2 display columns.
//!
//! # Example: Without any backend
//!
//! ```
//! use tui_input::{Input, InputRequest, StateChanged};
//!
//! let mut input: Input = "Hello Worl".into();
//!
//! let req = InputRequest::InsertChar('d');
//! let resp = input.handle(req);
//!
//! assert_eq!(resp, Some(StateChanged { value: true, cursor: true }));
//! assert_eq!(input.cursor(), 11);
//! assert_eq!(input.to_string(), "Hello World");
//! ```

use unicode_segmentation::{GraphemeCursor, UnicodeSegmentation};

fn prev_grapheme(s: &str, byte: usize) -> Option<usize> {
    GraphemeCursor::new(byte, s.len(), true)
        .prev_boundary(s, 0)
        .ok()
        .flatten()
}

fn next_grapheme(s: &str, byte: usize) -> Option<usize> {
    GraphemeCursor::new(byte, s.len(), true)
        .next_boundary(s, 0)
        .ok()
        .flatten()
}

fn is_word(s: &str) -> bool {
    s.chars()
        .any(|c| !c.is_whitespace() && !c.is_ascii_punctuation())
}

fn prev_word_byte(s: &str, byte: usize) -> usize {
    let mut words = s
        .split_word_bound_indices()
        .filter(|(i, _)| *i < byte)
        .rev();
    while let Some((i, word)) = words.next() {
        if is_word(word) {
            return i;
        }
    }
    0
}

fn next_word_byte(s: &str, byte: usize) -> usize {
    let mut words = s.split_word_bound_indices().filter(|(i, _)| *i > byte);
    while let Some((i, word)) = words.next() {
        if is_word(word) {
            return i;
        }
    }
    s.len()
}

fn codepoint_to_byte(s: &str, n: usize) -> usize {
    s.char_indices().nth(n).map_or(s.len(), |(i, _)| i)
}

fn byte_to_codepoint(s: &str, byte: usize) -> usize {
    s[..byte].chars().count()
}

enum Side {
    Left,
    Right,
}

/// Input requests are used to change the input state.
///
/// Different backends can be used to convert events into requests.
#[derive(Debug, PartialOrd, PartialEq, Eq, Clone, Copy, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum InputRequest {
    SetCursor(usize),
    InsertChar(char),
    GoToPrevChar,
    GoToNextChar,
    GoToPrevWord,
    GoToNextWord,
    GoToStart,
    GoToEnd,
    DeletePrevChar,
    DeleteNextChar,
    DeletePrevWord,
    DeleteNextWord,
    DeleteLine,
    DeleteTillEnd,
    Yank,
}

#[derive(Debug, PartialOrd, PartialEq, Eq, Clone, Copy, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StateChanged {
    pub value: bool,
    pub cursor: bool,
}

pub type InputResponse = Option<StateChanged>;

/// The input buffer with cursor support.
///
/// Example:
///
/// ```
/// use tui_input::Input;
///
/// let input: Input = "Hello World".into();
///
/// assert_eq!(input.cursor(), 11);
/// assert_eq!(input.to_string(), "Hello World");
/// ```
#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Input {
    value: String,
    /// Codepoints preceding the cursor.  See the module-level `Units` section.
    cursor: usize,
    yank: String,
    last_was_cut: bool,
}

impl Input {
    /// Initialize a new instance with a given value
    /// Cursor will be set to the given value's length.
    pub fn new(value: String) -> Self {
        let len = value.chars().count();
        Self {
            value,
            cursor: len,
            yank: String::new(),
            last_was_cut: false,
        }
    }

    /// Set the value manually.
    /// Cursor will be set to the given value's length.
    pub fn with_value(mut self, value: String) -> Self {
        self.cursor = value.chars().count();
        self.value = value;
        self
    }

    /// Set the cursor manually.
    /// If the input is larger than the value length, it'll be auto adjusted.
    pub fn with_cursor(mut self, cursor: usize) -> Self {
        self.cursor = cursor.min(self.value.chars().count());
        self
    }

    // Reset the cursor and value to default
    pub fn reset(&mut self) {
        self.cursor = Default::default();
        self.value = Default::default();
    }

    // Reset the cursor and value to default, returning the previous value
    pub fn value_and_reset(&mut self) -> String {
        let val = self.value.clone();
        self.reset();
        val
    }

    fn add_to_yank(&mut self, deleted: String, side: Side) {
        if self.last_was_cut {
            match side {
                Side::Left => self.yank.insert_str(0, &deleted),
                Side::Right => self.yank.push_str(&deleted),
            }
        } else {
            self.yank = deleted;
        }
    }

    fn set_last_was_cut(&mut self, req: InputRequest) {
        use InputRequest::*;
        self.last_was_cut = matches!(
            req,
            DeleteLine | DeletePrevWord | DeleteNextWord | DeleteTillEnd
        );
    }

    /// Handle request and emit response.
    pub fn handle(&mut self, req: InputRequest) -> InputResponse {
        use InputRequest::*;
        let result = match req {
            SetCursor(pos) => {
                let pos = pos.min(self.value.chars().count());
                if self.cursor == pos {
                    None
                } else {
                    self.cursor = pos;
                    Some(StateChanged {
                        value: false,
                        cursor: true,
                    })
                }
            }
            InsertChar(c) => {
                if self.cursor == self.value.chars().count() {
                    self.value.push(c);
                } else {
                    self.value = self
                        .value
                        .chars()
                        .take(self.cursor)
                        .chain(
                            std::iter::once(c)
                                .chain(self.value.chars().skip(self.cursor)),
                        )
                        .collect();
                }
                self.cursor += 1;
                Some(StateChanged {
                    value: true,
                    cursor: true,
                })
            }

            DeletePrevChar => {
                let byte = codepoint_to_byte(&self.value, self.cursor);
                let prev = prev_grapheme(&self.value, byte)?;
                let removed = self.value[prev..byte].chars().count();
                self.value.replace_range(prev..byte, "");
                self.cursor -= removed;
                Some(StateChanged {
                    value: true,
                    cursor: true,
                })
            }

            DeleteNextChar => {
                let byte = codepoint_to_byte(&self.value, self.cursor);
                let next = next_grapheme(&self.value, byte)?;
                self.value.replace_range(byte..next, "");
                Some(StateChanged {
                    value: true,
                    cursor: false,
                })
            }

            GoToPrevChar => {
                let byte = codepoint_to_byte(&self.value, self.cursor);
                let prev = prev_grapheme(&self.value, byte)?;
                self.cursor -= self.value[prev..byte].chars().count();
                Some(StateChanged {
                    value: false,
                    cursor: true,
                })
            }

            GoToPrevWord => {
                let byte = codepoint_to_byte(&self.value, self.cursor);
                let prev = prev_word_byte(&self.value, byte);
                if self.cursor == 0 {
                    None
                } else {
                    self.cursor = byte_to_codepoint(&self.value, prev);
                    Some(StateChanged {
                        value: false,
                        cursor: true,
                    })
                }
            }

            GoToNextChar => {
                let byte = codepoint_to_byte(&self.value, self.cursor);
                let next = next_grapheme(&self.value, byte)?;
                self.cursor += self.value[byte..next].chars().count();
                Some(StateChanged {
                    value: false,
                    cursor: true,
                })
            }

            GoToNextWord => {
                let byte = codepoint_to_byte(&self.value, self.cursor);
                let next = next_word_byte(&self.value, byte);
                if self.cursor == self.value.chars().count() {
                    None
                } else {
                    self.cursor = byte_to_codepoint(&self.value, next);
                    Some(StateChanged {
                        value: false,
                        cursor: true,
                    })
                }
            }

            DeleteLine => {
                if self.value.is_empty() {
                    None
                } else {
                    let side = if self.cursor == self.value.chars().count() {
                        Side::Left
                    } else {
                        Side::Right
                    };
                    self.add_to_yank(self.value.clone(), side);
                    self.value = "".into();
                    self.cursor = 0;
                    Some(StateChanged {
                        value: true,
                        cursor: true,
                    })
                }
            }

            DeletePrevWord => {
                if self.cursor == 0 {
                    None
                } else {
                    let byte = codepoint_to_byte(&self.value, self.cursor);
                    let prev = prev_word_byte(&self.value, byte);
                    let deleted = self.value[prev..byte].to_string();
                    self.add_to_yank(deleted, Side::Left);
                    self.value.replace_range(prev..byte, "");
                    self.cursor = byte_to_codepoint(&self.value, prev);
                    Some(StateChanged {
                        value: true,
                        cursor: true,
                    })
                }
            }

            DeleteNextWord => {
                let byte = codepoint_to_byte(&self.value, self.cursor);
                let next = next_word_byte(&self.value, byte);
                if self.cursor == self.value.chars().count() {
                    None
                } else {
                    let deleted = self.value[byte..next].to_string();
                    self.add_to_yank(deleted, Side::Right);
                    self.value.replace_range(byte..next, "");
                    Some(StateChanged {
                        value: true,
                        cursor: false,
                    })
                }
            }

            GoToStart => {
                if self.cursor == 0 {
                    None
                } else {
                    self.cursor = 0;
                    Some(StateChanged {
                        value: false,
                        cursor: true,
                    })
                }
            }

            GoToEnd => {
                let count = self.value.chars().count();
                if self.cursor == count {
                    None
                } else {
                    self.cursor = count;
                    Some(StateChanged {
                        value: false,
                        cursor: true,
                    })
                }
            }

            DeleteTillEnd => {
                let deleted: String = self.value.chars().skip(self.cursor).collect();
                self.add_to_yank(deleted, Side::Right);
                self.value = self.value.chars().take(self.cursor).collect();
                Some(StateChanged {
                    value: true,
                    cursor: false,
                })
            }

            Yank => {
                if self.yank.is_empty() {
                    None
                } else if self.cursor == self.value.chars().count() {
                    self.value.push_str(&self.yank);
                    self.cursor += self.yank.chars().count();
                    Some(StateChanged {
                        value: true,
                        cursor: true,
                    })
                } else {
                    self.value = self
                        .value
                        .chars()
                        .take(self.cursor)
                        .chain(self.yank.chars())
                        .chain(self.value.chars().skip(self.cursor))
                        .collect();
                    self.cursor += self.yank.chars().count();
                    Some(StateChanged {
                        value: true,
                        cursor: true,
                    })
                }
            }
        };
        self.set_last_was_cut(req);
        result
    }

    /// Get a reference to the current value.
    pub fn value(&self) -> &str {
        self.value.as_str()
    }

    /// Returns the number of **codepoints** preceding the cursor.  Movement
    /// and deletion operations step one *grapheme* at a time, so a single
    /// [`InputRequest::GoToNextChar`] or [`InputRequest::DeletePrevChar`]
    /// may change this count by more than one.
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// Returns the cursor's position in **display columns** (per
    /// `unicode-width`).
    pub fn visual_cursor(&self) -> usize {
        if self.cursor == 0 {
            return 0;
        }

        // Safe, because the end index will always be within bounds
        unicode_width::UnicodeWidthStr::width(unsafe {
            self.value.get_unchecked(
                0..self
                    .value
                    .char_indices()
                    .nth(self.cursor)
                    .map_or_else(|| self.value.len(), |(index, _)| index),
            )
        })
    }

    /// Get the scroll position with account for multispace characters.
    pub fn visual_scroll(&self, width: usize) -> usize {
        let scroll = (self.visual_cursor()).max(width) - width;
        let mut uscroll = 0;
        let mut chars = self.value().chars();

        while uscroll < scroll {
            match chars.next() {
                Some(c) => {
                    uscroll += unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
                }
                None => break,
            }
        }
        uscroll
    }
}

impl From<Input> for String {
    fn from(input: Input) -> Self {
        input.value
    }
}

impl From<String> for Input {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<&str> for Input {
    fn from(value: &str) -> Self {
        Self::new(value.into())
    }
}

impl std::fmt::Display for Input {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.value.fmt(f)
    }
}

#[cfg(test)]
mod tests;