def test_get_pydoc_for_functions(self): src = 'def a_func():\n' \ ' """a function"""\n' \ ' a_var = 10\n' \ 'a_func()' self.assertTrue(get_doc(self.project, src, len(src) - 4). endswith('a function')) get_doc(self.project, src, len(src) - 4).index('a_func()')
def run(self, edit): view = self.view row, col = view.rowcol(view.sel()[0].a) offset = view.text_point(row, col) if view.substr(offset) in [u'(', u')']: offset = view.text_point(row, col - 1) with ropemate.context_for(view) as context: try: doc = codeassist.get_doc(context.project, context.input, offset, context.resource, maxfixes=3) if not doc: raise rope.base.exceptions.BadIdentifierError self.output(doc) except rope.base.exceptions.BadIdentifierError: word = self.view.substr(self.view.word(offset)) self.view.set_status("rope_documentation_error", "No documentation found for %s" % word) def clear_status_callback(): self.view.erase_status("rope_documentation_error") sublime.set_timeout(clear_status_callback, 5000)
def run(self): try: doc = codeassist.get_doc(self.ropeProject, self.source, self.hoverOffset) self.docAvailable.emit(doc, self.hoverOffset) except: pass
def show_calltips(self): project = self.project_manager.project project.validate() current_resource = self.get_rope_resource(project) from rope.contrib import codeassist from snaked.util.pairs_parser import get_brackets source, offset = self.get_source_and_offset() # make foo.bar.baz( equivalent to foo.bar.baz if source[offset-1] in '(.': offset -= 1 brackets = get_brackets(source, offset) if brackets: br, spos, epos = brackets if br == '(': offset = spos - 1 try: doc = codeassist.get_doc(project, source, offset, resource=current_resource, maxfixes=3) except Exception, e: import traceback traceback.print_exc() self.editor.message(str(e), 5000) return
def get_calltip(self): calltip = codeassist.get_doc(self.project, self.source_code, self.code_point, resource=self.resource, maxfixes=10) return calltip
def test_get_pydoc_for_methods_should_include_class_name(self): src = 'class AClass(object):\n' \ ' def a_method(self):\n'\ ' """hey"""\n' \ ' pass\n' doc = get_doc(self.project, src, src.index('a_method') + 1) doc.index('AClass.a_method') doc.index('hey')
def documentation(self, source, project_path, file_path, loc): project, file_path = self.project_for(project_path, file_path, source) resource = libutils.path_to_resource(project, file_path) try: doc = get_doc(project, source, loc, resource=resource, maxfixes=3) except ModuleSyntaxError: doc = None return doc
def test_get_doc_on_relative_imports(self): pkg = testutils.create_package(self.project, 'pkg') mod1 = testutils.create_module(self.project, 'mod1', pkg) mod2 = testutils.create_module(self.project, 'mod2', pkg) mod1.write('def a_func():\n """hey"""\n pass\n') code = 'import mod1\nmod1.a_func\n' result = get_doc(self.project, code, len(code) - 2, mod2) self.assertTrue(result.endswith('hey'))
def my_get_doc(self, prefix, candidate): maxfixes = self.env.get('codeassist_maxfixes') text = self._get_text() offset = self.env.get_offset() text=text[:offset]+candidate[len(prefix):]+text[offset:] offset += len(candidate) - len(prefix) docs = codeassist.get_doc(self.project, text, offset, self.resource, maxfixes) return docs ##or 'no docfor %s text=%s, offset=%s' % (prefix, text, offset)
def getDoc(self, offset=None): if offset is None: offset = self.getOffset() project = self.getProject() try: doc = codeassist.get_doc(project, self.editorTabWidget.getSource(), offset) return doc except Exception as err: return None
def test_get_pydoc_for_methods_should_include_methods_from_super_classes(self): src = 'class A(object):\n def a_method(self):\n' \ ' """hey1"""\n pass\n' \ 'class B(A):\n def a_method(self):\n' \ ' """hey2"""\n pass\n' doc = get_doc(self.project, src, src.rindex('a_method') + 1) doc.index('A.a_method') doc.index('hey1') doc.index('B.a_method') doc.index('hey2')
def TooltipRequest(self, request, response): """ Finds and returns a tooltip for the given location in the given source file. """ project, resource, source, offset = self._Context(request.context) docstring = codeassist.get_doc(project, source, offset, maxfixes=self.MAXFIXES, resource=resource) if docstring is not None: response.rich_text = docstring
def show_doc(): """ Show documentation. """ with RopeContext() as ctx: source, offset = env.get_offset_params() try: doc = codeassist.get_doc( ctx.project, source, offset, ctx.resource, maxfixes=3) if not doc: raise exceptions.BadIdentifierError env.let('l:output', doc.split('\n')) except exceptions.BadIdentifierError: env.error("No documentation found.")
def get_documentation(self,name): sourceCopyStart = self.source[:self.starting_offset] sourceCopyEnd = self.source[min(len(self.source)-1,self.offset+1):] sourceCopy = sourceCopyStart + name + sourceCopyEnd maxfixes = self.env.get('codeassist_maxfixes') offset = self.starting_offset + len(name) res = self.interface._get_resource() docs = codeassist.get_doc(self.interface.project, sourceCopy, offset, res, maxfixes) return docs
def show_doc(): """ Show documentation. """ with RopeContext() as ctx: source, offset = get_assist_params() try: doc = codeassist.get_doc( ctx.project, source, offset, ctx.resource, maxfixes=3) if not doc: raise exceptions.BadIdentifierError vim.command('let l:output = %s' % json.dumps(doc.split('\n'))) except exceptions.BadIdentifierError: pymode_error("No documentation found.")
def test_get_pydoc_for_meths_should_inc_methods_from_super_classes(self): src = 'class A(object):\n' \ ' def a_method(self):\n' \ ' """hey1"""\n' \ ' pass\n' \ 'class B(A):\n' \ ' def a_method(self):\n' \ ' """hey2"""\n' \ ' pass\n' doc = get_doc(self.project, src, src.rindex('a_method') + 1) doc.index('A.a_method') doc.index('hey1') doc.index('B.a_method') doc.index('hey2')
def documentation(self, source, project_path, file_path, loc): """ Search for documentation about the word in the current location :param source: the document source :param project_path: the actual project_path :param file_path: the actual file path :param loc: the buffer location :returns: a string containing the documentation """ project, resource = self._get_resource(project_path, file_path, source) try: doc = get_doc(project, source, loc, resource=resource, maxfixes=3) except ModuleSyntaxError: doc = None return doc
def run(self, edit): view = self.view row, col = view.rowcol(view.sel()[0].a) offset = view.text_point(row, col) with ropemate.ropecontext(view) as context: try: doc = codeassist.get_doc( context.project, context.input, offset, context.resource) if not doc: raise rope.base.exceptions.BadIdentifierError self.output(doc) except rope.base.exceptions.BadIdentifierError: word = self.view.substr(self.view.word(offset)) self.view.set_status( "rope_documentation_error", "No documentation found for %s" % word) def clear_status_callback(): self.view.erase_status("rope_documentation_error") sublime.set_timeout(clear_status_callback, 5000)
def test_get_pydoc_for_builtins(self): src = 'print(object)\n' self.assertTrue( get_doc(self.project, src, src.index('obj')) is not None)
def test_get_pydoc_for_classes_with_init(self): src = 'class AClass(object):\n def __init__(self):\n pass\n' get_doc(self.project, src, src.index('AClass') + 1).index('AClass')
def test_get_pydoc_for_modules(self): mod = testutils.create_module(self.project, 'mod') mod.write('"""a module"""\n') src = 'import mod\nmod' self.assertEquals('a module', get_doc(self.project, src, len(src) - 1))
def test_get_pydoc_for_builtins(self): src = 'print(object)\n' self.assertTrue(get_doc(self.project, src, src.index('obj')) is not None)
def test_get_pydoc_utf8_bytestring(self): src = u'# coding: utf-8\ndef foo():\n "байтстринг"' doc = get_doc(self.project, src, src.index('foo') + 1) self.assertTrue(isinstance(doc, unicode)) self.assertTrue(u'байтстринг' in doc)
def test_get_pydoc_for_classes_should_name_super_classes(self): src = 'class A(object):\n pass\n' \ 'class B(A):\n pass\n' doc = get_doc(self.project, src, src.rindex('B') + 1) doc.index('B(A)')
def test_commenting_errors_before_offset(self): src = 'lsjd lsjdf\ns = "hey"\ns.replace()\n' doc = get_doc(self.project, src, src.rindex('replace') + 1) # noqa
def test_get_doc_on_from_import_module(self): mod1 = testutils.create_module(self.project, 'mod1') mod1.write('"""mod1 docs"""\nvar = 1\n') code = 'from mod1 import var\n' result = get_doc(self.project, code, code.index('mod1')) result.index('mod1 docs')
def test_commenting_errors_before_offset(self): src = 'lsjd lsjdf\ns = "hey"\ns.replace()\n' doc = get_doc(self.project, src, src.rindex('replace') + 1)
def getCalltipAndDoc(fileName, editor, position=None, tryQt=False): " Provides a calltip and docstring " try: GlobalData().validateRopeProject() ropeProject = GlobalData().getRopeProject(fileName) if position is None: position = editor.currentPosition() text = editor.text() calltip = None docstring = None resource = None if os.path.isabs(fileName): resource = path_to_resource(ropeProject, fileName) calltip = get_calltip(ropeProject, text, position, resource, ignore_unknown=False, remove_self=True, maxfixes=7) if calltip is not None: calltip = calltip.strip() while '..' in calltip: calltip = calltip.replace('..', '.') if '(.)' in calltip: calltip = calltip.replace('(.)', '(...)') calltip = calltip.replace('.__init__', '') try: docstring = get_doc(ropeProject, text, position, resource, maxfixes=7) except: pass if not calltip: calltip = None if tryQt and calltip is not None and docstring is not None: # try to extract signatures from the QT docstring try: if calltip.startswith('QtCore.') or calltip.startswith( 'QtGui.'): parenPos = calltip.index("(") dotPos = calltip.rindex(".", 0, parenPos) pattern = calltip[dotPos:parenPos + 1] signatures = [] for line in docstring.splitlines(): line = line.strip() if pattern in line and not line.endswith(':'): signatures.append(line) if signatures: calltip = '\n'.join(signatures) except: pass if calltip: # Sometimes rope makes a mistake and provides a calltip for the # wrong function. Check the name here. line, index = editor.lineIndexFromPosition(position) word = str(editor.getWord(line, index)) if word and not (word.startswith('__') and word.endswith('__')): fullName = calltip.split('(', 1)[0].strip() lastPart = fullName.split('.')[-1] if lastPart != word: # Wrong calltip # print "Wrong calltip. Asked: '" + word + "' received: '" + lastPart + "'" # print calltip return None, None return calltip, docstring except: return None, None
def test_get_pydoc_for_builtin_functions(self): src = 's = "hey"\ns.replace\n' doc = get_doc(self.project, src, src.rindex('replace') + 1) self.assertTrue(doc is not None)
option = option_arg; projectpath = project_arg if projectpath.startswith("file://"): projectpath = projectpath.replace("file://", "") proj = Project(projectpath) proj.pycore._init_python_files() input = open(source_code_arg, 'r') source_code = input.read() respath = relpath(projectpath, res_arg) res = proj.get_resource(respath) position = int(offset_arg) try: if option == "autocomplete": proposals = codeassist.code_assist(proj, source_code, position, resource=res, maxfixes=10) proposals = codeassist.sorted_proposals(proposals) for proposal in proposals: print proposal elif option == "calltip": proposals = codeassist.get_doc(proj, source_code, position, resource=res, maxfixes=10) print proposals except: pass proj.close()
def test_get_pydoc_unicode(self): src = u'# coding: utf-8\ndef foo():\n u"юникод-объект"' doc = get_doc(self.project, src, src.index('foo') + 1) self.assertTrue(isinstance(doc, unicode)) self.assertTrue(u'юникод-объект' in doc)
def getCalltipAndDoc( fileName, editor, position = None, tryQt = False ): " Provides a calltip and docstring " try: GlobalData().validateRopeProject() ropeProject = GlobalData().getRopeProject( fileName ) if position is None: position = editor.currentPosition() text = editor.text() calltip = None docstring = None resource = None if os.path.isabs( fileName ): resource = path_to_resource( ropeProject, fileName ) calltip = get_calltip( ropeProject, text, position, resource, ignore_unknown = False, remove_self = True, maxfixes = 7 ) if calltip is not None: calltip = calltip.strip() while '..' in calltip: calltip = calltip.replace( '..', '.' ) if '(.)' in calltip: calltip = calltip.replace( '(.)', '(...)' ) calltip = calltip.replace( '.__init__', '' ) try: docstring = get_doc( ropeProject, text, position, resource, maxfixes = 7 ) except: pass if not calltip: calltip = None if tryQt and calltip is not None and docstring is not None: # try to extract signatures from the QT docstring try: if calltip.startswith( 'QtCore.' ) or calltip.startswith( 'QtGui.' ): parenPos = calltip.index( "(" ) dotPos = calltip.rindex( ".", 0, parenPos ) pattern = calltip[ dotPos : parenPos + 1 ] signatures = [] for line in docstring.splitlines(): line = line.strip() if pattern in line and not line.endswith( ':' ): signatures.append( line ) if signatures: calltip = '\n'.join( signatures ) except: pass if calltip: # Sometimes rope makes a mistake and provides a calltip for the # wrong function. Check the name here. line, index = editor.lineIndexFromPosition( position ) word = str( editor.getWord( line, index ) ) if word and not (word.startswith( '__' ) and word.endswith( '__' )): fullName = calltip.split( '(', 1 )[ 0 ].strip() lastPart = fullName.split( '.' )[ -1 ] if lastPart != word: # Wrong calltip # print "Wrong calltip. Asked: '" + word + "' received: '" + lastPart + "'" # print calltip return None, None return calltip, docstring except: return None, None
def test_get_pydoc_for_modules(self): pycore = self.project.get_pycore() mod = testutils.create_module(self.project, 'mod') mod.write('"""a module"""\n') src = 'import mod\nmod' self.assertEquals('a module', get_doc(self.project, src, len(src) - 1))