Fix panic when using join_selections_space (#9783)

Joining lines with Alt-J does not properly select the inserted spaces
when the selection contains blank lines. In the worst case it panics
with an out of bounds index.

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:
Char index out of bounds: char index 11, Rope/RopeSlice char length 10'

Steps to reproduce:
* Create a new document
    ```
    a

    b

    c

    d

    e
    ```
* % (Select all)
* Alt-J (join and select the spaces)
pull/9789/head
Mike Trinkala 8 months ago committed by GitHub
parent d769fadde0
commit 5bd007266a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -4372,16 +4372,27 @@ fn join_selections_impl(cx: &mut Context, select_space: bool) {
// select inserted spaces // select inserted spaces
let transaction = if select_space { let transaction = if select_space {
let mut offset: usize = 0;
let ranges: SmallVec<_> = changes let ranges: SmallVec<_> = changes
.iter() .iter()
.scan(0, |offset, change| { .filter_map(|change| {
let range = Range::point(change.0 - *offset); if change.2.is_some() {
*offset += change.1 - change.0 - 1; // -1 because cursor is 0-sized let range = Range::point(change.0 - offset);
Some(range) offset += change.1 - change.0 - 1; // -1 adjusts for the replacement of the range by a space
Some(range)
} else {
offset += change.1 - change.0;
None
}
}) })
.collect(); .collect();
let selection = Selection::new(ranges, 0); let t = Transaction::change(text, changes.into_iter());
Transaction::change(text, changes.into_iter()).with_selection(selection) if ranges.is_empty() {
t
} else {
let selection = Selection::new(ranges, 0);
t.with_selection(selection)
}
} else { } else {
Transaction::change(text, changes.into_iter()) Transaction::change(text, changes.into_iter())
}; };

@ -526,3 +526,86 @@ async fn test_join_selections() -> anyhow::Result<()> {
Ok(()) Ok(())
} }
#[tokio::test(flavor = "multi_thread")]
async fn test_join_selections_space() -> anyhow::Result<()> {
// join with empty lines panic
test((
platform_line(indoc! {"\
#[a
b
c
d
e|]#
"}),
"<A-J>",
platform_line(indoc! {"\
a#[ |]#b#( |)#c#( |)#d#( |)#e
"}),
))
.await?;
// normal join
test((
platform_line(indoc! {"\
#[a|]#bc
def
"}),
"<A-J>",
platform_line(indoc! {"\
abc#[ |]#def
"}),
))
.await?;
// join with empty line
test((
platform_line(indoc! {"\
#[a|]#bc
def
"}),
"<A-J>",
platform_line(indoc! {"\
#[a|]#bc
def
"}),
))
.await?;
// join with additional space in non-empty line
test((
platform_line(indoc! {"\
#[a|]#bc
def
"}),
"<A-J><A-J>",
platform_line(indoc! {"\
abc#[ |]#def
"}),
))
.await?;
// join with retained trailing spaces
test((
platform_line(indoc! {"\
#[aaa
bb
c |]#
"}),
"<A-J>",
platform_line(indoc! {"\
aaa #[ |]#bb #( |)#c
"}),
))
.await?;
Ok(())
}

Loading…
Cancel
Save