Fix cursor position when inserting newlines on a repeated excerpt

Co-Authored-By: Nathan Sobo <nathan@zed.dev>
Co-Authored-By: Max Brunsfeld <max@zed.dev>
This commit is contained in:
Antonio Scandurra 2022-01-11 18:30:25 +01:00
parent 58e45dd9be
commit c16820166b
2 changed files with 30 additions and 25 deletions

View file

@ -1,7 +1,7 @@
[package] [package]
name = "editor" name = "editor"
version = "0.1.0" version = "0.1.0"
edition = "2018" edition = "2021"
[lib] [lib]
path = "src/editor.rs" path = "src/editor.rs"

View file

@ -1216,7 +1216,6 @@ impl Editor {
} }
} }
let mut new_selections = Vec::with_capacity(old_selections.len());
self.buffer.update(cx, |buffer, cx| { self.buffer.update(cx, |buffer, cx| {
let mut delta = 0_isize; let mut delta = 0_isize;
let mut pending_edit: Option<PendingEdit> = None; let mut pending_edit: Option<PendingEdit> = None;
@ -1259,31 +1258,27 @@ impl Editor {
} }
buffer.edit_with_autoindent(pending.ranges, new_text, cx); buffer.edit_with_autoindent(pending.ranges, new_text, cx);
let mut delta = 0_isize; let buffer = buffer.read(cx);
new_selections.extend(old_selections.into_iter().map( self.selections = self
|(id, range, indent, insert_extra_newline)| { .selections
let start = (range.start as isize + delta) as usize; .iter()
let end = (range.end as isize + delta) as usize; .cloned()
let text_before_cursor_len = indent as usize + 1; .zip(old_selections)
let cursor = start + text_before_cursor_len; .map(|(mut new_selection, (_, _, _, insert_extra_newline))| {
let text_len = if insert_extra_newline { if insert_extra_newline {
text_before_cursor_len * 2 let mut cursor = new_selection.start.to_point(&buffer);
} else { cursor.row -= 1;
text_before_cursor_len cursor.column = buffer.line_len(cursor.row);
}; let anchor = buffer.anchor_after(cursor);
delta += text_len as isize - (end - start) as isize; new_selection.start = anchor.clone();
Selection { new_selection.end = anchor;
id,
start: cursor,
end: cursor,
reversed: false,
goal: SelectionGoal::None,
} }
}, new_selection
)) })
.collect();
}); });
self.update_selections(new_selections, Some(Autoscroll::Fit), cx); self.request_autoscroll(Autoscroll::Fit, cx);
self.end_transaction(cx); self.end_transaction(cx);
#[derive(Default)] #[derive(Default)]
@ -6186,7 +6181,17 @@ mod tests {
DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2), DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5), DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
] ]
) );
view.newline(&Newline, cx);
assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
assert_eq!(
view.selected_display_ranges(cx),
&[
DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
]
);
}); });
} }