Skip to content

Instantly share code, notes, and snippets.

@jeetsukumaran
Created July 18, 2012 17:42
Show Gist options
  • Save jeetsukumaran/3137674 to your computer and use it in GitHub Desktop.
Save jeetsukumaran/3137674 to your computer and use it in GitHub Desktop.
Report the class name and method or function name of current location in a Python buffer open in Vim
" based on:
" http://vim.1045645.n5.nabble.com/editing-Python-files-how-to-keep-track-of-class-membership-td1189290.html
function! s:get_last_python_class()
let l:retval = ""
let l:last_line_declaring_a_class = search('^\s*class', 'bnW')
let l:last_line_starting_with_a_word_other_than_class = search('^\ \(\<\)\@=\(class\)\@!', 'bnW')
if l:last_line_starting_with_a_word_other_than_class < l:last_line_declaring_a_class
let l:nameline = getline(l:last_line_declaring_a_class)
let l:classend = matchend(l:nameline, '\s*class\s\+')
let l:classnameend = matchend(l:nameline, '\s*class\s\+[A-Za-z0-9_]\+')
let l:retval = strpart(l:nameline, l:classend, l:classnameend-l:classend)
endif
return l:retval
endfunction
function! s:get_last_python_def()
let l:retval = ""
let l:last_line_declaring_a_def = search('^\s*def', 'bnW')
let l:last_line_starting_with_a_word_other_than_def = search('^\ \(\<\)\@=\(def\)\@!', 'bnW')
if l:last_line_starting_with_a_word_other_than_def < l:last_line_declaring_a_def
let l:nameline = getline(l:last_line_declaring_a_def)
let l:defend = matchend(l:nameline, '\s*def\s\+')
let l:defnameend = matchend(l:nameline, '\s*def\s\+[A-Za-z0-9_]\+')
let l:retval = strpart(l:nameline, l:defend, l:defnameend-l:defend)
endif
return l:retval
endfunction
function! s:compose_python_location()
let l:pyloc = s:get_last_python_class()
if !empty(pyloc)
let pyloc = pyloc . "."
endif
let pyloc = pyloc . s:get_last_python_def()
return pyloc
endfunction
function! <SID>EchoPythonLocation()
echo s:compose_python_location()
endfunction
command! PythonLocation :call <SID>EchoPythonLocation()
nnoremap <Leader>? :PythonLocation<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment