Skip to content

Commit

Permalink
shrink_selection without history selects first contained child
Browse files Browse the repository at this point in the history
This changes the behavior of `shrink_history` to iterate through
child nodes until it finds one that is strictly contained within the
selection, i.e. exclusively. This produces more intuitive behavior for
selecting the "first logical thing" inside the selection.
  • Loading branch information
dead10ck committed Mar 6, 2023
1 parent 51816df commit ae7e718
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
19 changes: 19 additions & 0 deletions helix-core/src/movement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,25 @@ pub fn goto_treesitter_object(
last_range
}

/// Finds the first child node under the given input node that is fully
/// contained (i.e. strictly inside, non-inclusive) within the given range.
pub fn find_first_contained_child<'n>(
mut node: Node<'n>,
range: &Range,
text: RopeSlice,
) -> Option<Node<'n>> {
let start = text.char_to_byte(range.from());
let end = text.char_to_byte(range.to());
let mut cursor = node.walk();
let mut children = node.children(&mut cursor);

while node.start_byte() <= start || node.end_byte() >= end {
node = children.next()?;
}

Some(node)
}

#[cfg(test)]
mod test {
use ropey::Rope;
Expand Down
5 changes: 3 additions & 2 deletions helix-core/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ pub fn expand_selection(syntax: &Syntax, text: RopeSlice, selection: Selection)
}

pub fn shrink_selection(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection {
select_node_impl(syntax, text, selection, |descendant, _from, _to| {
descendant.child(0).or(Some(descendant))
select_node_impl(syntax, text, selection, |descendant, from, to| {
let range = Range::new(from, to);
crate::movement::find_first_contained_child(descendant, &range, text).or(Some(descendant))
})
}

Expand Down
22 changes: 20 additions & 2 deletions helix-term/tests/test/commands/movement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,18 +89,36 @@ async fn expand_shrink_selection() -> anyhow::Result<()> {
),
// shrink with no expansion history defaults to first child
(
helpers::platform_line(indoc! {r##"
#[(
Some(thing),
Some(other_thing),
)|]#
"##}),
"<A-i>",
helpers::platform_line(indoc! {r##"
(
#[Some(thing)|]#,
Some(other_thing),
)
"##}),
"<A-i>",
),
// any movement cancels selection history and falls back to first child
(
helpers::platform_line(indoc! {r##"
(
#[Some|]#(thing),
Some(#[thing|]#),
Some(#(other_thing|)#),
)
"##}),
"<A-o><A-o><A-o>jkvkkk<A-i>",
helpers::platform_line(indoc! {r##"
(
#[|Some(thing)]#,
Some(other_thing),
)
"##}),
),
];
Expand Down

0 comments on commit ae7e718

Please sign in to comment.