Filtering through vimgrep results using regular expressions

Here's a neat trick you can do with vimgrep / ack.vim to filter through results using regular expressions. This is super useful when doing a refactoring. Let me show an example of how I used this trick recently.

I wanted to rename todoist.users to todoist.apps.sessions, since it was a more appropriate name. Here's how I made sure that all the imports got updated:

1. Search for all occurrences of users in Python files, :vimgrep "users" **/*.py":

vimgrep filtering 1

2. Show all results in a quick list window by typing :cope in command mode:

vimgrep filtering 2

3. Copy the results of the quick list window into a new buffer. By for example typing gg => V => G => y => :ene => p

4. Delete all lines that have models in them (as we want to ignore todoist.models.users). You do this by typing :g/models/d.

5. Delete all lines that don't have import in them (we want only to focus on import lines). You do this by typing :g!/import/d

After this step I only see results that are relevant for my refactoring.

A bonus for you vimrc

Add this to your .vimrc to quickly transform your quicklist into a new buffer that's syntax highlighted:

map <leader>cc :botright cope<cr>
map <leader>co ggVGy:tabnew<cr>:set syntax=qf<cr>pgg

Anytime you press leader + co in a quicklist window it will isolate the quicklist in a new tab and syntax highlight it.

22. Dec 2011 Code improvement · Code rewrite · Tips · VIM Editor
© Amir Salihefendic