Last active
October 6, 2015 10:28
-
-
Save AndrewRadev/2979701 to your computer and use it in GitHub Desktop.
A simple :Grep
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
" 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