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, that’s 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
<br/>
:com! -nargs=1 Qfdofile try | sil cfirst |
\ while 1 | exec &lt;q-args&gt; | sil cnf | endwhile |
\ catch /^Vim\%((\a\+)\)\=:E\%(553\|42\):/ |
\ endtry

It’s dead simple to use them. For example, you have a macro @q which makes some changes in a single line and you want 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

Qfdofile command is a bit different to Qfdo - it applies your command not every line but to every file found by :vim search.

Leave a Reply