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.

Fix multicursor indentation (#64675)

Gautam Manchandaniec609f84c1af
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 3a69748472c..a26cf4a88d7 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -5582,7 +5582,13 @@ impl Editor {
let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
let indent_delta = match (current_indent.kind, indent_kind) {
(IndentKind::Space, IndentKind::Space) => {
- let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
+ let columns_to_next_tab_stop = if delta_for_start_row > 0 {
+ delta_for_start_row
+ } else if has_multiple_rows {
+ tab_size
+ } else {
+ tab_size - (current_indent.len % tab_size)
+ };
IndentSize::spaces(columns_to_next_tab_stop)
}
(IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rs
index db8f9bb71b2..4b57c52760e 100644
--- a/crates/editor/src/editor_tests.rs
+++ b/crates/editor/src/editor_tests.rs
@@ -6856,6 +6856,146 @@ async fn test_indent_yaml_non_comments_with_multiple_cursors(cx: &mut TestAppCon
);
}
+#[gpui::test]
+async fn test_multicursor_input_preserves_yaml_indentation(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+ let yaml_language = languages::language("yaml", tree_sitter_yaml::LANGUAGE.into());
+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(yaml_language), cx));
+
+ let initial_state = indoc! {r#"
+ ˇcoverage:
+ ˇrange: 40..60
+ ˇstatus:
+ ˇpatch: off
+ ˇproject:
+ ˇdefault:
+ ˇinformational: true
+
+ ˇ# Don't leave comments on PRs
+ ˇcomment: false
+ "#};
+
+ for input in ["2", "#"] {
+ cx.set_state(initial_state);
+ cx.update_editor(|editor, window, cx| editor.handle_input(input, window, cx));
+ cx.wait_for_autoindent_applied().await;
+ cx.assert_editor_state(&initial_state.replace('ˇ', &format!("{input}ˇ")));
+
+ // Recreate the cursors and delete the inserted characters, as in #21334.
+ cx.update_editor(|editor, window, cx| editor.cancel(&Cancel, window, cx));
+ cx.set_selections_state(&initial_state.replace('ˇ', &format!("ˇ{input}")));
+ cx.update_editor(|editor, window, cx| editor.delete(&Delete, window, cx));
+ cx.wait_for_autoindent_applied().await;
+ cx.assert_editor_state(initial_state);
+ }
+
+ // A multiline replacement must not reindent the other single-line edits.
+ cx.set_state(indoc! {"
+ ˇroot:
+ ˇchild:
+ ˇleaf: 1
+ replacement:
+ « first: 1
+ second: 2ˇ»
+ "});
+ cx.update_editor(|editor, window, cx| editor.handle_input("2", window, cx));
+ cx.wait_for_autoindent_applied().await;
+ cx.assert_editor_state(indoc! {"
+ 2ˇroot:
+ 2ˇchild:
+ 2ˇleaf: 1
+ replacement:
+ 2ˇ
+ "});
+}
+
+#[gpui::test]
+async fn test_multicursor_input_autoindents_multiline_replacements(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+ let python_language = languages::language("python", tree_sitter_python::LANGUAGE.into());
+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(python_language), cx));
+
+ cx.set_state(indoc! {"
+ def f():
+ « a = 1
+ b = 2ˇ»
+ def g():
+ « a = 1
+ b = 2ˇ»
+ "});
+
+ cx.update_editor(|editor, window, cx| editor.handle_input("pass", window, cx));
+ cx.wait_for_autoindent_applied().await;
+
+ assert_eq!(
+ cx.buffer_text(),
+ indoc! {"
+ def f():
+ pass
+ def g():
+ pass
+ "}
+ );
+}
+
+#[gpui::test]
+async fn test_tab_indents_selected_yaml_block(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+ let yaml_language = languages::language("yaml", tree_sitter_yaml::LANGUAGE.into());
+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(yaml_language), cx));
+
+ cx.set_state(indoc! {"
+ «foo:
+ - bar
+ - zop
+ x:
+ q
+ bar:
+ qˇ»
+ "});
+
+ cx.update_editor(|editor, window, cx| editor.tab(&Tab, window, cx));
+
+ assert_eq!(
+ cx.buffer_text(),
+ indoc! {"
+ \x20 foo:
+ - bar
+ - zop
+ x:
+ q
+ bar:
+ q
+ "}
+ );
+}
+
+#[gpui::test]
+async fn test_tab_indents_overlapping_selections_consistently(cx: &mut TestAppContext) {
+ init_test(cx, |_| {});
+
+ let mut cx = EditorTestContext::new(cx).await;
+ cx.set_state(indoc! {"
+ \x20 «firstˇ»: «1
+ \x20 second: 2
+ \x20 third: 3ˇ»
+ "});
+
+ cx.update_editor(|editor, window, cx| editor.tab(&Tab, window, cx));
+
+ cx.assert_editor_state(indoc! {"
+ \x20 «firstˇ»: «1
+ \x20 second: 2
+ \x20 third: 3ˇ»
+ "});
+}
+
#[gpui::test]
async fn test_indent_outdent_with_hard_tabs(cx: &mut TestAppContext) {
init_test(cx, |settings| {
@@ -40439,6 +40579,34 @@ async fn test_outdent_after_input_for_python(cx: &mut TestAppContext) {
else:ˇ
"});
+ // Completing `else:` at multiple cursors must still trigger syntax outdents.
+ cx.set_state(indoc! {"
+ def f():
+ if True:
+ pass
+ elseˇ
+ pass
+ def g():
+ if True:
+ pass
+ elseˇ
+ pass
+ "});
+ cx.update_editor(|editor, window, cx| editor.handle_input(":", window, cx));
+ cx.wait_for_autoindent_applied().await;
+ cx.assert_editor_state(indoc! {"
+ def f():
+ if True:
+ pass
+ else:ˇ
+ pass
+ def g():
+ if True:
+ pass
+ else:ˇ
+ pass
+ "});
+
// test `except` auto outdents when typed inside `try` block
cx.set_state(indoc! {"
def main():
diff --git a/crates/editor/src/input.rs b/crates/editor/src/input.rs
index 9524382be94..96f631e780a 100644
--- a/crates/editor/src/input.rs
+++ b/crates/editor/src/input.rs
@@ -79,6 +79,7 @@ impl Editor {
self.unfold_buffers_with_selections(cx);
let selections = self.selections.all_adjusted(&self.display_snapshot(cx));
+ let has_multiple_selections = selections.len() > 1;
let mut bracket_inserted = false;
let mut edits = Vec::new();
let mut linked_edits = LinkedEdits::new();
@@ -416,11 +417,18 @@ impl Editor {
let initial_buffer_versions =
jsx_tag_auto_close::construct_initial_buffer_versions_map(this, &edits, cx);
+ let autoindent_mode = if has_multiple_selections {
+ this.autoindent_mode
+ .clone()
+ .map(|_| AutoindentMode::PreserveSingleLine)
+ } else {
+ this.autoindent_mode.clone()
+ };
this.buffer.update(cx, |buffer, cx| {
if has_adjacent_edits {
- buffer.edit_non_coalesce(edits, this.autoindent_mode.clone(), cx);
+ buffer.edit_non_coalesce(edits, autoindent_mode, cx);
} else {
- buffer.edit(edits, this.autoindent_mode.clone(), cx);
+ buffer.edit(edits, autoindent_mode, cx);
}
});
linked_edits.apply(cx);
diff --git a/crates/language/src/buffer.rs b/crates/language/src/buffer.rs
index 17ad2f30301..e54228e6e7e 100644
--- a/crates/language/src/buffer.rs
+++ b/crates/language/src/buffer.rs
@@ -475,6 +475,8 @@ pub trait LocalFile: File {
pub enum AutoindentMode {
/// Indent each line of inserted text.
EachLine,
+ /// Autoindent multiline edits, but only apply syntax-triggered outdents to single-line edits.
+ PreserveSingleLine,
/// Apply the same indentation adjustment to all of the lines
/// in a given insertion.
Block {
@@ -509,6 +511,7 @@ struct AutoindentRequestEntry {
old_row: Option<u32>,
indent_size: IndentSize,
original_indent_column: Option<u32>,
+ only_explicit_outdents: bool,
}
#[derive(Debug)]
@@ -516,6 +519,7 @@ struct IndentSuggestion {
basis_row: u32,
delta: Ordering,
within_error: bool,
+ explicit_outdent: bool,
}
struct BufferChunkHighlights<'a> {
@@ -2138,7 +2142,11 @@ impl Buffer {
if let Some(old_row) = entry.old_row {
old_to_new_rows.insert(old_row, new_row);
}
- row_ranges.push((new_row..new_end_row, entry.original_indent_column));
+ row_ranges.push((
+ new_row..new_end_row,
+ entry.original_indent_column,
+ entry.only_explicit_outdents,
+ ));
}
// Build a map containing the suggested indentation for each of the edited lines
@@ -2190,7 +2198,7 @@ impl Buffer {
// if they differ from the old suggestion for that line.
let mut language_indent_sizes = language_indent_sizes_by_new_row.iter().peekable();
let mut language_indent_size = IndentSize::default();
- for (row_range, original_indent_column) in row_ranges {
+ for (row_range, original_indent_column, only_explicit_outdents) in row_ranges {
let new_edited_row_range = if request.is_block_mode {
row_range.start..row_range.start + 1
} else {
@@ -2226,7 +2234,8 @@ impl Buffer {
suggested_indent != *old_indentation
&& (!suggestion.within_error || *was_within_error)
},
- ) {
+ ) && (!only_explicit_outdents || suggestion.explicit_outdent)
+ {
indent_sizes.insert(
new_row,
(suggested_indent, request.ignore_empty_lines),
@@ -3043,6 +3052,9 @@ impl Buffer {
}
AutoindentRequestEntry {
+ only_explicit_outdents: matches!(mode, AutoindentMode::PreserveSingleLine)
+ && old_start.row == old_end.row
+ && !new_text.contains('\n'),
original_indent_column,
old_row: if first_line_is_new {
None
@@ -3115,6 +3127,7 @@ impl Buffer {
old_row: None,
indent_size: before_edit.language_indent_size_at(range.start, cx),
original_indent_column: None,
+ only_explicit_outdents: false,
})
.collect();
self.autoindent_requests.push(Arc::new(AutoindentRequest {
@@ -4053,24 +4066,28 @@ impl BufferSnapshot {
basis_row: prev_row,
delta: Ordering::Equal,
within_error: within_error && !from_regex,
+ explicit_outdent: true,
})
} else if indent_from_prev_row {
Some(IndentSuggestion {
basis_row: prev_row,
delta: Ordering::Greater,
within_error: within_error && !from_regex,
+ explicit_outdent: false,
})
} else if outdent_to_row < prev_row {
Some(IndentSuggestion {
basis_row: outdent_to_row,
delta: Ordering::Equal,
within_error: within_error && !from_regex,
+ explicit_outdent: true,
})
} else if outdent_from_prev_row {
Some(IndentSuggestion {
basis_row: prev_row,
delta: Ordering::Less,
within_error: within_error && !from_regex,
+ explicit_outdent: true,
})
} else if config.auto_indent_using_last_non_empty_line || !self.is_line_blank(prev_row)
{
@@ -4078,6 +4095,7 @@ impl BufferSnapshot {
basis_row: prev_row,
delta: Ordering::Equal,
within_error: within_error && !from_regex,
+ explicit_outdent: false,
})
} else {
None