diff --git a/crates/language/src/buffer.rs b/crates/language/src/buffer.rs index bf2b414976..5e3cb56a49 100644 --- a/crates/language/src/buffer.rs +++ b/crates/language/src/buffer.rs @@ -2210,7 +2210,12 @@ impl Buffer { original_indent_columns, } = &mode { - original_indent_column = Some( + original_indent_column = Some(if new_text.starts_with('\n') { + indent_size_for_text( + new_text[range_of_insertion_to_indent.clone()].chars(), + ) + .len + } else { original_indent_columns .get(ix) .copied() @@ -2220,8 +2225,8 @@ impl Buffer { new_text[range_of_insertion_to_indent.clone()].chars(), ) .len - }), - ); + }) + }); // Avoid auto-indenting the line after the edit. if new_text[range_of_insertion_to_indent.clone()].ends_with('\n') { diff --git a/crates/language/src/buffer_tests.rs b/crates/language/src/buffer_tests.rs index 76316b2640..dbe54b5c6d 100644 --- a/crates/language/src/buffer_tests.rs +++ b/crates/language/src/buffer_tests.rs @@ -1712,6 +1712,56 @@ fn test_autoindent_block_mode(cx: &mut App) { }); } +#[gpui::test] +fn test_autoindent_block_mode_with_newline(cx: &mut App) { + init_settings(cx, |_| {}); + + cx.new(|cx| { + let text = r#" + fn a() { + b(); + } + "# + .unindent(); + let mut buffer = Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx); + + // First line contains just '\n', it's indentation is stored in "original_indent_columns" + let original_indent_columns = vec![Some(4)]; + let inserted_text = r#" + + c(); + d(); + e(); + "# + .unindent(); + buffer.edit( + [(Point::new(2, 0)..Point::new(2, 0), inserted_text.clone())], + Some(AutoindentMode::Block { + original_indent_columns: original_indent_columns.clone(), + }), + cx, + ); + + // While making edit, we ignore first line as it only contains '\n' + // hence second line indent is used to calculate delta + assert_eq!( + buffer.text(), + r#" + fn a() { + b(); + + c(); + d(); + e(); + } + "# + .unindent() + ); + + buffer + }); +} + #[gpui::test] fn test_autoindent_block_mode_without_original_indent_columns(cx: &mut App) { init_settings(cx, |_| {});