Skip to content

Commit

Permalink
Add a join_ranges command
Browse files Browse the repository at this point in the history
  • Loading branch information
the-mikedavis committed Dec 24, 2022
1 parent 7a33325 commit 4a8cbcf
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 1 deletion.
13 changes: 13 additions & 0 deletions helix-core/src/selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,19 @@ impl Selection {

Selection::new(ranges, self.primary_index)
}

/// Creates a new selection in which all ranges are merged into one.
///
/// The new range covers from the lowest [Range::from] to the highest
/// [Range::to].
pub fn join_ranges(&self) -> Selection {
// SAFETY: selections created with Selection::new are asserted to have
// non-empty range vectors.
let first = self.ranges.first().unwrap();
let last = self.ranges.last().unwrap();

Selection::new(smallvec![first.union(*last)], 0)
}
}

impl<'a> IntoIterator for &'a Selection {
Expand Down
16 changes: 16 additions & 0 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,7 @@ impl MappableCommand {
select_shortest_selection_to_register, "Select shortest selection for each pair and save to register",
select_longest_selection_from_register, "Select longest selection for each pair from register",
select_longest_selection_to_register, "Select longest selection for each pair and save to register",
join_selections, "Join all selections into one",
);
}

Expand Down Expand Up @@ -5427,3 +5428,18 @@ pub mod range_combination {
}
}
}

fn join_selections(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
let doc_selection = doc.selection(view.id);
let range_count = doc_selection.ranges().len();

let selection = doc_selection.join_ranges();

doc.set_selection(view.id, selection);
cx.editor.set_status(format!(
"Joined {} range{}",
range_count,
if range_count == 1 { "" } else { "s" }
));
}
2 changes: 1 addition & 1 deletion helix-term/src/keymap/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ pub fn default() -> HashMap<Mode, Keymap> {
"^" => { "Selections"
"s" => save_selection_to_register,
"S" => restore_selection,
// "j" => join_selections,
"j" => join_selections,
"c" => { "Combine selection from register"
"a" => append_selection_from_register,
"u" => union_selection_from_register,
Expand Down
20 changes: 20 additions & 0 deletions helix-term/tests/test/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,3 +378,23 @@ async fn test_union_marker() -> anyhow::Result<()> {

Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_join_selections() -> anyhow::Result<()> {
test((
indoc! {"\
#(foo|)#
bar
#[baz|]#"
},
"^j",
indoc! {"\
#[foo
bar
baz|]#"
},
))
.await?;

Ok(())
}

0 comments on commit 4a8cbcf

Please sign in to comment.