@@ -3776,26 +3776,30 @@ fn normal_mode(cx: &mut Context) {
37763776}
37773777
37783778fn try_restore_indent(doc: &mut Document, view_id: ViewId) {
3779− let doc_changes = doc.changes().changes();
3780− let text = doc.text().slice(..);
3781− let pos = doc.selection(view_id).primary().cursor(text);
3782− let mut can_restore_indent = false;
3783−
3784− // Removes trailing whitespace if insert mode is exited after starting a blank new line.
37853779 use helix_core::chars::char_is_whitespace;
37863780 use helix_core::Operation;
3787− if let [Operation::Retain(move_pos), Operation::Insert(ref inserted_str), Operation::Retain(_)] =
3788− doc_changes
3789− {
3790− if move_pos + inserted_str.len32() as usize == pos
3791− && inserted_str.starts_with('\n')
3792− && inserted_str.chars().skip(1).all(char_is_whitespace)
3781+
3782+ fn inserted_a_new_blank_line(changes: &[Operation], pos: usize, line_end_pos: usize) -> bool {
3783+ if let [Operation::Retain(move_pos), Operation::Insert(ref inserted_str), Operation::Retain(_)] =
3784+ changes
37933785 {
3794− can_restore_indent = true;
3786+ move_pos + inserted_str.len32() as usize == pos
3787+ && inserted_str.starts_with('\n')
3788+ && inserted_str.chars().skip(1).all(char_is_whitespace)
3789+ && pos == line_end_pos // ensure no characters exists after current position
3790+ } else {
3791+ false
37953792 }
37963793 }
37973794
3798− if can_restore_indent {
3795+ let doc_changes = doc.changes().changes();
3796+ let text = doc.text().slice(..);
3797+ let range = doc.selection(view_id).primary();
3798+ let pos = range.cursor(text);
3799+ let line_end_pos = line_end_char_index(&text, range.cursor_line(text));
3800+
3801+ if inserted_a_new_blank_line(doc_changes, pos, line_end_pos) {
3802+ // Removes tailing whitespaces.
37993803 let transaction =
38003804 Transaction::change_by_selection(doc.text(), doc.selection(view_id), |range| {
38013805 let line_start_pos = text.line_to_char(range.cursor_line(text));