0

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?

Yu Zhou
  • 788
  • 6
  • 11

1 Answers1

1

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
Peter Rincker
  • 43,539
  • 9
  • 74
  • 101