Following code has been picked up from this blog
function! Privatize()
let priorMethod = PriorMethodDefinition()
exec "normal iprivate :" . priorMethod . "\<Esc>=="
endfunction
function! PriorMethodDefinition()
let lineNumber = search('def', 'bn')
let line = getline(lineNumber)
if line == 0
echo "No prior method definition found"
endif
return matchlist(line, 'def \(\w\+\).*')[1]
endfunction
map <Leader>p :call Privatize()<CR>
I tried but I fail to understand PriorMethodDefinition method. Can someone walk me through this code?
PriorMethodDefinitionreturns the name of the first method definition above the cursor.It does this by
searching backwards for a line containing the text ‘def’. The search function returns the line number andgetlineis used to retrieve the content of that line.The function checks that it has found a valid line, before using a regular expression to get the name of the method and return it.
You can read more about these functions if you’re curious about the specifics – see:
Edit: you can also read about the regular expression pattern
But I found it a little confusing at first, so allow me to explain it a little. Here’s the expression used:
This will search for any text matching the following pattern: “the text
deffollowed by one or more ‘word’ characters\w\+followed by zero or more characters.*“. The part matching the word characters is placed into a group (or atom), designated by the escaped parens\(&\). More info on the definitions of word characters etc can be found in the help link above.The
matchlistfunction returns a list of matches, the first[0]of which is the full text matching the regex, followed by submatches (ie our group). We are interested in the first such submatch, hence the[1].