Can't figure out how to automatically select a regex match in visual mode.
For example, manually, I could search for a word
/word
It lands the cursor on the first character of the match "word".
Then I press v
to enter Visual mode, and press llll
to select the whole "word".
Now I want to do this by a macro, and I don't know the length of the match ahead of time.
I expected that Vim would automatically define some built-in marks at the beginning and end of the current match, so that I could ` to them. But I couldn't find any information on that.
What I want is to reassign Ctrl+n
to a macro to take me to the next match and select it in visual mode, i.e. not just highlight the match. (To parallel how n
takes you to the next match.)
If you're wondering why, its because I want to create folds based on regex matches (like Ctrl+n
, zf
), but I'm sure it will come in handy in other cases too.
In normal mode, press / to start a search, then type the pattern ( \<i\> ), then press Enter. If you have an example of the word you want to find on screen, you do not need to enter a search pattern. Simply move the cursor anywhere within the word, then press * to search for the next occurrence of that whole word.
Using Regex in VimMany of Vim's search features allow you to use regular expressions. Some of them are: The search commands ( / and ? ) The global and substitute command-line (ex) commands ( :g and :s )
Press v to begin character-based visual selection, or V to select whole lines, or Ctrl-v or Ctrl-q to select a block. Move the cursor to the end of the text to be cut/copied. While selecting text, you can perform searches and other advanced movement. Press d (delete) to cut, or y (yank) to copy.
Match(String) Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor. Match(String, Int32) Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.
For the benefit of folks who stumble across this question in the future, vim now has this feature built-in: gn
(and its close sibling gN
) will jump to the next (respectively, previous) match and visually select it. It can also be used as a motion; e.g. cgn
will jump to the next match and change it.
:noremap <C-n> //s<CR>v//e+1<CR>
Edit summary: was //e, but //e+1 worked for me (selected the last character of the match too).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With