4

How does one move to the next match in Vimscript? The way you would when matching an expression and then hitting n?

5
  • 4
    :h :search() ?
    – statox
    Mar 22 '16 at 15:01
  • Good catch @statox. search() requires we know the regex to pass it again. :normal! n doesn't require us to know the regex. If you need the next match without knowing exactly the pattern to search, :norm! n is the closest to the initial question. But when you know the pattern, prefer search(), it won't mess the search register nor the search history, and you won't have to escape slashes either. Mar 22 '16 at 17:23
  • @LucHermitte couldn't you just use search(@/) to get the last used regex instead of using :normal! n? This would combine the benefits of both solutions.
    – Ingo
    Mar 27 '16 at 14:06
  • @Ingo, Indeed, we could also use search(@/). However, note that while this won't change the search register, it uses it. Somehow, it won't make any difference with norm! n. Mar 28 '16 at 11:38
  • @LucHermitte you're right, of course. I was thinking about 'side effects' in general and didn't realize all of those already happened when I use @/...
    – Ingo
    Mar 29 '16 at 15:22
6

Just use :normal.

-> :norm n

(:h :normal)

6

You can use the vimscript function search() (see :h search()).

The signature of the function is:

search({pattern} [, {flags} [, {stopline} [, {timeout}]]])

It has several advantages:

  • The function returns 0 if no match is found and it returns the number of the line of the match if one is found.
  • Thanks to the flags you can modify the behavior of the function. For example if you specify the tag e your cursor will be positioned at the end of the match instead of at the beginning.
  • You can restrict the search to a range of lines with the stopline argument. For example is you specify a value which is not zero the search will not wrap around the end of the file i.e. when the last match of the file is found, the search will not continue to the top of the file.
  • Also as @LucHermitte mentionned in his comment the use of this function won't mess the search register and history and will reduced the troubled of escaping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.