How would I go about setting up a hotkey (eg: CTRL+g) to perform a VIMGREP operation on the current visual selection in the current buffer? My intent is to show a line-numbered list in the "quickfix" window of all matching search results.
Right now, if I want to get a list of results for a regex search, I could do a command-mode query like so:
:vimgrep /foo/ %
However, there are two problems with this:
- I don't want to have to type out the entire query. I could always do a visual selection, then use CTRL+r, CTRL+w, to paste the current visual selection into the command buffer, but I'd like something simpler than this.
- The above approach requires that the current buffer is already saved to a file. I'd like to be able to work on a temporary buffer I've pasted into VIM rather than having to save a file buffer each time I want to do this.
Thank you.
A low-level solution
Try
[Iand the:ilistcommand:Press
:followed by a line number and<CR>to jump to that line.You can use them on the visual selection with a simple mapping:
You'll probably need to sanitize the register upon insertion, though.
See
:help :ilist.Another even lower-level solution
Since we are at it, let's dig even deeper and find the amazingly simple and elegant:
that you could use in the same way as
:ilistabove:Limitations
The solutions above don't use the quickfix window, obviously, but they allow you to:
They have limitations, though:
:cnextor:clastto move around the result.A higher-level solution
If those limitations are a showstopper, the function below, adapted from justinmk's answer in this /r/vim thread, gives you an almost complete solution:
[Iin normal mode to search for the word under the cursor in the whole buffer,]Iin normal mode to search for the word under the cursor after the current line,[Iin visual mode to search for the selected text in the whole buffer,]Iin visual mode to search for the selected text after the current line.The function below uses the quickfix list/window when the buffer is associated to a file and falls back to the regular behavior of
[Iand]Iotherwise. It could probably be modified to be used as part of an:Ilistcommand.NB:
<C-r><C-w>inserts the word under the cursor, not the visual selection for which there's unfortunately no such shortcut. We have no choice but to yank.