Search code examples
vimgrepincremental-search

vim: define command for grep + copen + incremental search


I'd like to define a custom command for doing the following steps: grep the current word, copen, incremental search the grep'ed word. Here's the command I'm using:

nmap <C-p> :execute "grep! -Irn " . shellescape(expand("<cword>")) . " ."<cr>:copen<cr>:g/<cword>/<cr>

But the second cword is expanded to the current word after the quickfix window is opened. How can I use the word that's used by grep earlier?


Solution

  • The same way you got <cword> into grep:

    nmap <C-p> :execute "grep! -Irn " . shellescape(expand("<cword>")) . " .\<cr>:copen\<cr>:g/" . expand("<cword>"). "/\<cr>"<cr>
    

    Some thoughts:

    • Set the search register instead of :g. E.g. :let @/ = "foo"
    • Use nnoremap
    • Use escape() to make it more resilient. See :h escape(
    • Maybe use :vimgrep. See :h :vimg
    • This is a similar problems solved by the following plugins: visual star, Ack.vim, and Ag.vim