Skip to content

Commit 0586770

Browse files
committed
Add trim_selections command
1 parent 6d4409c commit 0586770

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

book/src/keymap.md

+1
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@
8888
| `s` | Select all regex matches inside selections | `select_regex` |
8989
| `S` | Split selection into subselections on regex matches | `split_selection` |
9090
| `Alt-s` | Split selection on newlines | `split_selection_on_newline` |
91+
| `_` | Trim whitespace from selections | `trim_selections` |
9192
| `;` | Collapse selection onto a single cursor | `collapse_selection` |
9293
| `Alt-;` | Flip selection cursor and anchor | `flip_selections` |
9394
| `,` | Keep only the primary selection | `keep_primary_selection` |

helix-term/src/commands.rs

+29
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,7 @@ impl Command {
272272
// TODO: different description ?
273273
goto_line_end_newline, "Goto line end",
274274
goto_first_nonwhitespace, "Goto first non-blank in line",
275+
trim_selections, "Trim whitespace from selections",
275276
extend_to_line_start, "Extend to line start",
276277
extend_to_line_end, "Extend to line end",
277278
extend_to_line_end_newline, "Extend to line end",
@@ -584,6 +585,34 @@ fn goto_first_nonwhitespace(cx: &mut Context) {
584585
doc.set_selection(view.id, selection);
585586
}
586587

588+
fn trim_selections(cx: &mut Context) {
589+
let (view, doc) = current!(cx.editor);
590+
let text = doc.text().slice(..);
591+
592+
static END_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\S\s+$").unwrap());
593+
594+
let selection = doc.selection(view.id).clone().transform(|range| {
595+
let mut start = range.from();
596+
let mut end = range.to();
597+
let start_byte = text.char_to_byte(start);
598+
599+
start += text
600+
.chars_at(start)
601+
.position(|x| !x.is_whitespace())
602+
.unwrap_or(0);
603+
604+
if let Some(pos) = END_REGEX.find(&range.fragment(text)) {
605+
end = text.byte_to_char(start_byte + pos.start()) + 1;
606+
}
607+
if range.anchor < range.head {
608+
Range::new(start, end)
609+
} else {
610+
Range::new(end, start)
611+
}
612+
});
613+
doc.set_selection(view.id, selection);
614+
}
615+
587616
fn goto_window(cx: &mut Context, align: Align) {
588617
let (view, doc) = current!(cx.editor);
589618

helix-term/src/keymap.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -602,7 +602,7 @@ impl Default for Keymaps {
602602
// "Q" => replay_macro,
603603

604604
// & align selections
605-
// _ trim selections
605+
"_" => trim_selections,
606606

607607
"(" => rotate_selections_backward,
608608
")" => rotate_selections_forward,

0 commit comments

Comments
 (0)