public
Last active

Count method/property usage in vim

  • Download Gist
gistfile1.vim
VimL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
"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):
" 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
v/\<self\.\w\+/d
"count occurrences and sort from most popular to least
%sort
%!uniq -c
%sort n!

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.*.

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 _
endfunction

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.