From 1c820ea3c6d134b1862fff0b642c1754d80ea071 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Fri, 9 Jun 2023 20:02:51 +0200 Subject: [PATCH] Z-2303 editor: fix comment extension on the start of line (#2595) Release Notes: - Improved comment extension for cases where cursor was placed before start of comment marker --- crates/editor/src/editor.rs | 18 +++++++++++++++--- crates/editor/src/editor_tests.rs | 9 +++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs index 708a22c5c649a51b57b7ea8a5cd17d016fad4ded..cecefc7061eeb22791497db76af0ccad7af6cded 100644 --- a/crates/editor/src/editor.rs +++ b/crates/editor/src/editor.rs @@ -2219,11 +2219,23 @@ impl Editor { buffer .buffer_line_for_row(start_point.row) .is_some_and(|(snapshot, range)| { - snapshot + let mut index_of_first_non_whitespace = 0; + let line_starts_with_comment = snapshot .chars_for_range(range) - .skip_while(|c| c.is_whitespace()) + .skip_while(|c| { + let should_skip = c.is_whitespace(); + if should_skip { + index_of_first_non_whitespace += 1; + } + should_skip + }) .take(delimiter.len()) - .eq(delimiter.chars()) + .eq(delimiter.chars()); + let cursor_is_placed_after_comment_marker = + index_of_first_non_whitespace + delimiter.len() + <= start_point.column as usize; + line_starts_with_comment + && cursor_is_placed_after_comment_marker }) .then(|| delimiter.clone()) } else { diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rs index a94f01a386e2738b8a18b5c70b18490bb11e78d0..5cf79f9163ee3b787ba7685fb909ed63e34f550c 100644 --- a/crates/editor/src/editor_tests.rs +++ b/crates/editor/src/editor_tests.rs @@ -1744,6 +1744,15 @@ async fn test_newline_comments(cx: &mut gpui::TestAppContext) { // Foo //ˇ "}); + // Ensure that if cursor is before the comment start, we do not actually insert a comment prefix. + cx.set_state(indoc! {" + ˇ// Foo + "}); + cx.update_editor(|e, cx| e.newline(&Newline, cx)); + cx.assert_editor_state(indoc! {" + + ˇ// Foo + "}); } #[gpui::test]