Search code examples
windowsvimfindstr

How do I redirect output into Gvim as a list of files to be opened?


I would like findstr /m background *.vim | gvim to open all *.vim files containing background in a single instance of gvim - but I can't get the piping to work.

This is very similar to this question but instead of capturing the stdin output I would like GViM to treat the output as a list of files to be opened - and on a Windows system so xargs isn't guaranteed. Any ideas?


Solution

  • I can think of a few ways of doing this:

    Use vimgrep

    Use vimgrep: after running gvim, enter:

    :vimgrep /background/ **/*.vim
    

    This will populate the quickfix list with all of the matches (possibly more than one per file), so you can use things like :copen, :cw, :cn etc to navigate (see :help quickfix)


    Use vim's built-in cleverness

    Use findstr to give you a list of files and then get vim to open those files:

    findstr /m background *.vim > list_of_files.txt
    gvim list_of_files.txt
    
    " In Gvim, read each file into the buffer list:
    :g/^/exe 'badd' getline('.')
    
    " Open the files in tabs:
    :bufdo tabedit %
    

    This will load each file, but will keep the list of files open as well (you can always bunload it or whatever).

    Edit:

    Using :tabedit on a list of files didn't work (I'd only tested :badd). You can get round this by either using badd and then bufdo (as above) or by doing something like this (put it in your vimrc):

    command! -range=% OpenListedFiles <line1>,<line2>call OpenListedFiles()
    
    function! OpenListedFiles() range
        let FileList = getline(a:firstline, a:lastline)
        for filename in FileList
            if filereadable(filename)
                exe 'tabedit' filename
            endif
        endfor
    endfunction
    

    Then simply open the file containing all of your required file names and type:

    :OpenListedFiles
    

    Use Vim's server functionality and some awful batch scripting

    Use the server functionality and some batch script magic (which I don't understand as I use bash)

    @echo off
    REM Welcome to the hideous world of Windows batch scripts
    findstr /m background *.vim > list_of_files.txt
    REM Run GVIM (may not be required)
    gvim
    REM Still in command prompt or .bat file here
    REM for each line in the file "list_of_files.txt", pass the line to OpenInTab
    for /f %%i in (list_of_files.txt) do call:OpenInTab %%i
    goto:eof
    
    :OpenInTab
    REM Open the file in a separate tab of an existing vim instance
    gvim --remote-tab %~1
    goto:eof
    

    Eeeurrgh.


    If it were me, I would go with the "Use vim's built-in cleverness" option. Actually, that's not true: I'd use cygwin's bash script and just use bash, but if I HAD to do it with the native tools, I'd use the built-in cleverness approach.