Consider word bounds in TextInput cursor jumps

This commit is contained in:
Héctor Ramón Jiménez 2019-12-06 05:37:28 +01:00
parent a56eef0fec
commit 69590bcf72

View file

@ -468,46 +468,49 @@ impl Value {
} }
/// Returns the position of the previous start of a word from the given /// Returns the position of the previous start of a word from the given
/// grapheme `index`.
///
/// [`Value`]: struct.Value.html
pub fn previous_start_of_word(&self, index: usize) -> usize {
let previous_string =
&self.graphemes[..index.min(self.graphemes.len())].concat();
UnicodeSegmentation::split_word_bound_indices(&previous_string as &str)
.filter(|(_, word)| !word.trim_start().is_empty())
.next_back()
.map(|(i, previous_word)| {
index
- UnicodeSegmentation::graphemes(previous_word, true)
.count()
- UnicodeSegmentation::graphemes(
&previous_string[i + previous_word.len()..] as &str,
true,
)
.count()
})
.unwrap_or(0)
}
/// Returns the position of the next end of a word from the given grapheme
/// `index`. /// `index`.
/// ///
/// [`Value`]: struct.Value.html /// [`Value`]: struct.Value.html
pub fn previous_start_of_word(&self, mut index: usize) -> usize { pub fn next_end_of_word(&self, index: usize) -> usize {
let mut skip_space = true; let next_string = &self.graphemes[index..].concat();
while index > 0 { UnicodeSegmentation::split_word_bound_indices(&next_string as &str)
if skip_space { .filter(|(_, word)| !word.trim_start().is_empty())
skip_space = self.graphemes[index - 1] == " "; .next()
} else { .map(|(i, next_word)| {
if self.graphemes[index - 1] == " " { index
break; + UnicodeSegmentation::graphemes(next_word, true).count()
} + UnicodeSegmentation::graphemes(
} &next_string[..i] as &str,
true,
index -= 1; )
} .count()
})
index .unwrap_or(self.len())
}
/// Returns the position of the next end of a word from the given `index`.
///
/// [`Value`]: struct.Value.html
pub fn next_end_of_word(&self, mut index: usize) -> usize {
let mut skip_space = true;
while index < self.graphemes.len() {
if skip_space {
skip_space = self.graphemes[index] == " ";
} else {
if self.graphemes[index] == " " {
break;
}
}
index += 1;
}
index
} }
/// Returns a new [`Value`] containing the graphemes until the given `index`. /// Returns a new [`Value`] containing the graphemes until the given `index`.
@ -532,12 +535,10 @@ impl Value {
pub fn insert(&mut self, index: usize, c: char) { pub fn insert(&mut self, index: usize, c: char) {
self.graphemes.insert(index, c.to_string()); self.graphemes.insert(index, c.to_string());
self.graphemes = UnicodeSegmentation::graphemes( self.graphemes =
self.graphemes.concat().as_ref() as &str, UnicodeSegmentation::graphemes(&self.to_string() as &str, true)
true, .map(String::from)
) .collect();
.map(String::from)
.collect();
} }
/// Removes the grapheme at the given `index`. /// Removes the grapheme at the given `index`.