1
0
mirror of https://github.com/gryf/pythonhelper.git synced 2025-12-19 04:20:20 +01:00

Bugfix and move plugin to python specific ftplugin

Move to python specific plugin (ftplugin),
Fixed bug regarding empty buffer.
This commit is contained in:
2016-05-25 08:27:36 +02:00
parent 81a638762b
commit c41a450990
4 changed files with 23 additions and 3 deletions

View File

@@ -0,0 +1,214 @@
"""
Simple analyzer for python source files. Collect and give info about file
structure: classes, its methods and functions.
version: 0.2
date: 2016-05-21
author: Roman Dobosz <gryf@vimja.com>
TODO: - fix the corner case with applying a tag, where it shouldn't do. like:
1 def foo():
2 pass
3
4 if True == False:
5 foo()
where line 5 is reporting as a function foo() body, which is not true.
"""
from collections import OrderedDict
import re
import vim
RE_TAG_TYPE = re.compile(r'\s*(def|class)[ \t]+([^(:]+).*')
RE_INDENT = re.compile(r'([ \t]*).*')
class PythonTag(object):
"""A simple storage class representing a python tag."""
def __init__(self, tag_type='', full_name='', line_number=0,
indent_level=0):
"""Initializes instances of Python tags.
:param tag_type: Tag type as string
:param full_name: Full tag name (in dotted notation)
:param line_number: line number on which the tag starts
:param indent_level: indentation level of the tag (number)
"""
self.tag_type = tag_type
self.name = full_name.split(".")[-1]
self.full_name = full_name
self.line_number = line_number
self.indent_level = indent_level
def __str__(self):
"""Returns a string representation of the tag."""
return "%0.2d [%d] %s %s" % (self.line_number,
self.indent_level,
self.tag_type,
self.full_name)
__repr__ = __str__
class EvenSimplerPythonTagsParser(object):
"""Simplified version for Python source code tag parser."""
def get_tags(self):
"""Return OrderedDict with all tags for current buffer"""
tags_stack = []
tags = OrderedDict()
for line_no, line in enumerate(vim.current.buffer):
tag_match = RE_TAG_TYPE.match(line)
if not tag_match:
continue
indent_level = self._get_indent_level(line)
for _ in range(len(tags_stack)):
if tags_stack and tags_stack[-1].indent_level >= indent_level:
tags_stack.pop()
if not tags_stack:
break
tag = PythonTag(tag_match.group(1),
self._get_full_name(tags_stack,
tag_match.group(2)),
line_no,
indent_level)
tag.tag_type = self._get_tag_type(tag, tags_stack)
tags[line_no] = tag
tags_stack.append(tag)
return tags
def _get_tag_type(self, tag, tags_stack):
"""Return proper type of the tag depending on context"""
if tag.tag_type == 'class':
return 'class'
if tags_stack and tags_stack[-1].tag_type == 'class':
return 'method'
return 'function'
def _get_full_name(self, tags_stack, name):
"""Return full logical name dot separated starting from upper entity"""
if tags_stack:
return tags_stack[-1].full_name + "." + name
return name
def _get_indent_level(self, line):
"""Return indentation level as a simple count of whitespaces"""
return len(RE_INDENT.match(line).group(1))
class PythonHelper(object):
TAGS = {}
@classmethod
def find_tag(cls, buffer_number, changed_tick):
"""
Tries to find the best tag for the current cursor position.
Parameters
buffer_number -- number of the current buffer
changed_tick -- always-increasing number used to indicate that the
buffer has been modified since the last time
"""
tag = PythonHelper._get_tag(buffer_number, changed_tick)
update_vim_vars(tag)
@classmethod
def _get_tag(cls, buffer_number, changed_tick):
"""Return the nearset tag object or None"""
if PythonHelper.TAGS.get(buffer_number) and \
PythonHelper.TAGS[buffer_number]['changed_tick'] == changed_tick:
tags = PythonHelper.TAGS[buffer_number]['tags']
else:
parser = EvenSimplerPythonTagsParser()
tags = parser.get_tags()
PythonHelper.TAGS['buffer_number'] = {'changed_tick': changed_tick,
'tags': tags}
# get line number of current cursor position from Vim's internal data.
# It is always a positive number, starts from 1. Let's decrease it by
# one, so that it will not confuse us while operating vim interface by
# python, where everything starts from 0.
line_number = vim.current.window.cursor[0] - 1
while True:
try:
line = vim.current.buffer[line_number]
except IndexError:
return None
line_indent = len(RE_INDENT.match(line).group(1))
if line.strip():
break
# line contains nothing but white characters, looking up to grab
# some more context
line_number -= 1
tag = tags.get(line_number)
# if we have something at the beginning of the line, just return it;
# it doesn't matter if it is the tag found there or not
if line_indent == 0 or tag:
return tag
# get nearest tag
for line_no in range(line_number - 1, 0, -1):
tag = tags.get(line_no)
line = vim.current.buffer[line_no]
upper_line_indent = len(RE_INDENT.match(line).group(1))
if tag and upper_line_indent < line_indent:
return tag
if not line.strip():
continue
if upper_line_indent == 0:
return None
if upper_line_indent >= line_indent:
continue
if tag and tag.indent_level >= line_indent:
tag = None
continue
return tag
@classmethod
def delete_tags(cls, buffer_number):
"""Removes tag data for the specified buffer number."""
del PythonHelper.TAGS[buffer_number]
def update_vim_vars(tag):
"""Update Vim variable usable with vimscript side of the plugin"""
if not tag:
vim.command('let w:PHStatusLine=""')
vim.command('let w:PHStatusLineTag=""')
vim.command('let w:PHStatusLineType=""')
else:
vim.command('let w:PHStatusLine="%s (%s)"' % (tag.full_name,
tag.tag_type))
vim.command('let w:PHStatusLineTag="%s"' % tag.tag_type)
vim.command('let w:PHStatusLineType="%s"' % tag.full_name)

View File

@@ -0,0 +1,169 @@
" File: pythonhelper.vim
" Author: Michal Vitecek <fuf-at-mageo-dot-cz>
" Author: Roman Dobosz <gryf@vimja.com>
" Version: 0.85
" Last Modified: 2016-05-24
"
" Overview
" --------
" This Vim script helps you find yourself in larger Python source files. It
" displays the current Python class, method or function the cursor is placed
" on in the status line. It's smarter than Yegappan Lakshmanan's taglist.vim
" because it takes indentation and comments into account in order to determine
" what identifier the cursor is placed on.
"
" Requirements
" ------------
" This script needs only VIM compiled with the Python interpreter. It doesn't
" rely on the exuberant ctags utilities. You can determine whether your VIM
" has Python support by issuing command :ver and looking for +python or
" +python3 in the list of features.
"
" Installation
" ------------
" 1. Make sure your Vim has the Python feature enabled (+python). If not, you
" will need to recompile it with the --with-pythoninterp option passed to
" the configure script
" 2. Copy the pythonhelper.vim script to the $HOME/.vim/plugin directory, or
" install it in some other way (vim-addon-manager, pathogen, ...)
" 3. Add '%{TagInStatusLine()}' to the statusline in your vimrc. You can also
" use %{TagInStatusLineTag()} or %{TagInStatusLineType()} for just the tag
" name or tag type respectively.
" 4. Run Vim and open any Python file.
" VIM functions {{{
let g:pythonhelper_python = 'python'
let s:plugin_path = expand('<sfile>:p:h', 1)
function! s:PHLoader()
if !exists('g:pythonhelper_py_loaded')
if has('python')
exe 'pyfile ' . s:plugin_path . '/pythonhelper.py'
elseif has('python3')
let g:pythonhelper_python = 'python3'
exe 'py3file ' . s:plugin_path . '/pythonhelper.py'
else
echohl WarningMsg|echomsg
\ "PythonHelper unavailable: "
\ "requires Vim with Python support"|echohl None
finish
endif
let g:pythonhelper_py_loaded = 1
else
echohl "already loaded"
endif
endfunction
function! PHCursorHold()
" only Python is supported {{{
if (!exists('b:current_syntax') || (b:current_syntax != 'python'))
let w:PHStatusLine = ''
let w:PHStatusLineTag = ''
let w:PHStatusLineType = ''
return
endif
" }}}
" call Python function findTag() with the current buffer number and change
" status indicator
execute g:pythonhelper_python . ' PythonHelper.find_tag(' . expand("<abuf>") .
\ ', ' . b:changedtick . ')'
endfunction
function! PHBufferDelete()
" set the PHStatusLine etc for this window to an empty string
let w:PHStatusLine = ""
let w:PHStatusLineTag = ''
let w:PHStatusLineType = ''
" call Python function deleteTags() with the current buffer number and
" change status indicator
execute g:pythonhelper_python . ' PythonHelper.delete_tags(' . expand("<abuf>") . ')'
endfunction
function! TagInStatusLine()
" return value of w:PHStatusLine in case it's set
if (exists("w:PHStatusLine"))
return w:PHStatusLine
" otherwise just return an empty string
else
return ""
endif
endfunction
function! TagInStatusLineTag()
" return value of w:PHStatusLineTag in case it's set
if (exists("w:PHStatusLineTag"))
return w:PHStatusLineTag
" otherwise just return an empty string
else
return ""
endif
endfunction
function! TagInStatusLineType()
" return value of w:PHStatusLineType in case it's set
if (exists("w:PHStatusLineType"))
return w:PHStatusLineType
" otherwise just return an empty string
else
return ""
endif
endfunction
function! PHPreviousClassMethod()
call search('^[ \t]*\(class\|def\)\>', 'bw')
endfunction
function! PHNextClassMethod()
call search('^[ \t]*\(class\|def\)\>', 'w')
endfunction
function! PHPreviousClass()
call search('^[ \t]*class\>', 'bw')
endfunction
function! PHNextClass()
call search('^[ \t]*class\>', 'w')
endfunction
function! PHPreviousMethod()
call search('^[ \t]*def\>', 'bw')
endfunction
function! PHNextMethod()
call search('^[ \t]*def\>', 'w')
endfunction
" }}}
" event binding, Vim customization {{{
" load Python code
call s:PHLoader()
" autocommands
autocmd CursorHold * call PHCursorHold()
autocmd CursorHoldI * call PHCursorHold()
autocmd BufDelete * silent call PHBufferDelete()
" period of no activity after which the CursorHold event is triggered
if (exists("g:pythonhelper_updatetime"))
let &updatetime = g:pythonhelper_updatetime
endif
" }}}
" vim:foldmethod=marker

View File

@@ -0,0 +1,42 @@
import os
class Foo(object):
"""Some doc"""
CLASS_ATTR = {"dict": 1,
"bla": "foobar"}
def __init__(self, arg):
"""initializaion"""
self.arg = arg
def method(self, x, y):
"""very important method"""
def inner_funtion(x, y):
for i in y:
x = x + i
result = y[:]
result.append(x)
return result
result = None
result2 = """\
multiline
string
the
annoying
bastard"""
if self.arg < 100:
result = inner_funtion(x, y)
return result if result else result2
def main():
instance = Foo(10)
print(os.path.curdir, instance.method(2, [1, 2, 3]))
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,146 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
class Command(object):
def __call__(self, args):
print(args)
class Window(object):
def __init__(self):
self.cursor = (1, 1)
class Current(object):
def __init__(self):
self.buffer = []
self.window = Window()
class MockVim(object):
current = Current()
command = Command()
with open('test_py_example.py') as fobj:
BUFFER = fobj.read().split('\n')
sys.modules['vim'] = vim = MockVim
import pythonhelper
class TestTagsHelperWithEmptyBuffer(unittest.TestCase):
def setUp(self):
vim.current.buffer = []
def test_get_tag(self):
vim.current.window.cursor = (1, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 2)
self.assertIsNone(tag)
class TestTagsHelper(unittest.TestCase):
def setUp(self):
vim.current.buffer = BUFFER
def test_import(self):
vim.current.window.cursor = (1, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 2)
self.assertIsNone(tag)
def test_class(self):
vim.current.window.cursor = (4, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'class')
vim.current.window.cursor = (6, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'class')
vim.current.window.cursor = (7, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'class')
def test_init(self):
vim.current.window.cursor = (9, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'method')
vim.current.window.cursor = (11, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'method')
def test_method(self):
vim.current.window.cursor = (13, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'method')
vim.current.window.cursor = (15, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'method')
vim.current.window.cursor = (24, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'method')
# those tests should run if we have some kind of lexer analiser, not a
# simple py source parser.
#
# vim.current.window.cursor = (32, 1)
# tag = pythonhelper.PythonHelper._get_tag(1, 3)
# self.assertEqual(tag.tag_type, 'method')
# vim.current.window.cursor = (34, 1)
# tag = pythonhelper.PythonHelper._get_tag(1, 3)
# self.assertEqual(tag.tag_type, 'method')
def test_inner_function(self):
vim.current.window.cursor = (16, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'function')
vim.current.window.cursor = (18, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'function')
vim.current.window.cursor = (22, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'function')
vim.current.window.cursor = (23, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'function')
def test_main(self):
vim.current.window.cursor = (37, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'function')
vim.current.window.cursor = (38, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'function')
vim.current.window.cursor = (40, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertEqual(tag.tag_type, 'function')
def test_ifmain(self):
vim.current.window.cursor = (41, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertIsNone(tag)
vim.current.window.cursor = (42, 1)
tag = pythonhelper.PythonHelper._get_tag(1, 3)
self.assertIsNone(tag)
if __name__ == "__main__":
unittest.main()