59

I am new to vim, and still exploring some features of it. I have a problem with vimgrep. I can search for a pattern like this vimgrep /define/ ** so that it finds and opens next file that contains a define. But I couldn't yet find out how to go to the next file/line that matches my pattern. Any pointers?

kenorb
  • 155,785
  • 88
  • 678
  • 743
yasar
  • 13,158
  • 28
  • 95
  • 160

2 Answers2

92

Useful commands for the quickfix list (brackets around omittable part of the commands):

  • :cn[ext] and :cp[revious] jump to next and previous entry
  • :cnf[ile] and :cpf[ile] jump to next and previous file (if the quickfix list is not sorted by file you could write a function that getqflist(), performs a sort and then setqflist()
  • :cr[ewind] and :cla[st] go to beginning or end of the quickfix list
  • :col[der] and :cnew[er] will iterate through historical quickfix lists.

Needless to say there are plenty of other commands and you can discover them at :help quickfix.

Personally I have the following maps :

      | ø      | SHIFT   | CTRL
------+--------+---------+---------
<F11> | :cprev | :cpfile | :colder
<F12> | :cnext | :cnfile | :cnewer

Of course if you use the location list instead of the quickfix list (:lvimgrep) the same commands exist, just replace the initial c with an l and that's it.

Vim 8 Additions:

  • :cdo : perform a command on all entries of quickfix list. For example
    :vim /foo/ *.cpp *.h *.hpp can be followed by
    :cdo s/pattern/replacement/g
  • :cfdo: perform a command an all files in quickfix list. For example,
    :vim /foo/ *.cpp *.h *.hpp can be followed by
    :cfdo %s/2ndpattern/2ndreplacement/g
Benoit
  • 76,634
  • 23
  • 210
  • 236
  • 9
    The popular [unimpaired.vim](http://www.vim.org/scripts/script.php?script_id=1590) plugin maps `:cprev` and `:cnext` to `[q` and `]q`. Takes very little getting used to. – glts Jun 17 '13 at 18:35
  • 1
    It also maps `[` and `]` to `:cpfile` and `:cnfile`. – Jim Stewart Feb 05 '14 at 19:41
  • N.B. This is not to be confused with `:cNext` which is what comes up first for me if I type `:cn` and then hit tab. The problem being that you just get a 'No more items' error, because as @RandyMorris' answer points out `:cNext` goes in reverse. I just assumed something was wrong. – icc97 May 13 '17 at 23:16
  • What is the meaning of :c? – Tamil Sep 20 '21 at 18:44
10

To jump to the next occurrence of the patter you can use :cnext. You can go in reverse with :cNext.

I'm not sure of a way to skip all occurrences until the next file automatically, but you could open the quickfix window with :cwindow to see a list of matches and navigate to those matches by hitting Enter on the entry in the list.

Randy Morris
  • 39,631
  • 8
  • 69
  • 76