Skip to content

Instantly share code, notes, and snippets.

@oelmekki
Created June 18, 2009 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oelmekki/131905 to your computer and use it in GitHub Desktop.
Save oelmekki/131905 to your computer and use it in GitHub Desktop.
" taken from http://www.vim.org/tips/tip.php?tip_id=860
" CountMatches counts the number of times a pattern matches a
" range of lines
function! CountMatches(pattern, startline, endline) range
let l:match_count = 0
let l:restore_cursor = "normal!" . line(".") . "G" . virtcol(".") . "|"
normal! H
let l:restore_screen = line(".") . "normal!zt"
" move cursor to 1st line of search range
exec "normal!" . a:startline . "G0"
" loop over the lines of the search range looking for pattern
while 1
let l:lnum = search(a:pattern, "W")
" break loop if we are outside of the search range or we didn't
" find a match (l:lnum == 0)
if l:lnum > a:endline || l:lnum == 0
break
endif
let l:match_count = l:match_count + 1
endwhile
exec l:restore_screen
exec l:restore_cursor
" tell the user how many matches we found
echo "Pattern matched " . l:match_count . " times."
endfunction
" Define a command to call the above function
com! -range -nargs=1 CM call CountMatches("<args>", <line1>, <line2>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment