Reputation: 38450
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?
Upvotes: 0
Views: 109
Reputation: 19554
PriorMethodDefinition
returns the name of the first method definition above the cursor.
It does this by search
ing backwards for a line containing the text 'def'. The search function returns the line number and getline
is 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:
:help search
:help getline
:help matchlist
Edit: you can also read about the regular expression pattern
:help pattern
But I found it a little confusing at first, so allow me to explain it a little. Here's the expression used:
'def \(\w\+\).*'
This will search for any text matching the following pattern: "the text def
followed 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 matchlist
function 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]
.
Upvotes: 1