I would like to list the matches, when I hit:
/example
so that I see where all matches are at once.
I would like to list the matches, when I hit:
/example
so that I see where all matches are at once.
:g//p
In its longer form:
:global/regular-expression/print
You can leave out the pattern/regex and Vim will re-use the previous search term.
Trivia: The grep tool was named after this command sequence.
You can also do a :
g/pattern/#
that will print the pattern you want and the number of the line.
if you want to look at this list and jump quickly between the matches, consider using
:vimgrep example %
or
:grep example %
This will populate the "error list" with all of the matches so that you can use :copen to list them all in the quickfix buffer, press enter on a particular line to jump to that match, or use commands like :cn and :cp to go back and forth.
for a thorough explanation, see my reply to a similar question
Another possibility is to use the include file search commands.
[I
This will list all occurrences of the word under the cursor. It may be more than you need though, because it will also search any files that are included in the current file.
But the nice thing about this command is that the search result display also shows a count of the number of matches, in addition to the line number of each match.
:help include-search
to see lots of variants.
A note about
:g//p
This can be reduced further to
:g//
because, as others have said, p(rint) is the default action.
Using :set hlsearch will highlight all the matches in yellow allowing you to scan the file easily for matches. That may not be what you want though, after searching, :g//p will give you the listed matches
To elaborate on this ... instead of
/example
:g//p
you can also write directly
:g/example/p
or, as p(rint) is the default action for the :g(lobal) command, this can be shortened to
:g/example
And instead of p(rint), other actions are possible, e.g. d(elete). See :help :global
I have written a piece of code for this. It actually avoids the problems in vimgrep. It works even with unnamed files. And it is easier to use.
function! Matches(pat)
let buffer=bufnr("") "current buffer number
let b:lines=[]
execute ":%g/" . a:pat . "/let b:lines+=[{'bufnr':" . 'buffer' . ", 'lnum':" . "line('.')" . ", 'text': escape(getline('.'),'\"')}]"
call setloclist(0, [], ' ', {'items': b:lines})
lopen
endfunction
When you call it with a pattern, it opens the location windows with all the matches.
This could be a command
command! -nargs=1 Mat call Matches(<f-args>)
So all you need to do is to type :Mat pattern
I also use the following mapping to get the matches of the current visual selection.
vnoremap Y "xy:call Matches(@x)<CR>
Ctrl-f to list all search result:
nmap <C-f> :vimgrep /<C-r>//g %<CR> \| !:copen <Enter>