Processing results of vimgrep in vim

What I’ve been really missing in vim is a general mechanism of applying any arbitrary processing to the results of :vim[grep] command.

What I usually did was to record a macro and apply it manually(using :cp) to every entry in a quickfix window. Believe me, this is very boring.

Big thanks goes to Ben Schmidt who showed me a couple of vim script commands(in the official vim mailing list) which make it possible to automate this dull process. Here they are(put them into your ~/.vimrc):

:com! -nargs=1 Qfdo try | sil cfirst |
\ while 1 | exec <q-args> | sil cn | endwhile |
\ catch /^Vim\%((\a\+)\)\=:E\%(553\|42\):/ |
\ endtry
 
:com! -nargs=1 Qfdofile try | sil cfirst |
\ while 1 | exec <q-args> | sil cnf | endwhile |
\ catch /^Vim\%((\a\+)\)\=:E\%(553\|42\):/ |
\ endtry

Qfdo applies an arbitrary command to every line found by :vim search
Qfdofile is a bit different, it applies an arbitrary command to every file found by :vim search.

It’s really simple to use them. For example, you have a macro @q which does something useful and you would like to apply it to every line found by :vim command. Here’s a possible sequence of vim commands:

"search for foo string in all .cpp sources recursively
:vim /foo/ **/*.cpp     
"apply q macro to all found lines
:Qfdo normal @q

2 Responses to “Processing results of vimgrep in vim”

  1. ornicar Says:

    Thank you so much for this, it makes my day.

    There are some encoding issues in the commands above:

    <q-args>

    and

  2. pachanga Says:

    Fixed, thanks.

Leave a Reply