Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
editor: Add actions to move between comment paragraphs (#58353)
Todd L Smith57261fef89db
diff --git a/crates/editor/src/actions.rs b/crates/editor/src/actions.rsindex f0b9cfb4f5d..2bd544736a5 100644--- a/crates/editor/src/actions.rs+++ b/crates/editor/src/actions.rs@@ -669,10 +669,14 @@ actions!(MoveToEnd,/// Moves cursor to the end of the paragraph.MoveToEndOfParagraph,+ /// Moves cursor to the start of the next comment paragraph.+ MoveToNextCommentParagraph,/// Moves cursor to the end of the next subword.MoveToNextSubwordEnd,/// Moves cursor to the end of the next word.MoveToNextWordEnd,+ /// Moves cursor to the start of the previous comment paragraph.+ MoveToPreviousCommentParagraph,/// Moves cursor to the start of the previous subword.MoveToPreviousSubwordStart,/// Moves cursor to the start of the previous word.diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rsindex 9b78a9a5c0c..2a4ac54cf59 100644--- a/crates/editor/src/editor_tests.rs+++ b/crates/editor/src/editor_tests.rs@@ -2898,6 +2898,237 @@ async fn test_move_start_of_paragraph_end_of_paragraph(cx: &mut TestAppContext)cx.assert_editor_state(&"ˇone\ntwo\n \nthree\nfour\nfive\n\nsix");}+#[gpui::test]+async fn test_move_to_next_and_previous_comment_paragraph(cx: &mut TestAppContext) {+ init_test(cx, |_| {});++ let language = Arc::new(+ Language::new(+ LanguageConfig {+ line_comments: vec!["// ".into()],+ ..LanguageConfig::default()+ },+ Some(tree_sitter_rust::LANGUAGE.into()),+ )+ .with_override_query("[(line_comment)(block_comment)] @comment.inclusive")+ .unwrap(),+ );++ let mut cx = EditorTestContext::new(cx).await;+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));++ // A blank comment line (`//`) splits one comment block into two paragraphs;+ // a code line splits blocks; and a trailing comment preceded by code+ // (`let x = 1; // ...`) is not a comment line at all.+ cx.set_state(indoc! {"+ ˇ// first paragraph line one+ // first paragraph line two+ //+ // second paragraph+ fn code() {}+ // third paragraph+ let x = 1; // trailing comment, ignored+ // fourth paragraph+ "});+ cx.run_until_parked();++ let next = |cx: &mut EditorTestContext| {+ cx.update_editor(|editor, window, cx| {+ editor.move_to_next_comment_paragraph(&MoveToNextCommentParagraph, window, cx)+ });+ };+ let prev = |cx: &mut EditorTestContext| {+ cx.update_editor(|editor, window, cx| {+ editor.move_to_previous_comment_paragraph(&MoveToPreviousCommentParagraph, window, cx)+ });+ };++ // Forward: skip the second line of the first paragraph, the blank comment+ // line, the code line, and the trailing comment line.+ next(&mut cx);+ cx.assert_editor_state(indoc! {"+ // first paragraph line one+ // first paragraph line two+ //+ ˇ// second paragraph+ fn code() {}+ // third paragraph+ let x = 1; // trailing comment, ignored+ // fourth paragraph+ "});+ next(&mut cx);+ cx.assert_editor_state(indoc! {"+ // first paragraph line one+ // first paragraph line two+ //+ // second paragraph+ fn code() {}+ ˇ// third paragraph+ let x = 1; // trailing comment, ignored+ // fourth paragraph+ "});+ next(&mut cx);+ cx.assert_editor_state(indoc! {"+ // first paragraph line one+ // first paragraph line two+ //+ // second paragraph+ fn code() {}+ // third paragraph+ let x = 1; // trailing comment, ignored+ ˇ// fourth paragraph+ "});+ // No paragraph after the last one: the caret stays put.+ next(&mut cx);+ cx.assert_editor_state(indoc! {"+ // first paragraph line one+ // first paragraph line two+ //+ // second paragraph+ fn code() {}+ // third paragraph+ let x = 1; // trailing comment, ignored+ ˇ// fourth paragraph+ "});++ // Backward is the mirror image.+ prev(&mut cx);+ cx.assert_editor_state(indoc! {"+ // first paragraph line one+ // first paragraph line two+ //+ // second paragraph+ fn code() {}+ ˇ// third paragraph+ let x = 1; // trailing comment, ignored+ // fourth paragraph+ "});+ prev(&mut cx);+ cx.assert_editor_state(indoc! {"+ // first paragraph line one+ // first paragraph line two+ //+ ˇ// second paragraph+ fn code() {}+ // third paragraph+ let x = 1; // trailing comment, ignored+ // fourth paragraph+ "});+ prev(&mut cx);+ cx.assert_editor_state(indoc! {"+ ˇ// first paragraph line one+ // first paragraph line two+ //+ // second paragraph+ fn code() {}+ // third paragraph+ let x = 1; // trailing comment, ignored+ // fourth paragraph+ "});+ // No paragraph before the first one: the caret stays put.+ prev(&mut cx);+ cx.assert_editor_state(indoc! {"+ ˇ// first paragraph line one+ // first paragraph line two+ //+ // second paragraph+ fn code() {}+ // third paragraph+ let x = 1; // trailing comment, ignored+ // fourth paragraph+ "});+}++#[gpui::test]+async fn test_move_to_previous_comment_paragraph_skips_current_paragraph(cx: &mut TestAppContext) {+ init_test(cx, |_| {});++ let language = Arc::new(+ Language::new(+ LanguageConfig {+ line_comments: vec!["// ".into()],+ ..LanguageConfig::default()+ },+ Some(tree_sitter_rust::LANGUAGE.into()),+ )+ .with_override_query("[(line_comment)(block_comment)] @comment.inclusive")+ .unwrap(),+ );++ let mut cx = EditorTestContext::new(cx).await;+ cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));++ let prev = |cx: &mut EditorTestContext| {+ cx.update_editor(|editor, window, cx| {+ editor.move_to_previous_comment_paragraph(&MoveToPreviousCommentParagraph, window, cx)+ });+ };++ // Caret in the middle of the last line of the second paragraph: moving to+ // the previous paragraph must skip the entire current paragraph and land on+ // the first paragraph's start, not on the current paragraph's own start.+ cx.set_state(indoc! {"+ // alpha one+ // alpha two+ // alpha three++ // beta one+ // beta ˇtwo+ "});+ cx.run_until_parked();+ prev(&mut cx);+ cx.assert_editor_state(indoc! {"+ ˇ// alpha one+ // alpha two+ // alpha three++ // beta one+ // beta two+ "});++ // Same when the caret is part-way through the *first* line of the second+ // paragraph.+ cx.set_state(indoc! {"+ // alpha one+ // alpha two+ // alpha three++ // beˇta one+ // beta two+ "});+ cx.run_until_parked();+ prev(&mut cx);+ cx.assert_editor_state(indoc! {"+ ˇ// alpha one+ // alpha two+ // alpha three++ // beta one+ // beta two+ "});++ // Inside the first paragraph there is no previous paragraph, so the caret+ // stays put rather than jumping to the current paragraph's own start.+ cx.set_state(indoc! {"+ // alpha one+ // alpha ˇtwo+ // alpha three++ // beta one+ // beta two+ "});+ cx.run_until_parked();+ prev(&mut cx);+ cx.assert_editor_state(indoc! {"+ // alpha one+ // alpha ˇtwo+ // alpha three++ // beta one+ // beta two+ "});+}+#[gpui::test]async fn test_scroll_page_up_page_down(cx: &mut TestAppContext) {init_test(cx, |_| {});diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rsindex 4ce36632f25..fe06b33f431 100644--- a/crates/editor/src/element.rs+++ b/crates/editor/src/element.rs@@ -312,6 +312,8 @@ impl EditorElement {register_action(editor, window, Editor::move_to_end_of_line);register_action(editor, window, Editor::move_to_start_of_paragraph);register_action(editor, window, Editor::move_to_end_of_paragraph);+ register_action(editor, window, Editor::move_to_next_comment_paragraph);+ register_action(editor, window, Editor::move_to_previous_comment_paragraph);register_action(editor, window, Editor::move_to_beginning);register_action(editor, window, Editor::move_to_end);register_action(editor, window, Editor::move_to_start_of_excerpt);diff --git a/crates/editor/src/movement.rs b/crates/editor/src/movement.rsindex 5742c9d20ce..92b1a30cf22 100644--- a/crates/editor/src/movement.rs+++ b/crates/editor/src/movement.rs@@ -582,6 +582,99 @@ pub fn end_of_paragraph(map.max_point()}+/// Returns whether `row` is part of a comment paragraph: a line whose first+/// non-whitespace character lies within a comment scope and which contains at+/// least one alphanumeric character.+///+/// This intentionally excludes:+/// - blank lines and code lines,+/// - end-of-line comments preceded by code (the first non-whitespace character+/// is then code, not a comment),+/// - "blank"/divider comment lines such as a bare `//` or `// -----` (no+/// alphanumeric content), which act as paragraph separators.+fn is_comment_paragraph_line(snapshot: &MultiBufferSnapshot, row: u32) -> bool {+ let buffer_row = MultiBufferRow(row);+ if snapshot.is_line_blank(buffer_row) {+ return false;+ }+ let indent_len = snapshot.indent_size_for_line(buffer_row).len;+ let indent_end = Point::new(row, indent_len);+ let in_comment = snapshot.language_scope_at(indent_end).is_some_and(|scope| {+ matches!(+ scope.override_name(),+ Some("comment") | Some("comment.inclusive")+ )+ });+ if !in_comment {+ return false;+ }+ let line_end = Point::new(row, snapshot.line_len(buffer_row));+ snapshot+ .text_for_range(indent_end..line_end)+ .flat_map(|chunk| chunk.chars())+ .any(|c| c.is_alphanumeric())+}++/// Returns the position of the first non-whitespace character of the next or+/// previous comment paragraph, relative to `from`.+///+/// A comment paragraph is a run of consecutive comment lines (see+/// [`is_comment_paragraph_line`]); paragraphs are separated by blank lines, code+/// lines, and blank/divider comment lines. If no such paragraph exists in the+/// requested direction, `from` is returned unchanged.+///+/// Both directions always move to a *different* paragraph than the one the+/// caret is in: when the caret is inside a comment paragraph, the entire+/// current paragraph is skipped, so `Prev` lands on the previous paragraph's+/// start rather than the current paragraph's own start.+pub fn comment_paragraph(+ map: &DisplaySnapshot,+ from: DisplayPoint,+ direction: Direction,+) -> DisplayPoint {+ let snapshot = map.buffer_snapshot();+ let from_point = from.to_point(map);+ let max_row = snapshot.max_row().0;++ let is_paragraph_start = |row: u32| {+ is_comment_paragraph_line(snapshot, row)+ && (row == 0 || !is_comment_paragraph_line(snapshot, row - 1))+ };+ let paragraph_start_point =+ |row: u32| Point::new(row, snapshot.indent_size_for_line(MultiBufferRow(row)).len);++ let target = match direction {+ Direction::Next => (from_point.row..=max_row).find_map(|row| {+ let point = paragraph_start_point(row);+ (point > from_point && is_paragraph_start(row)).then_some(point)+ }),+ Direction::Prev => {+ // If the caret is within a comment paragraph, skip over the whole+ // current paragraph so we land on the *previous* paragraph rather+ // than stopping at the current paragraph's own start.+ let mut boundary_row = from_point.row;+ if is_comment_paragraph_line(snapshot, boundary_row) {+ while boundary_row > 0 && is_comment_paragraph_line(snapshot, boundary_row - 1) {+ boundary_row -= 1;+ }+ (0..boundary_row)+ .rev()+ .find_map(|row| is_paragraph_start(row).then(|| paragraph_start_point(row)))+ } else {+ (0..=from_point.row).rev().find_map(|row| {+ let point = paragraph_start_point(row);+ (point < from_point && is_paragraph_start(row)).then_some(point)+ })+ }+ }+ };++ match target {+ Some(point) => map.clip_point(point.to_display_point(map), Bias::Right),+ None => from,+ }+}+pub fn start_of_excerpt(map: &DisplaySnapshot,display_point: DisplayPoint,diff --git a/crates/editor/src/navigation.rs b/crates/editor/src/navigation.rsindex 4f9880c438b..471f68b16b8 100644--- a/crates/editor/src/navigation.rs+++ b/crates/editor/src/navigation.rs@@ -608,6 +608,68 @@ impl Editor {})}+ pub fn move_to_next_comment_paragraph(+ &mut self,+ _: &MoveToNextCommentParagraph,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ if matches!(self.mode, EditorMode::SingleLine) {+ cx.propagate();+ return;+ }+ // Keep the destination paragraph near the top of the viewport so the+ // whole paragraph below the caret stays visible after a jump.+ self.change_selections(+ SelectionEffects::scroll(Autoscroll::top_relative(5.0)),+ window,+ cx,+ |s| {+ s.move_with(&mut |map, selection| {+ selection.collapse_to(+ movement::comment_paragraph(+ map,+ selection.head(),+ workspace::searchable::Direction::Next,+ ),+ SelectionGoal::None,+ )+ });+ },+ )+ }++ pub fn move_to_previous_comment_paragraph(+ &mut self,+ _: &MoveToPreviousCommentParagraph,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ if matches!(self.mode, EditorMode::SingleLine) {+ cx.propagate();+ return;+ }+ // Keep the destination paragraph near the top of the viewport so the+ // whole paragraph below the caret stays visible after a jump.+ self.change_selections(+ SelectionEffects::scroll(Autoscroll::top_relative(5.0)),+ window,+ cx,+ |s| {+ s.move_with(&mut |map, selection| {+ selection.collapse_to(+ movement::comment_paragraph(+ map,+ selection.head(),+ workspace::searchable::Direction::Prev,+ ),+ SelectionGoal::None,+ )+ });+ },+ )+ }+pub fn select_to_start_of_paragraph(&mut self,_: &SelectToStartOfParagraph,