def _getRopeCompletion(fileName, text, editor, prefix): " Provides the rope library idea of how to complete " try: GlobalData().validateRopeProject() ropeProject = GlobalData().getRopeProject(fileName) position = editor.currentPosition() - len(prefix) if os.path.isabs(fileName): resource = path_to_resource(ropeProject, fileName) proposals = code_assist(ropeProject, text, position, resource, None, maxfixes=7) else: # The file does not exist proposals = code_assist(ropeProject, text, position, None, None, maxfixes=7) return proposals, True except: # Rope may throw exceptions e.g. in case of syntax errors return [], False
def autocomplete_pressed(self): try: items = code_assist(self.prj, unicode(self.toPlainText()), self.textCursor().position()) except Exception, e: items = []
def get_proporsals(source, offset, base='', dot=False): """ Code assist. :return str: """ with RopeContext() as ctx: # noqa try: proposals = codeassist.code_assist(ctx.project, source, offset, ctx.resource, maxfixes=3, later_locals=False) except exceptions.ModuleSyntaxError: proposals = [] proposals = sorted(proposals, key=_sort_proporsals) out = [] preview = 'preview' in ctx.options.get('completeopt') for p in proposals: out.append( dict( word=p.name, menu=p.type, kind=p.scope + ':', info=p.get_doc() or "No docs." if preview else "", )) out = _get_autoimport_proposals(out, ctx, source, offset, dot=dot) return out
def on_query_completions(self, view, prefix, locations): if not view.match_selector(locations[0], "source.python"): return [] with ropemate.context_for(view) as context: loc = locations[0] try: raw_proposals = codeassist.code_assist( context.project, context.input, loc, context.resource, maxfixes=3, later_locals=False) except ModuleSyntaxError: raw_proposals = [] if len(raw_proposals) <= 0 and self.use_simple_completion: # try the simple hackish completion line = view.substr(view.line(loc)) identifier = line[:view.rowcol(loc)[1]].strip(' .') if ' ' in identifier: identifier = identifier.split(' ')[-1] raw_proposals = self.simple_module_completion(view, identifier) proposals = codeassist.sorted_proposals(raw_proposals) proposals = [ (proposal_string(p), p.name) for p in proposals if p.name != 'self=' ] completion_flags = 0 if self.suppress_word_completions: completion_flags = sublime.INHIBIT_WORD_COMPLETIONS if self.suppress_explicit_completions: completion_flags |= sublime.INHIBIT_EXPLICIT_COMPLETIONS return (proposals, completion_flags)
def completions(self, source, project_path, file_path, loc): """ Get completions from the underlying Rope library and returns it back to the editor interface :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 list of tuples of strings """ project, resource = self._get_resource(project_path, file_path, source) try: proposals = code_assist( project, source, loc, resource=resource, maxfixes=3) proposals = sorted_proposals(proposals) except ModuleSyntaxError: proposals = [] except Exception: import traceback traceback.print_exc() proposals = [] finally: proposals = [ (self._proposal_string(p), self._insert_string(p)) for p in proposals if p.name != 'self=' ] return proposals
def completions(self, source, project_path, file_path, loc): """ Get completions from the underlying Rope library and returns it back to the editor interface :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 list of tuples of strings """ project, resource = self._get_resource(project_path, file_path, source) try: proposals = code_assist(project, source, loc, resource=resource, maxfixes=3) proposals = sorted_proposals(proposals) except ModuleSyntaxError: proposals = [] except Exception: import traceback traceback.print_exc() proposals = [] finally: proposals = [(self._proposal_string(p), self._insert_string(p)) for p in proposals if p.name != "self="] return proposals
def get_proporsals(source, offset, base='', dot=False): """ Code assist. :return str: """ with RopeContext() as ctx: try: proposals = codeassist.code_assist( ctx.project, source, offset, ctx.resource, maxfixes=3, later_locals=False) except exceptions.ModuleSyntaxError: proposals = [] proposals = sorted(proposals, key=_sort_proporsals) out = [] preview = 'preview' in ctx.options.get('completeopt') for p in proposals: out.append(dict( word=p.name, menu=p.type, kind=p.scope + ':', info=p.get_doc() or "No docs." if preview else "", )) out = _get_autoimport_proposals(out, ctx, source, offset, dot=dot) return out
def on_query_completions(self, view, prefix, locations): if not view.match_selector(locations[0], "source.python"): return [] with ropemate.RopeContext(view) as context: loc = locations[0] try: raw_proposals = codeassist.code_assist(context.project, context.input, loc, context.resource, maxfixes=3, later_locals=False) except ModuleSyntaxError: raw_proposals = [] if len(raw_proposals) <= 0: # try the simple hackish completion line = view.substr(view.line(loc)) identifier = line[:view.rowcol(loc)[1]].strip(' .') if ' ' in identifier: identifier = identifier.split(' ')[-1] raw_proposals = self.simple_module_completion(view, identifier) proposals = codeassist.sorted_proposals(raw_proposals) proposals = [(proposal_string(p), p.name) for p in proposals if p.name != 'self='] if self.suppress_default_completions: return (proposals, sublime.INHIBIT_EXPLICIT_COMPLETIONS | sublime.INHIBIT_WORD_COMPLETIONS) else: return proposals
def pylsp_completions(config, workspace, document, position): # pylint: disable=too-many-locals settings = config.plugin_settings('rope_completion', document_path=document.path) resolve_eagerly = settings.get('eager', False) # Rope is a bit rubbish at completing module imports, so we'll return None word = document.word_at_position({ # The -1 should really be trying to look at the previous word, but that might be quite expensive # So we only skip import completions when the cursor is one space after `import` 'line': position['line'], 'character': max(position['character'] - 1, 0), }) if word == 'import': return None offset = document.offset_at_position(position) rope_config = config.settings(document_path=document.path).get('rope', {}) rope_project = workspace._rope_project_builder(rope_config) document_rope = document._rope_resource(rope_config) try: definitions = code_assist(rope_project, document.source, offset, document_rope, maxfixes=3) except Exception as e: # pylint: disable=broad-except log.debug("Failed to run Rope code assist: %s", e) return [] definitions = sorted_proposals(definitions) new_definitions = [] for d in definitions: item = { 'label': d.name, 'kind': _kind(d), 'sortText': _sort_text(d), 'data': { 'doc_uri': document.uri } } if resolve_eagerly: item = _resolve_completion(item, d) new_definitions.append(item) # most recently retrieved completion items, used for resolution document.shared_data['LAST_ROPE_COMPLETIONS'] = { # label is the only required property; here it is assumed to be unique completion['label']: (completion, data) for completion, data in zip(new_definitions, definitions) } definitions = new_definitions return definitions or None
def autocomplete_pressed(self): try: items = code_assist(self.prj, unicode(self.toPlainText()), self.textCursor().position()) except Exception as e: items = [] if items: self.autocomplete.setItems(items) self.autocomplete.show()
def CompletionRequest(self, request, response): """ Finds completion proposals for the given location in the given source file. """ # Get information out of the request project, resource, source, offset = self._Context(request.context) # If the cursor is immediately after a comma or open paren, we should look # for a calltip first. word_finder = worder.Worder(source) non_space_offset = word_finder.code_finder._find_last_non_space_char( offset) if word_finder.code_finder.code[non_space_offset] in "(,": paren_start = word_finder.find_parens_start_from_inside(offset) # Get a calltip now calltip = codeassist.get_calltip(project, source, paren_start - 1, maxfixes=self.MAXFIXES, resource=resource, remove_self=True) if calltip is not None: response.insertion_position = paren_start + 1 response.calltip = calltip return # Do normal completion if a calltip couldn't be found proposals = codeassist.code_assist(project, source, offset, maxfixes=self.MAXFIXES, resource=resource) proposals = codeassist.sorted_proposals(proposals) # Get the position that this completion will start from. starting_offset = codeassist.starting_offset(source, offset) response.insertion_position = starting_offset # Construct the response protobuf for proposal in proposals: proposal_pb = response.proposal.add() proposal_pb.name = proposal.name docstring = proposal.get_doc() if proposal.type in self.PROPOSAL_TYPES: proposal_pb.type = self.PROPOSAL_TYPES[proposal.type] if proposal.scope in self.PROPOSAL_SCOPES: proposal_pb.scope = self.PROPOSAL_SCOPES[proposal.scope] if docstring is not None: proposal_pb.docstring = docstring
def pyls_completions(config, document, position, workspace): log.debug('Launching Rope...') # Rope is a bit rubbish at completing module imports, so we'll return None word = document.word_at_position({ # The -1 should really be trying to look at the previous word, but that might be quite expensive # So we only skip import completions when the cursor is one space after `import` 'line': position['line'], 'character': max(position['character'] - 1, 0), }) if word == 'import': return None offset = document.offset_at_position(position) rope_config = config.settings(document_path=document.path).get('rope', {}) rope_project = workspace._rope_project_builder(rope_config) # Rope resources can't be created for non-existing files try: rope_resource = document._rope_resource(rope_config) except Exception as e: # pylint: disable=broad-except log.error("Failed to create Rope resource: %s", e) rope_resource = None try: definitions = code_assist(rope_project, document.source, offset, rope_resource, maxfixes=3) except Exception as e: # pylint: disable=broad-except log.error("Failed to run Rope code assist: %s", e) return None definitions = sorted_proposals(definitions) new_definitions = [] for d in definitions: try: doc = d.get_doc() except AttributeError: doc = None new_definitions.append({ 'label': d.name, 'kind': _kind(d), 'detail': '{0} {1}'.format(d.scope or "", d.name), 'documentation': doc or "", 'sortText': _sort_text(d) }) definitions = new_definitions log.debug('Finish Rope!!!') return definitions or None
def _getRopeCompletion( fileName, text, editor, prefix ): " Provides the rope library idea of how to complete " try: GlobalData().validateRopeProject() ropeProject = GlobalData().getRopeProject( fileName ) position = editor.currentPosition() - len( prefix ) if os.path.isabs( fileName ): resource = path_to_resource( ropeProject, fileName ) proposals = code_assist( ropeProject, text, position, resource, None, maxfixes = 7 ) else: # The file does not exist proposals = code_assist( ropeProject, text, position, None, None, maxfixes = 7 ) return proposals, True except: # Rope may throw exceptions e.g. in case of syntax errors return [], False
def get_proposals(project, source, offset=None, **kwargs): head = 'from tests.djangotest.models import *\n' source = head + source if offset is None: offset = len(source) else: offset += len(head) return code_assist(project, source, offset, **kwargs)
def python_engine_get_completion_string(code, offset): from rope.contrib import codeassist proposals = codeassist.code_assist(pythonlab_rope_project, code, offset, maxfixes=20) # proposals = codeassist.sorted_proposals(proposals) proposals_string = [] for p in proposals: proposals_string.append(p.__str__()) return proposals_string
def update_proposals(self, update): source, offset = self.get_source_and_offset() try: proposals = codeassist.sorted_proposals( codeassist.code_assist(self.project, source, offset, resource=self.get_rope_resource(self.project))) except Exception, e: self.editor.update_message(str(e), "no", 1) traceback.print_exc() return False
def run(self, base, buffer, offset): from rope.contrib.codeassist import code_assist, sorted_proposals from rope.base.exceptions import RopeError try: mp = ModuleParser(self.document.filename, project=self.document.project) buffer = buffer + ('\n' * 20) co = code_assist(mp.project, buffer, offset, maxfixes=MAX_FIXES) except RopeError, IndentationError: return
def CompletionRequest(self, request, response): """ Finds completion proposals for the given location in the given source file. """ # Get information out of the request project, resource, source, offset = self._Context(request.context) # If the cursor is immediately after a comma or open paren, we should look # for a calltip first. word_finder = worder.Worder(source) non_space_offset = word_finder.code_finder._find_last_non_space_char(offset) if word_finder.code_finder.code[non_space_offset] in "(,": paren_start = word_finder.find_parens_start_from_inside(offset) # Get a calltip now calltip = codeassist.get_calltip(project, source, paren_start-1, maxfixes=self.MAXFIXES, resource=resource, remove_self=True) if calltip is not None: response.insertion_position = paren_start + 1 response.calltip = calltip return # Do normal completion if a calltip couldn't be found proposals = codeassist.code_assist(project, source, offset, maxfixes=self.MAXFIXES, resource=resource) proposals = codeassist.sorted_proposals(proposals) # Get the position that this completion will start from. starting_offset = codeassist.starting_offset(source, offset) response.insertion_position = starting_offset # Construct the response protobuf for proposal in proposals: proposal_pb = response.proposal.add() proposal_pb.name = proposal.name docstring = proposal.get_doc() if proposal.type in self.PROPOSAL_TYPES: proposal_pb.type = self.PROPOSAL_TYPES[proposal.type] if proposal.scope in self.PROPOSAL_SCOPES: proposal_pb.scope = self.PROPOSAL_SCOPES[proposal.scope] if docstring is not None: proposal_pb.docstring = docstring
def on_query_completions(self, view, prefix, locations): if ( not view.match_selector(locations[0], 'source.python') or not (self.complete_as_you_type) or SublimeRopeListener.user_requested ): return [] SublimeRopeListener.user_requested = False with ropemate.context_for(view) as context: loc = locations[0] try: raw_proposals = codeassist.code_assist( context.project, context.input, loc, context.resource, maxfixes=3, later_locals=False, case_sensitive=self.case_sensitive_completion ) except ModuleSyntaxError: raw_proposals = [] if not raw_proposals and self.use_simple_completion: # try the simple hackish completion line = view.substr(view.line(loc)) identifier = line[:view.rowcol(loc)[1]].strip(' .') if ' ' in identifier: identifier = identifier.split(' ')[-1] raw_proposals = self.simple_module_completion(view, identifier) # do not use rope's own sorting for large results, it is very slow! # simple sort-by-name is good enough if len(raw_proposals) <= 20: sorted_proposals = codeassist.sorted_proposals(raw_proposals) else: sorted_proposals = sorted(raw_proposals, key=lambda p: p.name) proposals = [ (self.proposal_string(p), self.insert_string(p)) for p in sorted_proposals if p.name != 'self=' ] completion_flags = 0 if self.suppress_word_completions: completion_flags = sublime.INHIBIT_WORD_COMPLETIONS if self.suppress_explicit_completions: completion_flags |= sublime.INHIBIT_EXPLICIT_COMPLETIONS return (proposals, completion_flags)
def get_proposals(project, source, offset=None, **kwargs): head = 'from scopetest import *\n\n' source = head + source if offset is None: offset = len(source) else: offset += len(head) resource = NoProject().get_file(join_to_file_dir(__file__, 'module.py')) resource.read = lambda: '' return code_assist(project, source, offset, resource=resource, **kwargs)
def get_proposals(self): ret = [] proposals = codeassist.code_assist(self.project, self.source_code, self.code_point, resource=self.resource, maxfixes=10) proposals = codeassist.sorted_proposals(proposals) if V(ROPE_VERSION) <= V('0.9.2'): for proposal in proposals: ret.append(new_completion_item(name=proposal.name, scope=proposal.kind, type=proposal.type)) else: for proposal in proposals: ret.append(new_completion_item(name=proposal.name, scope=proposal.scope, type=proposal.type)) return ret
def getCompletions(self): offset = self.getOffset() project = self.getProject() proposals = codeassist.code_assist(project, self.editorTabWidget.getSource(), offset) proposals = codeassist.sorted_proposals(proposals) if len(proposals) > 0: cmpl = [] for i in proposals: cmpl.append(str(i)) return cmpl else: return []
def _calculate_proposals(self): self.interface._check_project() resource = self.interface._get_resource() maxfixes = self.env.get('codeassist_maxfixes') proposals = codeassist.code_assist( self.interface.project, self.source, self.offset, resource, maxfixes=maxfixes) proposals = codeassist.sorted_proposals(proposals) names = [proposal.name for proposal in proposals] if self.autoimport is not None: if self.starting.strip() and '.' not in self.expression: import_assists = self.autoimport.import_assist(self.starting) names.extend(x[0] + ' : ' + x[1] for x in import_assists) return names
def update_proposals(self, update): source, offset = self.get_source_and_offset() try: proposals = codeassist.sorted_proposals( codeassist.code_assist(self.project, source, offset, resource=self.get_rope_resource( self.project))) except Exception, e: self.editor.update_message(str(e), "no", 1) traceback.print_exc() return False
def on_query_completions(self, view, prefix, locations): if (not view.match_selector(locations[0], 'source.python') or not (self.complete_as_you_type) or SublimeRopeListener.user_requested): return [] SublimeRopeListener.user_requested = False with ropemate.context_for(view) as context: loc = locations[0] try: raw_proposals = codeassist.code_assist( context.project, context.input, loc, context.resource, maxfixes=3, later_locals=False, case_sensitive=self.case_sensitive_completion) except ModuleSyntaxError: raw_proposals = [] if not raw_proposals and self.use_simple_completion: # try the simple hackish completion line = view.substr(view.line(loc)) identifier = line[:view.rowcol(loc)[1]].strip(' .') if ' ' in identifier: identifier = identifier.split(' ')[-1] raw_proposals = self.simple_module_completion(view, identifier) # do not use rope's own sorting for large results, it is very slow! # simple sort-by-name is good enough if len(raw_proposals) <= 20: sorted_proposals = codeassist.sorted_proposals(raw_proposals) else: sorted_proposals = sorted(raw_proposals, key=lambda p: p.name) proposals = [(self.proposal_string(p), self.insert_string(p)) for p in sorted_proposals if p.name != 'self='] completion_flags = 0 if self.suppress_word_completions: completion_flags = sublime.INHIBIT_WORD_COMPLETIONS if self.suppress_explicit_completions: completion_flags |= sublime.INHIBIT_EXPLICIT_COMPLETIONS return (proposals, completion_flags)
def do_populate(self, context): project = self.plugin().project_manager.project from rope.contrib import codeassist try: proposals = codeassist.sorted_proposals( codeassist.code_assist(project, *self.plugin().get_source_and_offset(), resource=self.plugin().get_rope_resource(project), maxfixes=3)) except Exception, e: import traceback traceback.print_exc() self.plugin().editor.message(str(e), 5000) return
def _calculate_proposals(self): self.interface._check_project() resource = self.interface.resource maxfixes = self.env.get('codeassist_maxfixes') proposals = codeassist.code_assist( self.interface.project, self.source, self.offset, resource, maxfixes=maxfixes) proposals = codeassist.sorted_proposals(proposals) if self.autoimport is not None: if self.starting.strip() and '.' not in self.expression: import_assists = self.autoimport.import_assist(self.starting) for assist in import_assists: p = codeassist.CompletionProposal(' : '.join(assist), 'autoimport') proposals.append(p) return proposals
def python_engine_get_completion_file(filename, offset): from rope.contrib import codeassist f = open(filename, 'r') code = ''.join(f.readlines()) proposals_string = [] try: proposals = codeassist.code_assist(pythonlab_rope_project, code, offset, maxfixes=20) # proposals = codeassist.sorted_proposals(proposals) for p in proposals: proposals_string.append(p.__str__()) return proposals_string # return [proposal.name for proposal in proposals] except: return []
def completions(self, source, project_path, file_path, loc): project = self.project_for(project_path, file_path) resource = libutils.path_to_resource(project, file_path) try: proposals = code_assist(project, source, loc, resource=resource, maxfixes=3) proposals = sorted_proposals(proposals) except ModuleSyntaxError: proposals = [] except Exception: import traceback traceback.print_exc() return [] proposals = [(self._proposal_string(p), self._insert_string(p)) for p in proposals if p.name != 'self='] return proposals
def rope_completions(self): """ Returns list of completions based on the current project contents """ try: proposals = codeassist.code_assist(self.ropeProject, self.source, self.offset) proposals = codeassist.sorted_proposals(proposals) if len(proposals) > 0: completions = [] for i in proposals: completions.append(str(i)) return completions else: return [] except: pass
def autocomplete(): """Can auto complete your code.""" with ropemate.context as context: offset = caret_position(context.input) pid = os.fork() result = "" if pid == 0: try: raw_proposals = codeassist.code_assist(context.project, context.input, offset, context.resource) sorted_proposals = codeassist.sorted_proposals(raw_proposals) proposals = [ p for p in sorted_proposals if p.name != "self="] if len(proposals) == 0: proposals, errors = simple_module_completion() else: completion_popup(proposals) except Exception as e: tooltip(e) return result
def pyls_completions(document, position): log.debug('Launching Rope') # Rope is a bit rubbish at completing module imports, so we'll return None word = document.word_at_position({ # The -1 should really be trying to look at the previous word, but that might be quite expensive # So we only skip import completions when the cursor is one space after `import` 'line': position['line'], 'character': max(position['character'] - 1, 0), }) if word == 'import': return None offset = document.offset_at_position(position) definitions = code_assist(document._rope_project, document.source, offset, document._rope, maxfixes=3) definitions = sorted_proposals(definitions) new_definitions = [] for d in definitions: try: doc = d.get_doc() except AttributeError: doc = None new_definitions.append({ 'label': d.name, 'kind': _kind(d), 'detail': '{0} {1}'.format(d.scope or "", d.name), 'documentation': doc or "", 'sortText': _sort_text(d) }) definitions = new_definitions log.debug('Rope finished') return definitions or None
def complete(self, cr): if self._project: try: self.popupView.clear() code = str(self._editor.toPlainText()) start = self._editor.textCursor().position() if self._fromProject: self._project.validate() proposals = codeassist.code_assist(self._project, code, start) proposals = codeassist.sorted_proposals(proposals) model = self.obtain_model_items(proposals) self.setModel(model) self.popup().setCurrentIndex(model.index(0, 0)) cr.setWidth(self.popup().sizeHintForColumn(0) \ + self.popup().verticalScrollBar().sizeHint().width() + 10) self.popupView.updateGeometries() super(Completer, self).complete(cr) except: return
def autocomplete(): """Can auto complete your code.""" with ropemate.context as context: offset = caret_position(context.input) pid = os.fork() result = "" if pid == 0: try: raw_proposals = codeassist.code_assist(context.project, context.input, offset, context.resource) sorted_proposals = codeassist.sorted_proposals(raw_proposals) proposals = filter(lambda p: p.name != "self=", sorted_proposals) if len(proposals) == 0: proposals, errors = simple_module_completion() if len(proposals) == 0: tooltip("No completions found!%s" % errors) else: completion_popup(proposals) except Exception, e: tooltip(e) return result
def get_proposals(project, source, offset=None, **kwargs): head = ( 'class Window(object):\n' ' """glade-file: sample.glade"""\n' '\n' ' def func(self):\n' ' ' ) source = head + source if offset is None: offset = len(source) else: offset += len(head) resource = NoProject().get_file(join_to_file_dir(__file__, 'pygtktest', 'module.py')) resource.read = lambda: '' return code_assist(project, source, offset, resource=resource, **kwargs)
def _complete(self): caret_index = self.source.find(tm.CURRENT_LINE) + tm.LINE_INDEX project = self.get_project() resource = project.get_resource(tm.FILEPATH.replace(tm.PROJECT_DIRECTORY, '')[1:]) current_word = tm.current_word(r"[a-zA-Z_]*", 'both') proposals = codeassist.code_assist(project, self.source, caret_index, resource) try: if len(proposals) == 0: raise 'no proposals found' except: tm.exit_show_tool_tip("No completions.") if len(proposals) == 1: tm.exit_insert_text(proposals[0].name.replace(current_word, '', 1)) else: proposals = codeassist.sorted_proposals(proposals) names = [proposal.name for proposal in proposals] tm.ui.complete(names, {'initial_filter': current_word, 'extra_chars': "_"})
def on_query_completions(self, view, prefix, locations): if not view.match_selector(locations[0], "source.python"): return [] loc = locations[0] line = view.substr(view.line(loc)) with ropemate.ropecontext(view) as context: try: raw_proposals = codeassist.code_assist( context.project, context.input, loc, context.resource) except ModuleSyntaxError: raw_proposals = [] if len(raw_proposals) > 0: sorted_proposals = codeassist.sorted_proposals(raw_proposals) else: # try the simple hackish completion identifier = line[:view.rowcol(loc)[1] - 1].strip() raw_proposals = self.simple_module_completion(view, identifier) sorted_proposals = sorted(raw_proposals, key=lambda x: x.name) proposals = filter(lambda p: p.name != "self=", sorted_proposals) return [(str(p), p.name) for p in proposals]
def on_query_completions(self, view, prefix, locations): if not view.match_selector(locations[0], "source.python"): return [] with ropemate.ropecontext(view) as context: loc = locations[0] try: raw_proposals = codeassist.code_assist( context.project, context.input, loc, context.resource) except ModuleSyntaxError: raw_proposals = [] if len(raw_proposals) <= 0: # try the simple hackish completion line = view.substr(view.line(loc)) identifier = line[:view.rowcol(loc)[1]].strip(' .') if ' ' in identifier: identifier = identifier.split(' ')[-1] raw_proposals = self.simple_module_completion(view, identifier) sorted_proposals = codeassist.sorted_proposals(raw_proposals) proposals = filter(lambda p: p.name != "self=", sorted_proposals) return [(str(p), p.name) for p in proposals]
def complete(self): if TM_PROJECT_DIRECTORY is None: return '' #from rope.contrib import autoimport project = Project(TM_PROJECT_DIRECTORY) #autoimport = autoimport.AutoImport(project) resource = project.get_resource(TM_FILEPATH.replace(TM_PROJECT_DIRECTORY, '')[1:]) #project.validate(self.project_path) caret_index = self.source.find(TM_CURRENT_LINE) + TM_LINE_INDEX try: proposals = codeassist.code_assist(project, self.source, caret_index, resource) except: ass = PythonCodeAssist(project) proposals = ass.assist(self.source, caret_index, resource) try: if len(proposals) == 0: return '' except: return '' if len(proposals) == 1: selection = proposals[0].name else: proposals = codeassist.sorted_proposals(proposals) #autoimport.generate_cache() #autoimport.generate_modules_cache(modules) #project.pycore.analyze_module(resource) names = [proposal.name for proposal in proposals] #if self.starting.strip() and '.' not in self.expression: # import_assists = self.autoimport.import_assist(self.starting) # names.extend(x[0] + ' : ' + x[1] for x in import_assists) #plist = "{ menuItems=(%s);}" selection = dialog.menu(names) if selection is None: return '' if TM_CURRENT_WORD is None: return selection else: return selection.replace(TM_CURRENT_WORD, '')
def main(): # TODO: Determine if this is necessary. Can we still provide basic completion in a 'standalone' file? if textmate.PROJECT_DIRECTORY is None: textmate.exit_show_tool_tip('No completions.') source = sys.stdin.read() #from rope.contrib import autoimport project = Project(textmate.PROJECT_DIRECTORY) #autoimport = autoimport.AutoImport(project) resource = project.get_resource(textmate.FILEPATH.replace(textmate.PROJECT_DIRECTORY, '')[1:]) #project.validate(self.project_path) caret_index = source.find(textmate.CURRENT_LINE) + textmate.LINE_INDEX current_word = textmate.current_word(r"[a-zA-Z_]*", 'both') proposals = codeassist.code_assist(project, source, caret_index, resource) try: if len(proposals) == 0: raise 'no proposals found' except: textmate.exit_show_tool_tip("No completions.") if len(proposals) == 1: textmate.exit_insert_text(proposals[0].name.replace(current_word, '', 1)) else: proposals = codeassist.sorted_proposals(proposals) #autoimport.generate_cache() #autoimport.generate_modules_cache(modules) #project.pycore.analyze_module(resource) names = [proposal.name for proposal in proposals] #if self.starting.strip() and '.' not in self.expression: # import_assists = self.autoimport.import_assist(self.starting) # names.extend(x[0] + ' : ' + x[1] for x in import_assists) #plist = "{ menuItems=(%s);}" ui.complete(names, {'initial_filter': current_word, 'extra_chars': "_"})
def get_proposals(self): ret = [] proposals = codeassist.code_assist(self.project, self.source_code, self.code_point, resource=self.resource, maxfixes=10) proposals = codeassist.sorted_proposals(proposals) if V(ROPE_VERSION) <= V('0.9.2'): for proposal in proposals: ret.append( new_completion_item(name=proposal.name, scope=proposal.kind, type=proposal.type)) else: for proposal in proposals: ret.append( new_completion_item(name=proposal.name, scope=proposal.scope, type=proposal.type)) return ret
def _assist(self, code, resource=None, **kwds): return code_assist(self.project, code, len(code), resource, **kwds)
def _assist(self, code, offset=None, **args): if offset is None: offset = len(code) return code_assist(self.project, code, offset, **args)
def _assist(self, code, offset=None, resource=None, **kwds): if offset is None: offset = len(code) return code_assist(self.project, code, offset, resource, **kwds)
ICONS = { #types 'variable': Icon.variable, 'parameter': Icon.variable, 'function': Icon.method, 'class': Icon.klass, 'imported': Icon.namespace, 'builtin': Icon.struct, #kids 'attribute': Icon.member, } def sort_function(element): #scintilla requires the list sorted #return KINDS.get(element.kind), TYPES.get(element.type), element.name return element.name project = Project(project_path) resource = File(project, name=file_name) elements = codeassist.code_assist(project, source, position, resource=resource) elements.sort(key=sort_function) for element in elements: icon = ICONS.get(element.type) or ICONS.get(element.kind) or '?7' #print element print element.name + icon