Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use vimgrep for a visual selection of the current file?

I would like to search with vimgrep only within a visual selection of the current file and not the whole file. Is that possible and how? I couldn't find something for this case with Google or in vim help.

The reason why I want this is because I need the result in the quicklist (copen) and :g/FOO which is showing the matching lines at the bottom is not doing this job.

like image 670
Cutú Chiqueño Avatar asked Jan 31 '14 15:01

Cutú Chiqueño


Video Answer


2 Answers

Yes, you can, as Vim has special regular expression atoms for mark positions, and the start and end of the visual selection is marked by '< and '>. As there are atoms for on / before / after a mark, we need to combine those to cover the entire range of selected lines:

On the selection start | after the selection start and before the selection end | on the selection end.

To limit the search to the current file, the special % keyword is used.

:vimgrep/\%(\%'<\|\%>'<\%<'>\|\%'>\)FOO/ %
like image 68
Ingo Karkat Avatar answered Sep 23 '22 17:09

Ingo Karkat


You are on the right path with using :g command. The basic idea is do something like this:

:g/FOO/caddexpr expand("%") . ":" . line(".") .  ":" . getline(".")

Now lets make it a command

command! -range -nargs=+ VisualSeach cgetexpr []|<line1>,<line2>g/<args>/caddexpr expand("%") . ":" . line(".") .  ":" . getline(".")

Now you can do :VisualSearch FOO and it will add the searches to the quickfix list.

Note that the issue w/ this is only finds one match per line.

like image 29
Peter Rincker Avatar answered Sep 25 '22 17:09

Peter Rincker