diff --git a/crates/behavior/src/editor.rs b/crates/behavior/src/editor.rs index b15112b51e..0dd1e190de 100644 --- a/crates/behavior/src/editor.rs +++ b/crates/behavior/src/editor.rs @@ -19,7 +19,8 @@ impl SurroundingUnit { /// the range only partly covers stays. pub fn chars_before(self, n: usize, text: &str) -> usize { match self { - SurroundingUnit::Chars => n, + // `text` is only what lies before the caret: a range wider than it covers all of it. + SurroundingUnit::Chars => n.min(text.chars().count()), SurroundingUnit::Bytes => { let from = text.len().saturating_sub(n); text.char_indices().filter(|(at, _)| *at >= from).count() @@ -31,7 +32,7 @@ impl SurroundingUnit { /// character the range only partly covers stays. pub fn chars_after(self, n: usize, text: &str) -> usize { match self { - SurroundingUnit::Chars => n, + SurroundingUnit::Chars => n.min(text.chars().count()), SurroundingUnit::Bytes => text.char_indices().take_while(|(at, c)| at + c.len_utf8() <= n).count(), } } diff --git a/crates/ui-widgets/tests/it/text/ime_delete.rs b/crates/ui-widgets/tests/it/text/ime_delete.rs index 3641445792..5b4420577a 100644 --- a/crates/ui-widgets/tests/it/text/ime_delete.rs +++ b/crates/ui-widgets/tests/it/text/ime_delete.rs @@ -49,3 +49,15 @@ fn the_input_methods_characters_after_the_caret_are_deleted() { fixture.frame(vec![Event::Ime(ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 2 })]).settle(); assert_eq!(*text.borrow(), "d", "one character before the caret and two after it"); } + +/// A range wider than the text around the caret deletes what there is, rather than underflowing its count of +/// characters before it. +#[trial] +fn a_character_range_wider_than_the_text_deletes_what_there_is() { + let (mut fixture, text) = field("ab", 0); + fixture.frame(vec![Event::Ime(ImeEvent::DeleteSurrounding { before_chars: 5, after_chars: 0 })]).settle(); + assert_eq!(*text.borrow(), "", "five characters asked of two bytes before the caret"); + let (mut fixture, text) = field("ab", 2); + fixture.frame(vec![Event::Ime(ImeEvent::DeleteSurrounding { before_chars: 0, after_chars: 5 })]).settle(); + assert_eq!(*text.borrow(), "", "and five asked after it"); +}