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.

helix: Add `m i m`/`m a m` and preserve the selection after those actions (#59201)

Mikhail Pertsev756c2b737cda
diff --git a/assets/keymaps/vim.json b/assets/keymaps/vim.json
index 6948cce3133..f5ce59ce274 100644
--- a/assets/keymaps/vim.json
+++ b/assets/keymaps/vim.json
@@ -695,6 +695,18 @@
"e": "vim::EntireFile",
},
},
+ {
+ // Helix textobject keys that differ from vim's: `mim`/`mam` select the
+ // closest surrounding pair, and `t`/`c`/`x` follow Helix's meanings
+ // (type, comment, xml element) instead of vim's (tag, class, unbound).
+ "context": "(vim_operator == a || vim_operator == i || vim_operator == helix_next || vim_operator == helix_previous) && helix_mode",
+ "bindings": {
+ "m": "vim::AnyPair",
+ "t": "vim::Class",
+ "c": "vim::Comment",
+ "x": "vim::Tag",
+ },
+ },
{
"context": "vim_operator == helix_m",
"bindings": {
diff --git a/crates/language/src/buffer.rs b/crates/language/src/buffer.rs
index c974ecde15d..2ff465f6ed3 100644
--- a/crates/language/src/buffer.rs
+++ b/crates/language/src/buffer.rs
@@ -5899,7 +5899,7 @@ pub(crate) fn contiguous_ranges(
})
}
-#[derive(Default, Debug)]
+#[derive(Clone, Default, Debug)]
pub struct CharClassifier {
scope: Option<LanguageScope>,
scope_context: Option<CharScopeContext>,
diff --git a/crates/vim/src/helix/boundary.rs b/crates/vim/src/helix/boundary.rs
index d93ca693b53..7396574e0f2 100644
--- a/crates/vim/src/helix/boundary.rs
+++ b/crates/vim/src/helix/boundary.rs
@@ -9,6 +9,7 @@ use language::{CharClassifier, CharKind};
use text::Bias;
use crate::helix::object::HelixTextObject;
+use crate::object::innermost_surrounding_pair_for_text_object;
/// Text objects (after helix definition) that can easily be
/// found by reading a buffer and comparing two neighboring chars
@@ -288,6 +289,59 @@ pub enum ImmediateBoundary {
VerticalBars,
}
+const PAIR_BOUNDARIES: [ImmediateBoundary; 8] = [
+ ImmediateBoundary::Parentheses,
+ ImmediateBoundary::SquareBrackets,
+ ImmediateBoundary::CurlyBrackets,
+ ImmediateBoundary::AngleBrackets,
+ ImmediateBoundary::DoubleQuotes,
+ ImmediateBoundary::SingleQuotes,
+ ImmediateBoundary::BackQuotes,
+ ImmediateBoundary::VerticalBars,
+];
+
+/// The closest surrounding pair of any type, like Helix's `m` text object.
+/// The current pair is matched via the language's bracket queries; only
+/// `next_range`/`previous_range` scan the text, since "the next pair" is not
+/// an enclosing-brackets question.
+pub struct NearestPair;
+
+impl HelixTextObject for NearestPair {
+ fn range(
+ &self,
+ map: &DisplaySnapshot,
+ relative_to: Range<DisplayPoint>,
+ around: bool,
+ ) -> Option<Range<DisplayPoint>> {
+ let pair = innermost_surrounding_pair_for_text_object(map, relative_to, around)?;
+ Some(pair.to_display_range(map, around))
+ }
+
+ fn next_range(
+ &self,
+ map: &DisplaySnapshot,
+ relative_to: Range<DisplayPoint>,
+ around: bool,
+ ) -> Option<Range<DisplayPoint>> {
+ PAIR_BOUNDARIES
+ .iter()
+ .filter_map(|pair| pair.next_range(map, relative_to.clone(), around))
+ .min_by_key(|range| range.start.to_offset(map, Bias::Left))
+ }
+
+ fn previous_range(
+ &self,
+ map: &DisplaySnapshot,
+ relative_to: Range<DisplayPoint>,
+ around: bool,
+ ) -> Option<Range<DisplayPoint>> {
+ PAIR_BOUNDARIES
+ .iter()
+ .filter_map(|pair| pair.previous_range(map, relative_to.clone(), around))
+ .max_by_key(|range| range.end.to_offset(map, Bias::Right))
+ }
+}
+
/// A textobject whose start and end can be found from an easy-to-find
/// boundary between two chars by following a simple path from there
pub enum FuzzyBoundary {
@@ -296,15 +350,15 @@ pub enum FuzzyBoundary {
}
impl ImmediateBoundary {
- fn is_inner_start(&self, left: char, right: char, classifier: CharClassifier) -> bool {
+ fn is_inner_start(&self, left: char, right: char, classifier: &CharClassifier) -> bool {
match self {
Self::Word { ignore_punctuation } => {
- let classifier = classifier.ignore_punctuation(*ignore_punctuation);
+ let classifier = classifier.clone().ignore_punctuation(*ignore_punctuation);
is_word_start(left, right, &classifier)
|| (is_buffer_start(left) && classifier.kind(right) != CharKind::Whitespace)
}
Self::Subword { ignore_punctuation } => {
- let classifier = classifier.ignore_punctuation(*ignore_punctuation);
+ let classifier = classifier.clone().ignore_punctuation(*ignore_punctuation);
movement::is_subword_start(left, right, &classifier)
|| (is_buffer_start(left) && classifier.kind(right) != CharKind::Whitespace)
}
@@ -318,15 +372,15 @@ impl ImmediateBoundary {
Self::VerticalBars => left == '|',
}
}
- fn is_inner_end(&self, left: char, right: char, classifier: CharClassifier) -> bool {
+ fn is_inner_end(&self, left: char, right: char, classifier: &CharClassifier) -> bool {
match self {
Self::Word { ignore_punctuation } => {
- let classifier = classifier.ignore_punctuation(*ignore_punctuation);
+ let classifier = classifier.clone().ignore_punctuation(*ignore_punctuation);
is_word_end(left, right, &classifier)
|| (is_buffer_end(right) && classifier.kind(left) != CharKind::Whitespace)
}
Self::Subword { ignore_punctuation } => {
- let classifier = classifier.ignore_punctuation(*ignore_punctuation);
+ let classifier = classifier.clone().ignore_punctuation(*ignore_punctuation);
movement::is_subword_start(left, right, &classifier)
|| (is_buffer_end(right) && classifier.kind(left) != CharKind::Whitespace)
}
@@ -340,7 +394,7 @@ impl ImmediateBoundary {
Self::VerticalBars => right == '|',
}
}
- fn is_outer_start(&self, left: char, right: char, classifier: CharClassifier) -> bool {
+ fn is_outer_start(&self, left: char, right: char, classifier: &CharClassifier) -> bool {
match self {
word @ Self::Word { .. } => word.is_inner_end(left, right, classifier) || left == '\n',
subword @ Self::Subword { .. } => {
@@ -356,7 +410,7 @@ impl ImmediateBoundary {
Self::VerticalBars => right == '|',
}
}
- fn is_outer_end(&self, left: char, right: char, classifier: CharClassifier) -> bool {
+ fn is_outer_end(&self, left: char, right: char, classifier: &CharClassifier) -> bool {
match self {
word @ Self::Word { .. } => {
word.is_inner_start(left, right, classifier) || right == '\n'
@@ -378,42 +432,44 @@ impl ImmediateBoundary {
impl BoundedObject for ImmediateBoundary {
fn next_start(&self, map: &DisplaySnapshot, from: Offset, outer: bool) -> Option<Offset> {
+ // Resolving the language scope walks the syntax tree, so doing it
+ // per scanned character makes long scans visibly slow.
+ let classifier = map.buffer_snapshot().char_classifier_at(from.0);
try_find_boundary(map, from, &|left, right| {
- let classifier = map.buffer_snapshot().char_classifier_at(from.0);
if outer {
- self.is_outer_start(left, right, classifier)
+ self.is_outer_start(left, right, &classifier)
} else {
- self.is_inner_start(left, right, classifier)
+ self.is_inner_start(left, right, &classifier)
}
})
}
fn next_end(&self, map: &DisplaySnapshot, from: Offset, outer: bool) -> Option<Offset> {
+ let classifier = map.buffer_snapshot().char_classifier_at(from.0);
try_find_boundary(map, from, &|left, right| {
- let classifier = map.buffer_snapshot().char_classifier_at(from.0);
if outer {
- self.is_outer_end(left, right, classifier)
+ self.is_outer_end(left, right, &classifier)
} else {
- self.is_inner_end(left, right, classifier)
+ self.is_inner_end(left, right, &classifier)
}
})
}
fn previous_start(&self, map: &DisplaySnapshot, from: Offset, outer: bool) -> Option<Offset> {
+ let classifier = map.buffer_snapshot().char_classifier_at(from.0);
try_find_preceding_boundary(map, from, &|left, right| {
- let classifier = map.buffer_snapshot().char_classifier_at(from.0);
if outer {
- self.is_outer_start(left, right, classifier)
+ self.is_outer_start(left, right, &classifier)
} else {
- self.is_inner_start(left, right, classifier)
+ self.is_inner_start(left, right, &classifier)
}
})
}
fn previous_end(&self, map: &DisplaySnapshot, from: Offset, outer: bool) -> Option<Offset> {
+ let classifier = map.buffer_snapshot().char_classifier_at(from.0);
try_find_preceding_boundary(map, from, &|left, right| {
- let classifier = map.buffer_snapshot().char_classifier_at(from.0);
if outer {
- self.is_outer_end(left, right, classifier)
+ self.is_outer_end(left, right, &classifier)
} else {
- self.is_inner_end(left, right, classifier)
+ self.is_inner_end(left, right, &classifier)
}
})
}
@@ -562,8 +618,8 @@ impl FuzzyBoundary {
backward: bool,
boundary_kind: Boundary,
) -> Option<Offset> {
+ let classifier = map.buffer_snapshot().char_classifier_at(from.0);
let generate_boundary_data = |left, right, point: Offset| {
- let classifier = map.buffer_snapshot().char_classifier_at(from.0);
let reach_boundary = if outer && boundary_kind == Boundary::Start {
self.is_near_potential_outer_start(left, right, &classifier)
} else if !outer && boundary_kind == Boundary::Start {
diff --git a/crates/vim/src/helix/object.rs b/crates/vim/src/helix/object.rs
index 798cd7162eb..263e8cc2c12 100644
--- a/crates/vim/src/helix/object.rs
+++ b/crates/vim/src/helix/object.rs
@@ -8,7 +8,7 @@ use editor::{DisplayPoint, display_map::DisplaySnapshot, movement};
use text::Selection;
use crate::{
- helix::boundary::{FuzzyBoundary, ImmediateBoundary},
+ helix::boundary::{FuzzyBoundary, ImmediateBoundary, NearestPair},
object::Object as VimObject,
};
@@ -45,9 +45,13 @@ impl VimObject {
selection: Selection<DisplayPoint>,
around: bool,
) -> Result<Option<Range<DisplayPoint>>, VimToHelixError> {
- let cursor = cursor_range(&selection, map);
+ let relative_to = if self == VimObject::AnyPair && !selection.is_empty() {
+ selection.range()
+ } else {
+ cursor_range(&selection, map)
+ };
if let Some(helix_object) = self.to_helix_object() {
- Ok(helix_object.range(map, cursor, around))
+ Ok(helix_object.range(map, relative_to, around))
} else {
Err(VimToHelixError)
}
@@ -100,6 +104,7 @@ impl VimObject {
fn to_helix_object(self) -> Option<Box<dyn HelixTextObject>> {
Some(match self {
Self::AngleBrackets => Box::new(ImmediateBoundary::AngleBrackets),
+ Self::AnyPair => Box::new(NearestPair),
Self::BackQuotes => Box::new(ImmediateBoundary::BackQuotes),
Self::CurlyBrackets => Box::new(ImmediateBoundary::CurlyBrackets),
Self::DoubleQuotes => Box::new(ImmediateBoundary::DoubleQuotes),
@@ -179,4 +184,152 @@ mod test {
Mode::HelixNormal,
);
}
+
+ #[gpui::test]
+ async fn test_select_any_pair_object(cx: &mut gpui::TestAppContext) {
+ let mut cx = VimTestContext::new(cx, true).await;
+
+ // The innermost surrounding pair wins, regardless of its kind.
+ cx.set_state("(foo \"bar bˇaz\")", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state("(foo \"«bar bazˇ»\")", Mode::HelixNormal);
+
+ cx.set_state("(foo \"bar bˇaz\")", Mode::HelixNormal);
+ cx.simulate_keystrokes("m a m");
+ cx.assert_state("(foo «\"bar baz\"ˇ»)", Mode::HelixNormal);
+
+ cx.set_state("[foo (bˇar) baz]", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state("[foo («barˇ») baz]", Mode::HelixNormal);
+
+ cx.set_state("fn foo() { let x = ˇ1; }", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state("fn foo() {« let x = 1; ˇ»}", Mode::HelixNormal);
+ cx.simulate_keystrokes("m a m");
+ cx.assert_state("fn foo() «{ let x = 1; }ˇ»", Mode::HelixNormal);
+
+ // Between nested pairs the outer pair is the closest one.
+ cx.set_state("{foo (bar) ˇbaz}", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state("{«foo (bar) bazˇ»}", Mode::HelixNormal);
+
+ // Without a surrounding pair the selection is unchanged.
+ cx.set_state("foo bˇar baz", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state("foo bˇar baz", Mode::HelixNormal);
+
+ // Pairs come from the language's bracket queries: parentheses inside
+ // a string literal are plain text, so the quotes are the closest pair.
+ cx.set_state("let s = (\"a (bˇc) d\");", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state("let s = (\"«a (bc) dˇ»\");", Mode::HelixNormal);
+
+ // A lifetime apostrophe is not a quote.
+ cx.set_state("fn f<'a>(x: ˇ&'a str) {}", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state("fn f<'a>(«x: &'a strˇ») {}", Mode::HelixNormal);
+
+ // `|` pairs where it delimits closure parameters, but not where it is
+ // a binary operator.
+ cx.set_state("let f = |aˇ, b| a;", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state("let f = |«a, bˇ»| a;", Mode::HelixNormal);
+
+ cx.set_state("let x = a | bˇ | c;", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state("let x = a | bˇ | c;", Mode::HelixNormal);
+
+ // Composes with surround add.
+ cx.set_state("let a: Vec<iˇ32> = vec![];", Mode::HelixNormal);
+ cx.simulate_keystrokes("m a m m s (");
+ cx.assert_state("let a: Vec«(<i32>)ˇ» = vec![];", Mode::HelixNormal);
+
+ // Repeated `m` objects expand from the current selection, not the
+ // cursor position within that selection.
+ cx.set_state(
+ "#[cfg_attr(feature = \"arbitˇrary\", derive(arbitrary::Arbitrary))]",
+ Mode::HelixNormal,
+ );
+ cx.simulate_keystrokes("m a m");
+ cx.assert_state(
+ "#[cfg_attr(feature = «\"arbitrary\"ˇ», derive(arbitrary::Arbitrary))]",
+ Mode::HelixNormal,
+ );
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state(
+ "#[cfg_attr(«feature = \"arbitrary\", derive(arbitrary::Arbitrary)ˇ»)]",
+ Mode::HelixNormal,
+ );
+ cx.simulate_keystrokes("m i m");
+ cx.assert_state(
+ "#[«cfg_attr(feature = \"arbitrary\", derive(arbitrary::Arbitrary))ˇ»]",
+ Mode::HelixNormal,
+ );
+
+ // Like other text objects, `m` also works with `]` and `[`.
+ cx.set_state("foo ˇbar (baz)", Mode::HelixNormal);
+ cx.simulate_keystrokes("] m");
+ cx.assert_state("foo bar «(baz)ˇ»", Mode::HelixNormal);
+
+ cx.set_state("(baz) foˇo", Mode::HelixNormal);
+ cx.simulate_keystrokes("[ m");
+ cx.assert_state("«ˇ(baz)» foo", Mode::HelixNormal);
+ }
+
+ #[gpui::test]
+ async fn test_helix_treesitter_object_keys(cx: &mut gpui::TestAppContext) {
+ let mut cx = VimTestContext::new(cx, true).await;
+
+ // In Helix, `t` is the type text object, not an HTML tag.
+ cx.set_state(
+ indoc! {"
+ const A: usize = 1;
+ struct Foo {
+ barˇ: usize,
+ }"},
+ Mode::HelixNormal,
+ );
+ cx.simulate_keystrokes("m a t");
+ cx.assert_state(
+ indoc! {"
+ const A: usize = 1;
+ «struct Foo {
+ bar: usize,
+ }ˇ»"},
+ Mode::HelixNormal,
+ );
+
+ // In Helix, `c` is the comment text object, not a class.
+ cx.set_state(
+ indoc! {"
+ fn foo() {
+ // some coˇmment
+ bar();
+ }"},
+ Mode::HelixNormal,
+ );
+ cx.simulate_keystrokes("m a c");
+ cx.assert_state(
+ indoc! {"
+ fn foo() {
+ «// some commentˇ»
+ bar();
+ }"},
+ Mode::HelixNormal,
+ );
+ }
+
+ #[gpui::test]
+ async fn test_helix_xml_element_object_key(cx: &mut gpui::TestAppContext) {
+ let mut cx = VimTestContext::new_html(cx).await;
+
+ // In Helix, `x` is the (X)HTML element text object.
+ cx.set_state("<div>heˇllo</div>", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i x");
+ cx.assert_state("<div>«helloˇ»</div>", Mode::HelixNormal);
+
+ cx.set_state("<div>heˇllo</div>", Mode::HelixNormal);
+ cx.simulate_keystrokes("m a x");
+ cx.assert_state("«<div>hello</div>ˇ»", Mode::HelixNormal);
+ }
}
diff --git a/crates/vim/src/helix/surround.rs b/crates/vim/src/helix/surround.rs
index 976a27390b3..98cdc9e9655 100644
--- a/crates/vim/src/helix/surround.rs
+++ b/crates/vim/src/helix/surround.rs
@@ -1,41 +1,12 @@
use editor::display_map::DisplaySnapshot;
-use editor::{Bias, DisplayPoint, MultiBufferOffset};
+use editor::{Bias, DisplayPoint, MultiBufferOffset, movement};
use gpui::{Context, Window};
use multi_buffer::Anchor;
use text::Selection;
use crate::Vim;
-use crate::object::surrounding_markers;
-use crate::surrounds::{SURROUND_PAIRS, bracket_pair_for_str_helix, surround_pair_for_char_helix};
-
-/// Find the nearest surrounding bracket pair around the cursor.
-fn find_nearest_surrounding_pair(
- display_map: &DisplaySnapshot,
- cursor: DisplayPoint,
-) -> Option<(char, char)> {
- let cursor_offset = cursor.to_offset(display_map, Bias::Left);
- let mut best_pair: Option<(char, char)> = None;
- let mut min_range_size = usize::MAX;
-
- for pair in SURROUND_PAIRS {
- if let Some(range) =
- surrounding_markers(display_map, cursor, true, true, pair.open, pair.close)
- {
- let start_offset = range.start.to_offset(display_map, Bias::Left);
- let end_offset = range.end.to_offset(display_map, Bias::Right);
-
- if cursor_offset >= start_offset && cursor_offset <= end_offset {
- let size = end_offset - start_offset;
- if size < min_range_size {
- min_range_size = size;
- best_pair = Some((pair.open, pair.close));
- }
- }
- }
- }
-
- best_pair
-}
+use crate::object::{DelimiterRange, innermost_surrounding_pair, surrounding_markers};
+use crate::surrounds::{bracket_pair_for_str_helix, surround_pair_for_char_helix};
fn surrounding_markers_containing_cursor(
display_map: &DisplaySnapshot,
@@ -55,6 +26,34 @@ fn surrounding_markers_containing_cursor(
}
}
+/// The delimiter ranges of the pair surrounding the cursor: a literal search
+/// for an explicit pair character, or the tree-sitter based closest pair for
+/// 'm', matching `mim`/`mam`.
+fn surrounding_pair_ranges(
+ display_map: &DisplaySnapshot,
+ cursor: DisplayPoint,
+ target_char: char,
+) -> Option<DelimiterRange> {
+ match surround_pair_for_char_helix(target_char) {
+ Some(pair) => {
+ let range =
+ surrounding_markers_containing_cursor(display_map, cursor, pair.open, pair.close)?;
+ let open_start = range.start.to_offset(display_map, Bias::Left);
+ let open_end = open_start + pair.open.len_utf8();
+ let close_end = range.end.to_offset(display_map, Bias::Left);
+ let close_start = close_end - pair.close.len_utf8();
+ Some(DelimiterRange {
+ open: open_start..open_end,
+ close: close_start..close_end,
+ })
+ }
+ None => {
+ let cursor_range = cursor..movement::right(display_map, cursor);
+ innermost_surrounding_pair(display_map, cursor_range)
+ }
+ }
+}
+
fn selection_cursor(map: &DisplaySnapshot, selection: &Selection<DisplayPoint>) -> DisplayPoint {
if selection.reversed || selection.is_empty() {
selection.head()
@@ -63,6 +62,23 @@ fn selection_cursor(map: &DisplaySnapshot, selection: &Selection<DisplayPoint>)
}
}
+/// Anchor a pre-edit selection so it survives the surround edits with its
+/// direction intact, the way Helix maps selections through a transaction.
+fn preserved_selection_anchors(
+ display_map: &DisplaySnapshot,
+ selection: &Selection<DisplayPoint>,
+) -> std::ops::Range<Anchor> {
+ let range = selection.range();
+ let snapshot = display_map.buffer_snapshot();
+ let start = snapshot.anchor_before(range.start.to_offset(display_map, Bias::Left));
+ let end = snapshot.anchor_before(range.end.to_offset(display_map, Bias::Left));
+ if selection.reversed {
+ end..start
+ } else {
+ start..end
+ }
+}
+
type SurroundEdits = Vec<(std::ops::Range<MultiBufferOffset>, String)>;
type SurroundAnchors = Vec<std::ops::Range<Anchor>>;
@@ -109,10 +125,20 @@ impl Vim {
let start = range.start.to_offset(display_map, Bias::Right);
let end = range.end.to_offset(display_map, Bias::Left);
- let end_anchor = display_map.buffer_snapshot().anchor_before(end);
+ // Like Helix, the new selection covers the surrounded text
+ // including the added delimiters, so that surrounds compose
+ // and `i`/`a` land outside the pair. The anchor biases make
+ // the selection grow over the insertions at its edges.
+ let snapshot = display_map.buffer_snapshot();
+ let start_anchor = snapshot.anchor_before(start);
+ let end_anchor = snapshot.anchor_after(end);
edits.push((end..end, pair.end.clone()));
edits.push((start..start, pair.start.clone()));
- anchors.push(end_anchor..end_anchor);
+ if selection.reversed {
+ anchors.push(end_anchor..start_anchor);
+ } else {
+ anchors.push(start_anchor..end_anchor);
+ }
}
(edits, anchors)
@@ -138,41 +164,11 @@ impl Vim {
for selection in selections {
let cursor = selection_cursor(display_map, &selection);
+ anchors.push(preserved_selection_anchors(display_map, &selection));
- // For 'm', find the nearest surrounding pair
- let markers = match surround_pair_for_char_helix(old_char) {
- Some(pair) => Some((pair.open, pair.close)),
- None => find_nearest_surrounding_pair(display_map, cursor),
- };
-
- let Some((open_marker, close_marker)) = markers else {
- let offset = selection.head().to_offset(display_map, Bias::Left);
- let anchor = display_map.buffer_snapshot().anchor_before(offset);
- anchors.push(anchor..anchor);
- continue;
- };
-
- if let Some(range) = surrounding_markers_containing_cursor(
- display_map,
- cursor,
- open_marker,
- close_marker,
- ) {
- let open_start = range.start.to_offset(display_map, Bias::Left);
- let open_end = open_start + open_marker.len_utf8();
- let close_end = range.end.to_offset(display_map, Bias::Left);
- let close_start = close_end - close_marker.len_utf8();
-
- edits.push((close_start..close_end, new_pair.end.clone()));
- edits.push((open_start..open_end, new_pair.start.clone()));
-
- let cursor_offset = cursor.to_offset(display_map, Bias::Left);
- let anchor = display_map.buffer_snapshot().anchor_before(cursor_offset);
- anchors.push(anchor..anchor);
- } else {
- let offset = selection.head().to_offset(display_map, Bias::Left);
- let anchor = display_map.buffer_snapshot().anchor_before(offset);
- anchors.push(anchor..anchor);
+ if let Some(pair) = surrounding_pair_ranges(display_map, cursor, old_char) {
+ edits.push((pair.close, new_pair.end.clone()));
+ edits.push((pair.open, new_pair.start.clone()));
}
}
@@ -195,41 +191,11 @@ impl Vim {
for selection in selections {
let cursor = selection_cursor(display_map, &selection);
+ anchors.push(preserved_selection_anchors(display_map, &selection));
- // For 'm', find the nearest surrounding pair
- let markers = match surround_pair_for_char_helix(target_char) {
- Some(pair) => Some((pair.open, pair.close)),
- None => find_nearest_surrounding_pair(display_map, cursor),
- };
-
- let Some((open_marker, close_marker)) = markers else {
- let offset = selection.head().to_offset(display_map, Bias::Left);
- let anchor = display_map.buffer_snapshot().anchor_before(offset);
- anchors.push(anchor..anchor);
- continue;
- };
-
- if let Some(range) = surrounding_markers_containing_cursor(
- display_map,
- cursor,
- open_marker,
- close_marker,
- ) {
- let open_start = range.start.to_offset(display_map, Bias::Left);
- let open_end = open_start + open_marker.len_utf8();
- let close_end = range.end.to_offset(display_map, Bias::Left);
- let close_start = close_end - close_marker.len_utf8();
-
- edits.push((close_start..close_end, String::new()));
- edits.push((open_start..open_end, String::new()));
-
- let cursor_offset = cursor.to_offset(display_map, Bias::Left);
- let anchor = display_map.buffer_snapshot().anchor_before(cursor_offset);
- anchors.push(anchor..anchor);
- } else {
- let offset = selection.head().to_offset(display_map, Bias::Left);
- let anchor = display_map.buffer_snapshot().anchor_before(offset);
- anchors.push(anchor..anchor);
+ if let Some(pair) = surrounding_pair_ranges(display_map, cursor, target_char) {
+ edits.push((pair.close, String::new()));
+ edits.push((pair.open, String::new()));
}
}
@@ -251,19 +217,50 @@ mod test {
cx.set_state("hello ˇworld", Mode::HelixNormal);
cx.simulate_keystrokes("m s (");
- cx.assert_state("hello (wˇ)orld", Mode::HelixNormal);
+ cx.assert_state("hello «(w)ˇ»orld", Mode::HelixNormal);
cx.set_state("hello ˇworld", Mode::HelixNormal);
cx.simulate_keystrokes("m s )");
- cx.assert_state("hello (wˇ)orld", Mode::HelixNormal);
+ cx.assert_state("hello «(w)ˇ»orld", Mode::HelixNormal);
cx.set_state("hello «worlˇ»d", Mode::HelixNormal);
cx.simulate_keystrokes("m s [");
- cx.assert_state("hello [worlˇ]d", Mode::HelixNormal);
+ cx.assert_state("hello «[worl]ˇ»d", Mode::HelixNormal);
cx.set_state("hello «worlˇ»d", Mode::HelixNormal);
cx.simulate_keystrokes("m s \"");
- cx.assert_state("hello \"worlˇ\"d", Mode::HelixNormal);
+ cx.assert_state("hello «\"worl\"ˇ»d", Mode::HelixNormal);
+
+ // The selection direction is preserved.
+ cx.set_state("hello «ˇworl»d", Mode::HelixNormal);
+ cx.simulate_keystrokes("m s (");
+ cx.assert_state("hello «ˇ(worl)»d", Mode::HelixNormal);
+ }
+
+ #[gpui::test]
+ async fn test_helix_surround_add_composes(cx: &mut gpui::TestAppContext) {
+ let mut cx = VimTestContext::new(cx, true).await;
+ cx.enable_helix();
+
+ // The new selection includes the added delimiters, so `i` prepends
+ // before the opening delimiter: i32 -> Vec<i32>.
+ cx.set_state("let x: iˇ32 = 5;", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i w m s <");
+ cx.assert_state("let x: «<i32>ˇ» = 5;", Mode::HelixNormal);
+ cx.simulate_keystrokes("i");
+ cx.assert_state("let x: ˇ<i32> = 5;", Mode::Insert);
+ cx.simulate_keystrokes("V e c");
+ cx.assert_state("let x: Vecˇ<i32> = 5;", Mode::Insert);
+
+ // `a` appends after the closing delimiter.
+ cx.set_state("hello woˇrld test", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i w m s ( a");
+ cx.assert_state("hello (world)ˇ test", Mode::Insert);
+
+ // Surround adds chain, each wrapping the previous result.
+ cx.set_state("hello woˇrld test", Mode::HelixNormal);
+ cx.simulate_keystrokes("m i w m s \" m s (");
+ cx.assert_state("hello «(\"world\")ˇ» test", Mode::HelixNormal);
}
#[gpui::test]
@@ -302,6 +299,11 @@ mod test {
cx.set_state("((woˇrld))", Mode::HelixNormal);
cx.simulate_keystrokes("m d (");
cx.assert_state("(woˇrld)", Mode::HelixNormal);
+
+ // A non-empty selection survives the deletion.
+ cx.set_state("(«woˇ»rld)", Mode::HelixNormal);
+ cx.simulate_keystrokes("m d (");
+ cx.assert_state("«woˇ»rld", Mode::HelixNormal);
}
#[gpui::test]
@@ -340,6 +342,11 @@ mod test {
cx.set_state("((woˇrld))", Mode::HelixNormal);
cx.simulate_keystrokes("m r ( [");
cx.assert_state("([woˇrld])", Mode::HelixNormal);
+
+ // A non-empty selection survives the replacement.
+ cx.set_state("(«woˇ»rld)", Mode::HelixNormal);
+ cx.simulate_keystrokes("m r ( [");
+ cx.assert_state("[«woˇ»rld]", Mode::HelixNormal);
}
#[gpui::test]
@@ -371,7 +378,7 @@ mod test {
cx.set_state("hello «worldˇ» test", Mode::HelixSelect);
cx.simulate_keystrokes("m s {");
- cx.assert_state("hello {worldˇ} test", Mode::HelixNormal);
+ cx.assert_state("hello «{world}ˇ» test", Mode::HelixNormal);
}
#[gpui::test]
@@ -444,7 +451,7 @@ mod test {
// ms (add) also doesn't use aliases - 'msb' adds literal 'b' surrounds
cx.set_state("hello ˇworld", Mode::HelixNormal);
cx.simulate_keystrokes("m s b");
- cx.assert_state("hello bwˇborld", Mode::HelixNormal);
+ cx.assert_state("hello «bwbˇ»orld", Mode::HelixNormal);
// mr (replace) also doesn't use aliases
cx.set_state("hello (woˇrld) test", Mode::HelixNormal);
@@ -475,6 +482,12 @@ mod test {
cx.simulate_keystrokes("m d m");
cx.assert_state("(woˇrld)", Mode::HelixNormal);
+ // 'm' matches via the language's bracket queries, so brackets inside
+ // a string literal are plain text and the quotes are the closest pair.
+ cx.set_state("let s = (\"a (bˇc) d\");", Mode::HelixNormal);
+ cx.simulate_keystrokes("m d m");
+ cx.assert_state("let s = (a (bˇc) d);", Mode::HelixNormal);
+
// mrm - replace nearest surrounding pair
cx.set_state("hello (woˇrld) test", Mode::HelixNormal);
cx.simulate_keystrokes("m r m [");
diff --git a/crates/vim/src/object.rs b/crates/vim/src/object.rs
index acdf64ecfd3..e0f2b5e78cc 100644
--- a/crates/vim/src/object.rs
+++ b/crates/vim/src/object.rs
@@ -4,7 +4,7 @@ use crate::{
Vim,
motion::{is_subword_end, is_subword_start, right},
state::{Mode, Operator},
- surrounds::{BRACKET_PAIRS, QUOTE_PAIRS, SurroundPair},
+ surrounds::{BRACKET_PAIRS, QUOTE_PAIRS, SURROUND_PAIRS, SurroundPair},
};
use editor::{
Bias, BufferOffset, DisplayPoint, Editor, MultiBufferOffset, ToOffset,
@@ -34,6 +34,7 @@ pub enum Object {
VerticalBars,
AnyBrackets,
MiniBrackets,
+ AnyPair,
Parentheses,
SquareBrackets,
CurlyBrackets,
@@ -182,13 +183,17 @@ fn cover_or_next<I: Iterator<Item = (Range<MultiBufferOffset>, Range<MultiBuffer
type DelimiterPredicate = dyn Fn(&BufferSnapshot, usize, usize) -> bool;
-struct DelimiterRange {
- open: Range<MultiBufferOffset>,
- close: Range<MultiBufferOffset>,
+pub(crate) struct DelimiterRange {
+ pub(crate) open: Range<MultiBufferOffset>,
+ pub(crate) close: Range<MultiBufferOffset>,
}
impl DelimiterRange {
- fn to_display_range(&self, map: &DisplaySnapshot, around: bool) -> Range<DisplayPoint> {
+ pub(crate) fn to_display_range(
+ &self,
+ map: &DisplaySnapshot,
+ around: bool,
+ ) -> Range<DisplayPoint> {
if around {
self.open.start.to_display_point(map)..self.close.end.to_display_point(map)
} else {
@@ -197,6 +202,97 @@ impl DelimiterRange {
}
}
+/// The innermost pair from the language's bracket queries that surrounds
+/// `relative_to` and whose delimiters form a known single-character surround
+/// pair, like Helix's tree-sitter based closest-pair matching. Returns None
+/// in buffers without bracket queries.
+pub(crate) fn innermost_surrounding_pair(
+ map: &DisplaySnapshot,
+ relative_to: Range<DisplayPoint>,
+) -> Option<DelimiterRange> {
+ innermost_surrounding_pair_impl(map, relative_to, PairMatchMode::Any)
+}
+
+pub(crate) fn innermost_surrounding_pair_for_text_object(
+ map: &DisplaySnapshot,
+ relative_to: Range<DisplayPoint>,
+ around: bool,
+) -> Option<DelimiterRange> {
+ innermost_surrounding_pair_impl(map, relative_to, PairMatchMode::ExpandSelection { around })
+}
+
+#[derive(Clone, Copy)]
+enum PairMatchMode {
+ Any,
+ ExpandSelection { around: bool },
+}
+
+fn innermost_surrounding_pair_impl(
+ map: &DisplaySnapshot,
+ relative_to: Range<DisplayPoint>,
+ match_mode: PairMatchMode,
+) -> Option<DelimiterRange> {
+ let snapshot = map.buffer_snapshot();
+ let offset_range =
+ relative_to.start.to_offset(map, Bias::Left)..relative_to.end.to_offset(map, Bias::Left);
+
+ let results = snapshot.map_excerpt_ranges(offset_range, |buffer, _, input_range| {
+ let filter = |open: Range<usize>, close: Range<usize>| {
+ if let PairMatchMode::ExpandSelection { around } = match_mode {
+ let input_range = input_range.start.0..input_range.end.0;
+ let selects_around = input_range == (open.start..close.end);
+ let selects_inside = input_range == (open.end..close.start);
+ // `mam` after `mim` changes the form of the current pair;
+ // every other exact match expands to the enclosing pair.
+ if selects_around || (selects_inside && !around) {
+ return false;
+ }
+ }
+ is_surround_pair_delimiter(buffer, open, close)
+ };
+ let Some((open, close)) = buffer.innermost_enclosing_bracket_ranges(
+ input_range.start.0..input_range.end.0,
+ Some(&filter),
+ ) else {
+ return vec![];
+ };
+ vec![
+ (BufferOffset(open.start)..BufferOffset(open.end), ()),
+ (BufferOffset(close.start)..BufferOffset(close.end), ()),
+ ]
+ })?;
+
+ if results.len() < 2 {
+ return None;
+ }
+
+ Some(DelimiterRange {
+ open: results[0].0.clone(),
+ close: results[1].0.clone(),
+ })
+}
+
+/// Bracket queries can also match multi-character delimiters (e.g. HTML
+/// element tags), which Helix's pair matching rejects.
+fn is_surround_pair_delimiter(
+ buffer: &BufferSnapshot,
+ open: Range<usize>,
+ close: Range<usize>,
+) -> bool {
+ if open.len() != 1 || close.len() != 1 {
+ return false;
+ }
+ match (
+ buffer.chars_at(open.start).next(),
+ buffer.chars_at(close.start).next(),
+ ) {
+ (Some(open_char), Some(close_char)) => SURROUND_PAIRS
+ .iter()
+ .any(|pair| pair.open == open_char && pair.close == close_char),
+ _ => false,
+ }
+}
+
fn find_mini_delimiters(
map: &DisplaySnapshot,
display_point: DisplayPoint,
@@ -337,6 +433,10 @@ actions!(
MiniBrackets,
/// Selects text within any type of brackets.
AnyBrackets,
+ /// Selects text within the closest surrounding pair of any type
+ /// (brackets, quotes, backticks, or vertical bars), based on the
+ /// language's bracket queries, like Helix's `m` text object.
+ AnyPair,
/// Selects a function argument.
Argument,
/// Selects an HTML/XML tag.
@@ -394,6 +494,9 @@ pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
Vim::action(editor, cx, |vim, _: &AnyBrackets, window, cx| {
vim.object(Object::AnyBrackets, window, cx)
});
+ Vim::action(editor, cx, |vim, _: &AnyPair, window, cx| {
+ vim.object(Object::AnyPair, window, cx)
+ });
Vim::action(editor, cx, |vim, _: &BackQuotes, window, cx| {
vim.object(Object::BackQuotes, window, cx)
});
@@ -485,6 +588,7 @@ impl Object {
| Object::Paragraph
| Object::AnyBrackets
| Object::MiniBrackets
+ | Object::AnyPair
| Object::Parentheses
| Object::Tag
| Object::AngleBrackets
@@ -515,6 +619,7 @@ impl Object {
| Object::VerticalBars
| Object::AnyBrackets
| Object::MiniBrackets
+ | Object::AnyPair
| Object::Parentheses
| Object::SquareBrackets
| Object::Tag
@@ -546,6 +651,7 @@ impl Object {
Object::Parentheses
| Object::AnyBrackets
| Object::MiniBrackets
+ | Object::AnyPair
| Object::SquareBrackets
| Object::CurlyBrackets
| Object::AngleBrackets
@@ -739,6 +845,11 @@ impl Object {
})
}
Object::MiniBrackets => find_mini_brackets(map, relative_to, around),
+ Object::AnyPair => {
+ let cursor = relative_to..movement::right(map, relative_to);
+ innermost_surrounding_pair(map, cursor)
+ .map(|pair| pair.to_display_range(map, around))
+ }
Object::SquareBrackets => {
surrounding_markers(map, relative_to, around, self.is_multiline(), '[', ']')
}
diff --git a/crates/vim/src/vim.rs b/crates/vim/src/vim.rs
index 6a0ebce1d7a..c016bd6d415 100644
--- a/crates/vim/src/vim.rs
+++ b/crates/vim/src/vim.rs
@@ -1538,6 +1538,12 @@ impl Vim {
{
context.add("VimControl");
}
+ // `vim_mode` is replaced by "operator"/"waiting" while an operator is
+ // pending, so expose helix-ness separately to allow Helix-specific
+ // bindings in those states (e.g. text objects after `mi`/`ma`).
+ if self.mode.is_helix() {
+ context.add("helix_mode");
+ }
context.set("vim_mode", mode);
context.set("vim_operator", operator_id);
}
diff --git a/docs/src/helix.md b/docs/src/helix.md
index 4cac8818ecd..cec150f00aa 100644
--- a/docs/src/helix.md
+++ b/docs/src/helix.md
@@ -18,3 +18,7 @@ For a detailed list of Helix's default keybindings, please visit the [official H
## Core differences
Any text object that works with `m i` or `m a` also works with `]` and `[`, so for example `] (` selects the next pair of parentheses after the cursor.
+
+In Helix mode, some text object keys follow Helix's meanings instead of Vim's: `m i m` and `m a m` select the closest surrounding pair of any kind (brackets, quotes, backticks, or vertical bars), `t` is the type/class text object, `c` is the comment text object, and `x` is the (X)HTML element text object.
+
+Like Helix, the closest surrounding pair (`m i m`, `m a m`, `m d m`, `m r m`) is matched using the language's syntax tree, so delimiters inside string literals or comments don't count as pairs. In buffers without a language, no pair is matched.
diff --git a/docs/src/vim.md b/docs/src/vim.md
index db8bc03d40e..6604529a575 100644
--- a/docs/src/vim.md
+++ b/docs/src/vim.md
@@ -425,6 +425,7 @@ Vim mode adds several contexts to the `"Editor"` context:
| vim_mode == waiting | Waiting for an arbitrary key (e.g., after typing `f` or `t`) |
| vim_mode == operator | Waiting for another binding to trigger (e.g., after typing `c` or `d`) |
| vim_operator | Set to `none` unless `vim_mode == operator`, in which case it is set to the current operator's default keybinding (e.g., after typing `d`, `vim_operator == d`) |
+| helix_mode | Set when the current mode is a Helix mode (`helix_normal` or `helix_select`), including while an operator is pending and `vim_mode` reports `operator` or `waiting` |
> **Note**: Contexts are matched only on one level at a time. So it is possible to use the expression `"Editor && vim_mode == normal"`, but `"Workspace && vim_mode == normal"` will never match because we set the vim context at the `"Editor"` level.