Search pattern in all open files

2 Points

Lifepillar Lifepillar

2 years ago

Find all the occurrences of a pattern in all the open files and show the result in the quickfix window. For example:

:SearchAll var\d\+

Note that /in the pattern, if present, must be escaped.

fun! s:search_open_files(pattern)
  let l:files = map(filter(range(1, bufnr('$')), 'buflisted(v:val)'), 'fnameescape(bufname(v:val))')
  try
    silent noautocmd execute "vimgrep /" . a:pattern . "/gj " . join(l:files)
  catch /^Vim\%((\a\+)\)\=:E480/
    echomsg "No match"
  endtry
  bo cwindow
endf

command! -nargs=1 SearchAll call <sid>search_open_files(<q-args>)