Skip to content

Commit

Permalink
Add trim_selections command
Browse files Browse the repository at this point in the history
  • Loading branch information
ath3 committed Nov 13, 2021
1 parent 6d4409c commit 0586770
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
1 change: 1 addition & 0 deletions book/src/keymap.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
| `s` | Select all regex matches inside selections | `select_regex` |
| `S` | Split selection into subselections on regex matches | `split_selection` |
| `Alt-s` | Split selection on newlines | `split_selection_on_newline` |
| `_` | Trim whitespace from selections | `trim_selections` |
| `;` | Collapse selection onto a single cursor | `collapse_selection` |
| `Alt-;` | Flip selection cursor and anchor | `flip_selections` |
| `,` | Keep only the primary selection | `keep_primary_selection` |
Expand Down
29 changes: 29 additions & 0 deletions helix-term/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ impl Command {
// TODO: different description ?
goto_line_end_newline, "Goto line end",
goto_first_nonwhitespace, "Goto first non-blank in line",
trim_selections, "Trim whitespace from selections",
extend_to_line_start, "Extend to line start",
extend_to_line_end, "Extend to line end",
extend_to_line_end_newline, "Extend to line end",
Expand Down Expand Up @@ -584,6 +585,34 @@ fn goto_first_nonwhitespace(cx: &mut Context) {
doc.set_selection(view.id, selection);
}

fn trim_selections(cx: &mut Context) {
let (view, doc) = current!(cx.editor);
let text = doc.text().slice(..);

static END_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\S\s+$").unwrap());

let selection = doc.selection(view.id).clone().transform(|range| {
let mut start = range.from();
let mut end = range.to();
let start_byte = text.char_to_byte(start);

start += text
.chars_at(start)
.position(|x| !x.is_whitespace())
.unwrap_or(0);

if let Some(pos) = END_REGEX.find(&range.fragment(text)) {
end = text.byte_to_char(start_byte + pos.start()) + 1;
}
if range.anchor < range.head {
Range::new(start, end)
} else {
Range::new(end, start)
}
});
doc.set_selection(view.id, selection);
}

fn goto_window(cx: &mut Context, align: Align) {
let (view, doc) = current!(cx.editor);

Expand Down
2 changes: 1 addition & 1 deletion helix-term/src/keymap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ impl Default for Keymaps {
// "Q" => replay_macro,

// & align selections
// _ trim selections
"_" => trim_selections,

"(" => rotate_selections_backward,
")" => rotate_selections_forward,
Expand Down

0 comments on commit 0586770

Please sign in to comment.