How to find out if a search was successful in vimscript?

I am trying to learn vimscript. I read a lot in "Learn vimscript in a difficult way", but did not find answers to my questions:

How can I find out if the search was successful in vimscript? I have two cases:

:if there a ( on the current line do foo :endif :if /searchtarget succeeds do bar :endif 
+6
source share
2 answers

There are different approaches depending on the context.

: if any (in the current line do foo: endif

You can use search() according to @Kent's answer. It supports the {stopline} argument to avoid that it goes beyond the current line (which you can pass through line('.') ). But it only searches in one direction (forward or backward), so you will need to place the cursor.

So, it seems that if getline('.') =~ '(' Is the best test. It compares regular expressions of the current line with ( . Instead, you can use match() (look for any function via :help for full API documentation and BTW examples) or non-regexp stridx() (which can be faster, but also less readable).

: if / searchtarget succeeds, do bar: endif

Again, this sounds like a use for search() , which will move the cursor to a match, for example /search . But you can also use the latter (with :normal ) and check the transition by comparing the cursor positions (obtained with getpos('.') ) Before and after the command.

+6
source

Vim has a search() function. :h search( to read the description of the function.

If a match is found, func will return the line number, otherwise return 0 . You can do your logic based on the return value of the function.

To check if there is any template in the current row, you can use the search() function, also you can split() text of the current row to see if there is a list of results with more than two elements.

+2
source

Source: https://habr.com/ru/post/1209928/


All Articles