|
| 1 | +// Custom implementation of word navigation functions from tui-textarea v0.5.2+ |
| 2 | + |
| 3 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 4 | +enum CharKind { |
| 5 | + Space, |
| 6 | + Punctuation, |
| 7 | + Other, |
| 8 | +} |
| 9 | + |
| 10 | +impl CharKind { |
| 11 | + fn new(c: char) -> Self { |
| 12 | + if c.is_whitespace() { |
| 13 | + Self::Space |
| 14 | + } else if c.is_ascii_punctuation() { |
| 15 | + Self::Punctuation |
| 16 | + } else { |
| 17 | + Self::Other |
| 18 | + } |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +/// Find the end of the next word |
| 23 | +/// This is a custom implementation of the `find_word_end_next` function from tui-textarea v0.5.2+ |
| 24 | +pub fn find_word_end_next(line: &str, start_col: usize) -> Option<usize> { |
| 25 | + let mut it = line.chars().enumerate().skip(start_col); |
| 26 | + let (mut cur_col, cur_char) = it.next()?; |
| 27 | + let mut cur = CharKind::new(cur_char); |
| 28 | + |
| 29 | + for (next_col, c) in it { |
| 30 | + let next = CharKind::new(c); |
| 31 | + // if cursor started at the end of a word, don't stop |
| 32 | + if next_col.saturating_sub(start_col) > 1 && cur != CharKind::Space && next != cur { |
| 33 | + return Some(next_col.saturating_sub(1)); |
| 34 | + } |
| 35 | + cur = next; |
| 36 | + cur_col = next_col; |
| 37 | + } |
| 38 | + |
| 39 | + // if end of line is whitespace, don't stop the cursor |
| 40 | + if cur != CharKind::Space && cur_col.saturating_sub(start_col) >= 1 { |
| 41 | + return Some(cur_col); |
| 42 | + } |
| 43 | + |
| 44 | + None |
| 45 | +} |
| 46 | + |
| 47 | +/// Move cursor to the end of the next word |
| 48 | +pub fn move_cursor_to_word_end(text: &[String], row: usize, col: usize) -> (usize, usize) { |
| 49 | + if row >= text.len() { |
| 50 | + return (row, col); |
| 51 | + } |
| 52 | + |
| 53 | + let line = &text[row]; |
| 54 | + |
| 55 | + if let Some(new_col) = find_word_end_next(line, col) { |
| 56 | + return (row, new_col); |
| 57 | + } else if row + 1 < text.len() { |
| 58 | + // Try to find word end in the next line |
| 59 | + if let Some(new_col) = find_word_end_next(&text[row + 1], 0) { |
| 60 | + return (row + 1, new_col); |
| 61 | + } else if !text[row + 1].is_empty() { |
| 62 | + // If no word end found but line is not empty, go to the end of the line |
| 63 | + return (row + 1, text[row + 1].chars().count().saturating_sub(1)); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + // Can't find a word end, stay at the current position |
| 68 | + (row, col) |
| 69 | +} |
0 commit comments