Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am looking for a way to open all files that contain a specific string in new vim tabs.

The files are not in a specific directory, but scattered across a directory tree.

Ideally I want to jump to the position of the string match in each file.

Even better if it can be executed form within vim

share|improve this question

migrated from Jun 5 '13 at 16:18

This question came from our site for professional and enthusiast programmers.

it's not exactly what you're looking for, but you can find all files containing your string as follows:

:grep -r "string" directory

and then browse the results using:


that opens a quickfix window containing the results, and then you can get up/down in the list, and press <CR> to load that file at the matched line in a new buffer.

It's the vim way of grepping. Of course, you can use :vimgrep instead, or use the Grep plugin or the Ack plugin. The ack plugin has a feature to open the result in a new tab, if you press t instead of <CR> on a result line.

share|improve this answer
is there a way to set 'directory' to pwd and sub-directories so I don't type it every time? – ppp Jun 5 '13 at 18:09
Use a dot: :grep -r "string" . – romainl Jun 5 '13 at 19:35

You could put the following in your .vimrc file:

com! -nargs=+ PatternFilesToTabs call s:PatternFilesToTabs(<q-args>)

function! s:PatternFilesToTabs(pattern)
    let savelz=&lz
    let savlast=@#
    let savfile=@%
    let hash={}
    let files=[]
    sil! redir => result
    exec 'sil! grep ' . a:pattern . ' -r .'
    sil! redir end
    for line in split(result, '\n')
        if (match(line, ':\d\+:') > 0)
            let filen=substitute(line, ':.*', '', '')
            if (!has_key(hash,filen))
                let hash[filen] = 1
                let files += [ filen ]
    for filen in files
        exec 'sil! tabedit ' . filen
        sil! call search(a:pattern)
    exec 'sil! tabp ' . len(files)
    exec 'sil! edit ' . savlast
    exec 'sil! edit ' . savfile
    let &lz=savelz
share|improve this answer
And how should I use it after that? – ppp Jun 6 '13 at 0:21
To use just do :PatternFilesToTabs pattern – cforbish Jun 6 '13 at 1:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .