Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

vim: Fix insert above auto-indentation (#52594)

William Whittakerc6e0868cb8f2
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index c42ed695529..3689f1903d0 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -3275,6 +3275,21 @@ impl Editor {
});
}
+ pub fn edit_before_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
+ where
+ I: IntoIterator<Item = (Range<S>, T)>,
+ S: ToOffset,
+ T: Into<Arc<str>>,
+ {
+ if self.read_only(cx) {
+ return;
+ }
+
+ self.buffer.update(cx, |buffer, cx| {
+ buffer.edit_before(edits, self.autoindent_mode.clone(), cx)
+ });
+ }
+
pub fn edit_with_block_indent<I, S, T>(
&mut self,
edits: I,
diff --git a/crates/language/src/buffer.rs b/crates/language/src/buffer.rs
index 8e2f6ee946e..9f8e12aac61 100644
--- a/crates/language/src/buffer.rs
+++ b/crates/language/src/buffer.rs
@@ -950,6 +950,16 @@ impl EditPreview {
}
}
+/// Which pre-existing line to exclude from auto-indentation when inserting
+/// text.
+#[derive(Clone, Copy, Debug)]
+pub enum AutoIndentExclusion {
+ /// Exclude the preceding line when the inserted text starts with a newline.
+ PrecedingLine,
+ /// Exclude the following line when the inserted text ends with a newline.
+ FollowingLine,
+}
+
impl Buffer {
/// Create a new buffer with the given base text.
pub fn local<T: Into<String>>(base_text: T, cx: &Context<Self>) -> Self {
@@ -2732,7 +2742,35 @@ impl Buffer {
S: ToOffset,
T: Into<Arc<str>>,
{
- self.edit_internal(edits_iter, autoindent_mode, true, cx)
+ self.edit_internal(
+ edits_iter,
+ autoindent_mode,
+ true,
+ AutoIndentExclusion::PrecedingLine,
+ cx,
+ )
+ }
+
+ /// Like [`edit`](Self::edit), but preserves the following line's
+ /// indentation when the inserted text ends with a newline.
+ pub fn edit_before<I, S, T>(
+ &mut self,
+ edits_iter: I,
+ autoindent_mode: Option<AutoindentMode>,
+ cx: &mut Context<Self>,
+ ) -> Option<clock::Lamport>
+ where
+ I: IntoIterator<Item = (Range<S>, T)>,
+ S: ToOffset,
+ T: Into<Arc<str>>,
+ {
+ self.edit_internal(
+ edits_iter,
+ autoindent_mode,
+ true,
+ AutoIndentExclusion::FollowingLine,
+ cx,
+ )
}
/// Like [`edit`](Self::edit), but does not coalesce adjacent edits.
@@ -2747,7 +2785,13 @@ impl Buffer {
S: ToOffset,
T: Into<Arc<str>>,
{
- self.edit_internal(edits_iter, autoindent_mode, false, cx)
+ self.edit_internal(
+ edits_iter,
+ autoindent_mode,
+ false,
+ AutoIndentExclusion::PrecedingLine,
+ cx,
+ )
}
fn edit_internal<I, S, T>(
@@ -2755,6 +2799,7 @@ impl Buffer {
edits_iter: I,
autoindent_mode: Option<AutoindentMode>,
coalesce_adjacent: bool,
+ autoindent_exclusion: AutoIndentExclusion,
cx: &mut Context<Self>,
) -> Option<clock::Lamport>
where
@@ -2859,11 +2904,21 @@ impl Buffer {
first_line_is_new = false;
}
- // When inserting text starting with a newline, avoid auto-indenting the
- // previous line.
- if new_text.starts_with('\n') {
- range_of_insertion_to_indent.start += 1;
- first_line_is_new = true;
+ // When the insertion introduces a line boundary, exclude
+ // the adjacent pre-existing line from auto-indentation.
+ match autoindent_exclusion {
+ AutoIndentExclusion::PrecedingLine => {
+ if new_text.starts_with('\n') {
+ range_of_insertion_to_indent.start += 1;
+ first_line_is_new = true;
+ }
+ }
+ AutoIndentExclusion::FollowingLine => {
+ if new_text.ends_with('\n') {
+ range_of_insertion_to_indent.end -= 1;
+ first_line_is_new = true;
+ }
+ }
}
let mut original_indent_column = None;
diff --git a/crates/language/src/buffer_tests.rs b/crates/language/src/buffer_tests.rs
index 4ec52fc1056..d69e19a83a0 100644
--- a/crates/language/src/buffer_tests.rs
+++ b/crates/language/src/buffer_tests.rs
@@ -2334,6 +2334,41 @@ fn test_autoindent_multi_line_insertion(cx: &mut App) {
});
}
+#[gpui::test]
+fn test_autoindent_edit_before_insertion(cx: &mut App) {
+ init_settings(cx, |_| {});
+
+ cx.new(|cx| {
+ let text = "
+ fn a() {
+ b();
+ }
+ "
+ .unindent();
+
+ // Insert a new line above a line that is over-indented. Only the newly added line should
+ // be auto-formatted. The rest of the text should remain the same as before the operation.
+ let mut buffer = Buffer::local(text, cx).with_language(rust_lang(), cx);
+ buffer.edit_before(
+ [(Point::new(1, 0)..Point::new(1, 0), " c();\n")],
+ Some(AutoindentMode::EachLine),
+ cx,
+ );
+ assert_eq!(
+ buffer.text(),
+ "
+ fn a() {
+ c();
+ b();
+ }
+ "
+ .unindent()
+ );
+
+ buffer
+ });
+}
+
#[gpui::test]
fn test_autoindent_block_mode(cx: &mut App) {
init_settings(cx, |_| {});
diff --git a/crates/multi_buffer/src/multi_buffer.rs b/crates/multi_buffer/src/multi_buffer.rs
index 9ac5396db77..0f17aa07829 100644
--- a/crates/multi_buffer/src/multi_buffer.rs
+++ b/crates/multi_buffer/src/multi_buffer.rs
@@ -20,11 +20,12 @@ use futures_lite::future::yield_now;
use gpui::{App, Context, Entity, EventEmitter};
use itertools::Itertools;
use language::{
- AutoindentMode, Buffer, BufferChunks, BufferEditSource, BufferRow, BufferSnapshot, Capability,
- CharClassifier, CharKind, CharScopeContext, Chunk, CursorShape, DiagnosticEntryRef, File,
- IndentGuideSettings, IndentSize, Language, LanguageAwareStyling, LanguageScope, OffsetRangeExt,
- OffsetUtf16, Outline, OutlineItem, Point, PointUtf16, Selection, TextDimension, TextObject,
- ToOffset as _, ToPoint as _, TransactionId, TreeSitterOptions, Unclipped,
+ AutoIndentExclusion, AutoindentMode, Buffer, BufferChunks, BufferEditSource, BufferRow,
+ BufferSnapshot, Capability, CharClassifier, CharKind, CharScopeContext, Chunk, CursorShape,
+ DiagnosticEntryRef, File, IndentGuideSettings, IndentSize, Language, LanguageAwareStyling,
+ LanguageScope, OffsetRangeExt, OffsetUtf16, Outline, OutlineItem, Point, PointUtf16, Selection,
+ TextDimension, TextObject, ToOffset as _, ToPoint as _, TransactionId, TreeSitterOptions,
+ Unclipped,
language_settings::{AllLanguageSettings, LanguageSettings},
};
@@ -1377,7 +1378,32 @@ impl MultiBuffer {
S: ToOffset,
T: Into<Arc<str>>,
{
- self.edit_internal(edits, autoindent_mode, true, cx);
+ self.edit_internal(
+ edits,
+ autoindent_mode,
+ true,
+ AutoIndentExclusion::PrecedingLine,
+ cx,
+ );
+ }
+
+ pub fn edit_before<I, S, T>(
+ &mut self,
+ edits: I,
+ autoindent_mode: Option<AutoindentMode>,
+ cx: &mut Context<Self>,
+ ) where
+ I: IntoIterator<Item = (Range<S>, T)>,
+ S: ToOffset,
+ T: Into<Arc<str>>,
+ {
+ self.edit_internal(
+ edits,
+ autoindent_mode,
+ true,
+ AutoIndentExclusion::FollowingLine,
+ cx,
+ );
}
pub fn edit_non_coalesce<I, S, T>(
@@ -1390,7 +1416,13 @@ impl MultiBuffer {
S: ToOffset,
T: Into<Arc<str>>,
{
- self.edit_internal(edits, autoindent_mode, false, cx);
+ self.edit_internal(
+ edits,
+ autoindent_mode,
+ false,
+ AutoIndentExclusion::PrecedingLine,
+ cx,
+ );
}
fn edit_internal<I, S, T>(
@@ -1398,6 +1430,7 @@ impl MultiBuffer {
edits: I,
autoindent_mode: Option<AutoindentMode>,
coalesce_adjacent: bool,
+ autoindent_exclusion: AutoIndentExclusion,
cx: &mut Context<Self>,
) where
I: IntoIterator<Item = (Range<S>, T)>,
@@ -1420,7 +1453,14 @@ impl MultiBuffer {
})
.collect::<Vec<_>>();
- return edit_internal(self, edits, autoindent_mode, coalesce_adjacent, cx);
+ return edit_internal(
+ self,
+ edits,
+ autoindent_mode,
+ coalesce_adjacent,
+ autoindent_exclusion,
+ cx,
+ );
// Non-generic part of edit, hoisted out to avoid blowing up LLVM IR.
fn edit_internal(
@@ -1428,6 +1468,7 @@ impl MultiBuffer {
edits: Vec<(Range<MultiBufferOffset>, Arc<str>)>,
mut autoindent_mode: Option<AutoindentMode>,
coalesce_adjacent: bool,
+ autoindent_exclusion: AutoIndentExclusion,
cx: &mut Context<MultiBuffer>,
) {
let original_indent_columns = match &mut autoindent_mode {
@@ -1515,8 +1556,16 @@ impl MultiBuffer {
};
if coalesce_adjacent {
- buffer.edit(deletions, deletion_autoindent_mode, cx);
- buffer.edit(insertions, insertion_autoindent_mode, cx);
+ match autoindent_exclusion {
+ AutoIndentExclusion::PrecedingLine => {
+ buffer.edit(deletions, deletion_autoindent_mode, cx);
+ buffer.edit(insertions, insertion_autoindent_mode, cx);
+ }
+ AutoIndentExclusion::FollowingLine => {
+ buffer.edit_before(deletions, deletion_autoindent_mode, cx);
+ buffer.edit_before(insertions, insertion_autoindent_mode, cx);
+ }
+ }
} else {
buffer.edit_non_coalesce(deletions, deletion_autoindent_mode, cx);
buffer.edit_non_coalesce(insertions, insertion_autoindent_mode, cx);
diff --git a/crates/vim/src/normal.rs b/crates/vim/src/normal.rs
index 389eeb88e61..7cb89a00539 100644
--- a/crates/vim/src/normal.rs
+++ b/crates/vim/src/normal.rs
@@ -753,17 +753,7 @@ impl Vim {
let indent = if auto_indent_mode == AutoIndentMode::None {
String::new()
} else {
- let indent_size = snapshot.indent_size_for_line(MultiBufferRow(row)).len;
- let first_char = snapshot.chars_at(Point::new(row, indent_size)).next();
- let indent_row = if matches!(first_char, Some('}') | Some(')')) {
- snapshot
- .prev_non_blank_row(MultiBufferRow(row))
- .map(|r| r.0)
- .unwrap_or(row)
- } else {
- row
- };
- snapshot.indent_and_comment_for_line(MultiBufferRow(indent_row), cx)
+ snapshot.indent_and_comment_for_line(MultiBufferRow(row), cx)
};
let start_of_line = Point::new(row, 0);
let edit = (start_of_line..start_of_line, indent + "\n");
@@ -778,7 +768,7 @@ impl Vim {
editor.edit(plain_edits, cx);
}
if !auto_indent_edits.is_empty() {
- editor.edit_with_autoindent(auto_indent_edits, cx);
+ editor.edit_before_with_autoindent(auto_indent_edits, cx);
}
editor.change_selections(Default::default(), window, cx, |s| {
@@ -1746,6 +1736,23 @@ mod test {
}"},
Mode::Insert,
);
+
+ // Inserting a line above should auto-indent the newly added line and leave the previous
+ // line unchanged
+ cx.assert_binding(
+ "shift-o",
+ indoc! {"
+ fn test() {
+ println!(ˇ);
+ }"},
+ Mode::Normal,
+ indoc! {"
+ fn test() {
+ ˇ
+ println!();
+ }"},
+ Mode::Insert,
+ );
}
#[gpui::test]
@@ -2223,6 +2230,11 @@ mod test {
cx.set_state(" let xˇ = 1;", Mode::Normal);
cx.simulate_keystrokes("shift-o");
cx.assert_state(" ˇ\n let x = 1;", Mode::Insert);
+
+ // O on an unindented line: the new line gets no indentation
+ cx.set_state("fn test() {\n println!(\"\");\nˇ}", Mode::Normal);
+ cx.simulate_keystrokes("shift-o");
+ cx.assert_state("fn test() {\n println!(\"\");\nˇ\n}", Mode::Insert);
}
#[gpui::test]