Skip to content

Instantly share code, notes, and snippets.

@mattboehm
Created December 7, 2012 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattboehm/4234781 to your computer and use it in GitHub Desktop.
Save mattboehm/4234781 to your computer and use it in GitHub Desktop.
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):
" 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!
@mattboehm
Copy link
Author

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment