on master help sign in
Add command to add word boundaries to search (#4322)

* Add command to add word boundaries to search * Calculate string capacity before building

commit392a018aebe1716c94be94dbbf967b1698843218 authorArmin Ronacher <armin.ronacher@active-4.com> dateTue 15 Nov 2022, 15:16 (4 years ago) parent77be98c
1 file changed+30
helix-term/src/commands.rs+30
helix-term/src/commands.rs+30
@@ -250,6 +250,7 @@ impl MappableCommand {
250250 extend_search_next, "Add next search match to selection",
251251 extend_search_prev, "Add previous search match to selection",
252252 search_selection, "Use current selection as search pattern",
253+ make_search_word_bounded, "Modify current search to make it word bounded",
253254 global_search, "Global search in workspace folder",
254255 extend_line, "Select current line, if already selected, extend to another line based on the anchor",
255256 extend_line_below, "Select current line, if already selected, extend to next line",
@@ -1809,6 +1810,35 @@ fn search_selection(cx: &mut Context) {
18091810 cx.editor.set_status(msg);
18101811}
18111812
1813+fn make_search_word_bounded(cx: &mut Context) {
1814+ let regex = match cx.editor.registers.last('/') {
1815+ Some(regex) => regex,
1816+ None => return,
1817+ };
1818+ let start_anchored = regex.starts_with("\\b");
1819+ let end_anchored = regex.ends_with("\\b");
1820+
1821+ if start_anchored && end_anchored {
1822+ return;
1823+ }
1824+
1825+ let mut new_regex = String::with_capacity(
1826+ regex.len() + if start_anchored { 0 } else { 2 } + if end_anchored { 0 } else { 2 },
1827+ );
1828+
1829+ if !start_anchored {
1830+ new_regex.push_str("\\b");
1831+ }
1832+ new_regex.push_str(regex);
1833+ if !end_anchored {
1834+ new_regex.push_str("\\b");
1835+ }
1836+
1837+ let msg = format!("register '{}' set to '{}'", '/', &new_regex);
1838+ cx.editor.registers.get_mut('/').push(new_regex);
1839+ cx.editor.set_status(msg);
1840+}
1841+
18121842fn global_search(cx: &mut Context) {
18131843 #[derive(Debug)]
18141844 struct FileResult {