Thomson
Thomson

Reputation: 21615

Search in the result set of previous searched lines in Vim?

Is there a way to search only in the lines which match the pattern in previous search by /pattern? The scenarios is the first search providers some a super set of results, and I'd like to navigate sub-categories inside it.

Upvotes: 0

Views: 78

Answers (2)

Zhouster
Zhouster

Reputation: 746

I was unable to find any built-in vim syntax to do a search over a search. As such, this post attempts to pose a few workarounds in vim that could be used to achieve your goal.

  1. In the case that you are trying to find two patterns on the same line, you could use the line stated in the comments: /.*<pattern1>\&.*<pattern2>. The .* is necessary so that it won't just try to match at beginning. The \& essentially says to match both patterns.

  2. You could search for the pattern through /<pattern1> and then type / and press the up arrow key to display the previously used pattern. You can then add to this previous pattern (not much special about this workaround).

  3. This is a pretty similar response to romainl's, but if you would like to use an external command instead (will be faster): grep <firstpattern> % | copen. This will execute the grep using your external command instead (Vim Quickfix Doc & Vim Grep Wiki). Also, as a general explanation, the % sign is a cmdline special character (Vim Cmdline Special Character Doc), and the copen command opens up the quickfix list.

    Note: you may need to run the copen command outside of the pipe. At least, when I tried, I wasn't able to make the piping work the way I wanted.

Romainl's response (using the quickfix list) is probably the best you can get to an interactive solution. You could try to implement the extra open source code in romainl's link if you feel you need the extra functionality.

These are all the thoughts that come to the top of my head as of right now. Let me know if they find you well, and if not, then I will continue my search.

Upvotes: 1

romainl
romainl

Reputation: 196476

You can't perform a built-in command on a discontinuous range. Your best option is, in my opinion, to do something like:

:vim firstpattern % | cw

then use one of the answers to this question to filter the result with secondpattern.

Upvotes: 1

Related Questions