Limit a grep search in vim to files with the same extension as the current file
-
07-07-2021 - |
Question
I'm trying to make a key mapping that will grep for the word under the cursor. Here's what I have so far:
map <Leader>g :grep -r '<C-R><C-W>' ./<CR><CR>:cw<CR>
I would like this to only find files of the type I'm currently working on (so, for example, grepping in a .coffee file doesn't list .js files). With grep, you can do (for example):
grep -r --include='*.coffee' 'whatever' ./
to only search for files with a certain extension. To do this, I need the current file's extension. So, what's the easiest way to get the current file's extension?
If there's a better way to accomplish this task, that would be great too.
Solution
Of course, right after I give up and ask on SO, I figure it out...
map <Leader>g :grep -r --include='*.<C-R>=expand('%:e')<CR>' '<C-R><C-W>' ./<CR><CR>:cw<CR>
expand() returns all sorts of information about the current buffer. Check out :help expand() for the details.
In this case, expand('%:e') returns the extension of the current file.
In command-line mode, <C-R>=some_function()<CR> will insert the result of some_function() in the command-line.