As I've found myself frequently doing this I mashed up an (improvable) script.
You or someone else might find it useful.
Short explanation:
Basically it searches buffer list and show result in quickfix-window.
Two basic commands is added.
Search <pattern>
: Search all buffers for <pattern>
.
Search1 <pattern>
: Search all buffers for <pattern>
, but only show first result for each buffer. Typically useful for listing all buffers where function, variable foo
is used, (or what ever).
Use bang (:Search! foo
) to append to results.
Additionally GSearch
and GSearch1
is added where difference is that with Search
the script add regex delimiter, e.g.:
foo -> /foo/
Where as GSearch
expect it to be enclosed.
The j
flag is always added to prevent jump.
Code:
There are some hacks to prevent error listing while at the same time keeping the code short. try / catch
was a bit cumbersome on bufdo
.
let s:not_idents = split("/!#$%&\"`´¨'¯()*+,-.:;<=>?¿@[\]^{|}µ¶·¸~±×÷®©«»¬ª°º¹²³¼½¾", '\zs')
" Create a delimited pattern. "
fun! s:Parse_pat(pat)
for c in s:not_idents
if stridx(a:pat, c) == -1
return c . a:pat . c
endif
endfor
echohl Error
echom "Could not delimit pattern '". a:pat ."'"
echohl None
return ''
endfun
fun! s:AllBufSearch(pat, bang, uno, isg)
if a:isg
let pat = a:pat
else
let pat = s:Parse_pat(a:pat)
endif
if pat == ''
return
endif
cclose
let [_buf, _view] = [bufnr("%"), winsaveview()]
let _foldenable = &foldenable
set nofoldenable
" Copy of current qflist. "
let qfc = getqflist()
" Hack to prevent error if no matches. "
call setqflist([{}])
silent execute "bufdo vimgrepadd! " . pat . "j %"
" Restore "
exec "buffer " . _buf
let &foldenable = _foldenable
call winrestview(_view)
" Fix "
let qf = getqflist()
call remove(qf, 0)
" Only one listing per buffer. "
if a:uno
let bn = {}
let i = 0
for m in qf
if has_key(bn, m["bufnr"])
call remove(qf, i)
else
let bn[m["bufnr"]] = 1
call remove(qf[i], "valid")
let i += 1
endif
endfor
endif
if a:bang == "!"
let qf = qfc + qf
endif
" If any matches, copen. "
if len(qf)
call setqflist(qf)
copen
endif
endfun
command! -nargs=1 -bang Search call s:AllBufSearch(<q-args>, "<bang>", 0, 0)
command! -nargs=1 -bang Search1 call s:AllBufSearch(<q-args>, "<bang>", 1, 0)
command! -nargs=1 -bang GSearch call s:AllBufSearch(<q-args>, "<bang>", 0, 1)
command! -nargs=1 -bang GSearch1 call s:AllBufSearch(<q-args>, "<bang>", 1, 1)