| 1 | use std::ops::Range; |
| 2 | |
| 3 | #[derive(Clone, Copy)] |
| 4 | enum CharacterKind { |
| 5 | Word, |
| 6 | Whitespace, |
| 7 | Newline, |
| 8 | Other, |
| 9 | } |
| 10 | |
| 11 | impl From<char> for CharacterKind { |
| 12 | fn from(character: char) -> Self { |
| 13 | if character == '_' |
| 14 | || character.is_ascii_alphanumeric() |
| 15 | || matches!(character, '\u{00C0}'..='\u{024F}' | '\u{0400}'..='\u{04FF}' | '\u{1E00}'..='\u{1EFF}' | '\u{0300}'..='\u{036F}') |
| 16 | { |
| 17 | Self::Word |
| 18 | } else if matches!(character, '\n' | '\r') { |
| 19 | Self::Newline |
| 20 | } else if character.is_whitespace() { |
| 21 | Self::Whitespace |
| 22 | } else { |
| 23 | Self::Other |
| 24 | } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | pub(crate) fn word_range_from_chars( |
| 29 | offset: usize, |
| 30 | character: char, |
| 31 | previous: impl Iterator<Item = char>, |
| 32 | following: impl Iterator<Item = char>, |
| 33 | ) -> Range<usize> { |
| 34 | let kind = CharacterKind::from(character); |
| 35 | let connects = |next| { |
| 36 | matches!( |
| 37 | (kind, CharacterKind::from(next)), |
| 38 | (CharacterKind::Word, CharacterKind::Word) |
| 39 | | (CharacterKind::Whitespace, CharacterKind::Whitespace) |
| 40 | ) |
| 41 | }; |
| 42 | let start = previous |
| 43 | .take(128) |
| 44 | .take_while(|character| connects(*character)) |
| 45 | .fold(offset, |offset, character| offset - character.len_utf8()); |
| 46 | let end = following |
| 47 | .take(128) |
| 48 | .take_while(|character| connects(*character)) |
| 49 | .fold(offset + character.len_utf8(), |offset, character| { |
| 50 | offset + character.len_utf8() |
| 51 | }); |
| 52 | start..end |
| 53 | } |
| 54 | |
| 55 | pub(crate) fn word_range_at(text: &str, offset: usize) -> Option<Range<usize>> { |
| 56 | let offset = clip_offset_left(text, offset); |
| 57 | let character = text[offset..].chars().next()?; |
| 58 | let end = offset + character.len_utf8(); |
| 59 | Some(word_range_from_chars( |
| 60 | offset, |
| 61 | character, |
| 62 | text[..offset].chars().rev(), |
| 63 | text[end..].chars(), |
| 64 | )) |
| 65 | } |
| 66 | |
| 67 | pub(crate) fn line_range_at(text: &str, offset: usize) -> Range<usize> { |
| 68 | let offset = clip_offset_left(text, offset); |
| 69 | let start = text[..offset].rfind('\n').map_or(0, |newline| newline + 1); |
| 70 | let end = text[offset..] |
| 71 | .find('\n') |
| 72 | .map_or(text.len(), |newline| offset + newline); |
| 73 | start..end |
| 74 | } |
| 75 | |
| 76 | fn clip_offset_left(text: &str, offset: usize) -> usize { |
| 77 | let mut offset = offset.min(text.len()); |
| 78 | while !text.is_char_boundary(offset) { |
| 79 | offset -= 1; |
| 80 | } |
| 81 | offset |
| 82 | } |