Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim - Commands to visually select a regex match?

Tags:

vim

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.

like image 515
Evgeni Sergeev Avatar asked Feb 19 '12 09:02

Evgeni Sergeev


People also ask

How do I match a pattern in Vim?

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.

Does Vim search use Regex?

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 )

How do I select a word in Vim?

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.

What does match in Regex?

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.


2 Answers

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.

like image 196
Daniel Wagner Avatar answered Oct 22 '22 06:10

Daniel Wagner


: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).

like image 34
ninjalj Avatar answered Oct 22 '22 04:10

ninjalj