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 test_proposals_sorter(self): code = 'def my_sample_function(self):\n' + \ ' my_sample_var = 20\n' + \ ' my_sample_' proposals = sorted_proposals(self._assist(code)) self.assertEquals('my_sample_var', proposals[0].name) self.assertEquals('my_sample_function', proposals[1].name)
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 test_proposals_sorter_and_missing_type_in_typepref(self): code = 'my_global_var = 1\n' \ 'def my_global_func():\n' \ ' pass\n' \ 'my_' result = self._assist(code) proposals = sorted_proposals(result, typepref=['function']) # noqa
def test_proposals_sorter_and_missing_type_in_typepref(self): code = 'my_global_var = 1\n' \ 'def my_global_func():\n' \ ' pass\n' \ 'my_' result = self._assist(code) proposals = sorted_proposals(result, typepref=['function'])
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 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 test_completing_names_after_from_import_and_sorted_proposals(self): mod1 = testutils.create_module(self.project, 'mod1') mod2 = testutils.create_module(self.project, 'mod2') mod1.write('myvar = None\n') result = self._assist('from mod1 import myva', resource=mod2) result = sorted_proposals(result) self.assertTrue(len(result) > 0) self.assert_completion_in_result('myvar', 'global', result)
def test_proposals_sorter_for_global_methods_and_funcs(self): code = 'def my_b_func(self):\n' + \ ' pass\n' + \ 'my_a_var = 10\n' + \ 'my_' proposals = sorted_proposals(self._assist(code)) self.assertEquals('my_b_func', proposals[0].name) self.assertEquals('my_a_var', proposals[1].name)
def test_proposals_sorter_and_type_prefs(self): code = 'my_global_var = 1\n' \ 'def my_global_func(self):\n' \ ' pass\n' \ 'my_' result = self._assist(code) proposals = sorted_proposals(result, typepref=['variable', 'function']) self.assertEquals('my_global_var', proposals[0].name) self.assertEquals('my_global_func', proposals[1].name)
def test_proposals_sorter_and_kind_prefs(self): code = 'my_global_var = 1\n' \ 'def func(self):\n' \ ' my_local_var = 2\n' \ ' my_' result = self._assist(code) proposals = sorted_proposals(result, kindpref=['global', 'local']) self.assertEquals('my_global_var', proposals[0].name) self.assertEquals('my_local_var', proposals[1].name)
def test_proposals_sorter_and_scope_prefs(self): code = 'my_global_var = 1\n' \ 'def func(self):\n' \ ' my_local_var = 2\n' \ ' my_' result = self._assist(code) proposals = sorted_proposals(result, scopepref=['global', 'local']) self.assertEquals('my_global_var', proposals[0].name) self.assertEquals('my_local_var', proposals[1].name)
def test_proposals_sorter_and_type_prefs(self): code = 'my_global_var = 1\n' \ 'def my_global_func(self):\n' \ ' pass\n' \ 'my_' result = self._assist(code) proposals = sorted_proposals(result, typepref=['instance', 'function']) self.assertEquals('my_global_var', proposals[0].name) self.assertEquals('my_global_func', proposals[1].name)
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 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 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 test_proposals_sorter_underlined_methods(self): code = 'class A(object):\n' + \ ' def _my_func(self):\n' + \ ' self.my_a_var = 10\n' + \ ' def my_func(self):\n' + \ ' pass\n' + \ 'a_var = A()\n' + \ 'a_var.' proposals = sorted_proposals(self._assist(code)) self.assertEquals('my_func', proposals[0].name) self.assertEquals('_my_func', proposals[1].name)
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(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 _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 test_proposals_sorter_for_methods_and_attributes(self): code = 'class A(object):\n' + \ ' def __init__(self):\n' + \ ' self.my_a_var = 10\n' + \ ' def my_b_func(self):\n' + \ ' pass\n' + \ ' def my_c_func(self):\n' + \ ' pass\n' + \ 'a_var = A()\n' + \ 'a_var.my_' proposals = sorted_proposals(self._assist(code)) self.assertEquals('my_b_func', proposals[0].name) self.assertEquals('my_c_func', proposals[1].name) self.assertEquals('my_a_var', proposals[2].name)
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 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 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 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 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 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 _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': "_"})
class PythonCompleter(Completer): priority = LANG_PRIO.VERY_GOOD name = "rope" plugin = "python" description = _("Creates very exact suggestions at reasonable speed") 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 so = sorted_proposals(co) for c in so: if c.name.startswith(base): r = Suggestion(c.name) #'variable', 'class', 'function', 'imported' , 'paramter' if keyword.iskeyword(c.name): r.type_ = COMPLETER.KEYWORD elif c.type in ( 'variable', 'class', 'builtin', 'function', 'parameter', ): r.type_ = getattr(COMPLETER, c.type.upper()) elif c.type == None: if c.kind == "parameter_keyword": r.type_ = COMPLETER.PARAMETER else: r.type_ = COMPLETER.UNKNOWN yield r
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 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 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
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()