Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Count method/property usage in vim
"Copy all matches to a vim search and paste in new buffer separated by lines
"Source this file to try it out.
"Let's say you have a python file and want to find all the methods/properties
"on self mentioned in a file (commence esoteric example):
"class Student(object):
" def __init__(self, name):
" = name
" def set_gpa(self, gpa):
" self.gpa = gpa
" def is_good_student(self):
" return self.gpa and self.gpa > 3
"clear 'a' register
let @a=""
"copy matching lines to a
g/\<self\.\w\+/y A
"(paste in new buffer)
vnew | norm "ap
"we have matching lines. if we want leading/trailing chars,
"the best solution I have is:
"add newline before and after the pattern
%s/\ze\<self\.\w\+/\r/g | %s/self\.\w\+\zs/\r/g
"delete lines not matching pattern
"count occurrences and sort from most popular to least
%!uniq -c
%sort n!

mattboehm commented Dec 7, 2012

I'm wondering if there's a better way to to trim non-matching characters than my hack above. I'd probably want to adapt this to be a function or command that uses your last search instead of self.*.

idbrii commented Dec 7, 2012

You could try something like this to remove everything that doesn't match a query from the current buffer.

" Remove all text except what matches the current search result
" The opposite of :%s///g (which clears all instances of the current search.
" Note: Clobbers the c register
function! ClearAllButMatches()
    let @c=""
    %s//\=setreg('C', submatch(0), 'l')/g
    %d _
    put c
    0d _
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment