I'd like to search the current directory recursively for the word under cursor.

Here is what I have now in my .vimrc (Note I'm on Windows):

nmap <leader>f :vimgrep! <cword> **.* <bar> :copen <CR>

This works fine but it searches all the files including object files, project files, etc.

I want vimgrep to search only .c .h .txt files

When I tried the following, it didn't work:

nmap <leader>f :vimgrep! <cword> **.c **.h **.txt <bar> :copen <CR>

What is the right way to do it?

Another question: why adding ! after vimgrep doesn't prevent it from automatically jumping to the first match?


You can use {} to specify different extensions:

nnoremap <leader>f :vimgrep /<c-r><c-w>/j **/*.{c,h,txt} <bar> :copen <CR>

Some suggestions:

  • Use nnoremp unless you want to recursive mappings
  • You may wanto to look into 'wildignore' to ignore object files and other files which should always be ignored
  • You may want to look into faster project grepping tools. e.g. ripgrep & The Silver Searcher
  • You can use the j flag to prevent :vimgrep from jumping the first match. e.g. :vimgrep /foo/j **/*
  • Using ! with :vimgrep will abandon the current buffer when jumping to another buffer. See :h abandon.

For more help see:

:h :vimgrep
:h 'wildignore'
:h :grep
:h 'grepprg'
:h 'grepformat'
  • Thanks for your answer. It works for me. Could you please answer my second question too? – Salahuddin Ahmed Jun 19 '18 at 15:03
  • I tried adding j flag after <cword> but it didn't work. Could you please update the full command with j in the right position? – Salahuddin Ahmed Jun 19 '18 at 15:14
  • 1
    You need to use the / pattern delimiters to use any flags. example: :vimgrep /<c-r><c-w>/j % – Peter Rincker Jun 19 '18 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.