Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A simple :Grep
" Can be called in several ways:
"
" :Grep <something> " -> Grep for the given search query
" :Grep " -> Grep for the word under the cursor
" :'<,'>Grep " -> Grep in visual mode
"
command! -count=0 -nargs=* Grep call s:Grep(<count>, <q-args>)
function! s:Grep(count, args)
try
let original_grepprg = &grepprg
if a:count > 0
" then we've selected something in visual mode
let query = s:LastSelectedText()
if a:count > 1
" Then it's multiline, we need some magic
set grepprg=pcregrep\ -n\ -M
let query = substitute(query, "\n", '.*?\\n.*?', 'g')
endif
elseif empty(a:args)
" If no pattern is provided, search for the word under the cursor
let query = expand("<cword>")
else
let query = a:args
end
exe 'grep -r '.shellescape(query).' .'
finally
let &grepprg = original_grepprg
endtry
endfunction
function! s:LastSelectedText()
let saved_cursor = getpos('.')
let original_reg = getreg('z')
let original_reg_type = getregtype('z')
normal! gv"zy
let text = @z
call setreg('z', original_reg, original_reg_type)
call setpos('.', saved_cursor)
return text
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment