开发者

vim codewalk through

开发者 https://www.devze.com 2023-01-28 23:30 出处:网络
Following code has been picked up from this blog function! Privatize() let priorMethod = PriorMethodDefinition()

Following code has been picked up from this blog

function! Privatize()
  let priorMethod = PriorMethodDefinition()
  exec "normal ipriv开发者_运维技巧ate :" . 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?


PriorMethodDefinition returns 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 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].

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号