Reputation: 389
I've enjoyed using # to highlight and search for a word (variable) but I would love if I could hit a single command that would simply tell me how many occurrences are in the current file. I've found the following
:%s/dns_name_change_flag/&/gn
But that's too much typing. Is there anyway to maybe map the above one-liner to use the word under cursor?
Upvotes: 3
Views: 1536
Reputation: 11820
I have a function that does not change search register @/
fun! CountWordFunction()
try
let l:win_view = winsaveview()
exec "%s/" . expand("<cword>") . "//gn"
finally
call winrestview(l:win_view)
endtry
endfun
command! -nargs=0 CountWord :call CountWordFunction()
nnoremap <F3> :CountWord<CR>
If you alredy have searched for the word you can just type
:%~n
Upvotes: 1
Reputation: 1538
:map <F2> "zyiw:exe "%s/".@z."//gn"<CR>
add this line (without the ":") to your .vimrc and F2 will be mapped every time you start vim.
It yanks the 'inner word' to the z register and then performs a search in the whole buffer outputting the number of appearances.
This approach differs to the one given by Thor in that way, that it also counts appearances of the word that are not a word themselves, but only part of a word. For example: looking for 'an' will also count 'and'.
This might be helpful too:
"A quick way to list all occurrences of the word under the cursor it to type [I (which displays each line containing the current keyword, in this file and in included files when using a language such as C)."
source: http://vim.wikia.com/wiki/Word_count
Upvotes: 2
Reputation: 172648
I have written a plugin for that: SearchPosition; it provides mappings for the current search pattern and current word / selection, and also lists where the matches occur:
1 match after cursor in this line, 8 following, 2 in previous lines;
total 10 for /\<SearchPosition\>/
Upvotes: 1
Reputation: 84393
You can map a sequence to an external grep command. For example:
:nmap fg :execute '!fgrep --count <cword> %'<CR>
This maps a normal-mode command to fg. The command will run fgrep on the current file in an external process, counting the instances of the word under the cursor.
This operates on the current file, not the current buffer. You need to make sure the file is written to disk (e.g. :write
) before the word count will be accurate.
Upvotes: 1
Reputation: 47169
I don't know how to do this without execute
. The following maps F5
to count occurrences of the word under the cursor using <cword>
and word boundary patterns (\\<
and \\>
):
:map <f5> :execute ":%s@\\<" . expand("<cword>") . "\\>\@&@gn"<CR>
Upvotes: 5