def tab_completer(text, state): """Called by the readline lib to calculate possible completions""" array_to_match = None if readline.get_begidx() == 0: # since we are at the start of the line # we are matching commands array_to_match = 'cmds' match_list = CMD_ARG_DICT.get('cmds', {}).keys() else: # we are matching args cmd_line = readline.get_line_buffer()[0:readline.get_begidx()] cmd = shlex.split(cmd_line)[-1] array_to_match = CMD_ARG_DICT.get('cmds', {}).get(cmd) if array_to_match: match_list = CMD_ARG_DICT[array_to_match] else: array_to_match = CMD_ARG_DICT.get('options', {}).get(cmd) if array_to_match: match_list = CMD_ARG_DICT[array_to_match] else: array_to_match = 'options' match_list = CMD_ARG_DICT.get('options',{}).keys() matches = [item for item in match_list if item.upper().startswith(text.upper())] try: return matches[state] except IndexError: return None
def complete(self, text, state): if state == 0: import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if begidx>0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: #compfunc = getattr(self, 'complete_' + cmd) compfunc = self.pupy_completer.complete except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: if self.completion_matches: return self.completion_matches[state] except IndexError: return None
def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: origline = readline.get_line_buffer() line = origline.lstrip() # in case '|', ';', '&' used, take last part of line to complete line = re.split('&|\||;', line)[-1].lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if line.split(' ')[0] == 'sudo' and len(line.split(' ')) <= 2: compfunc = self.completesudo elif len (line.split(' ')) > 1 \ and line.split(' ')[0] in self.conf['allowed']: compfunc = self.completechdir elif begidx > 0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def complete(self, text, state): response = None if state == 0: # 首次输入文本,建立匹配项 origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() if not words: self.current_candidates = sorted(self.options.keys()) else: try: if begin == 0: candidates = self.options.keys() else: first = words[0] candidates = self.options[first] if being_completed: self.current_candidates = [ w for w in candidates if w.startswith(being_completed) ] else: self.current_candidates = candidates except (KeyError, IndexError), err: self.current_candidates = [] try: response = self.current_candidates[state] except IndexError: response = None return response
def complete(self, text, state): """ overwrite the origin complete function, but only change one line: self.completenames => self.complete_sequence_number """ if state == 0: import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if begidx > 0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.complete_sequence_number self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def complete(text, state): """On tab press, return the next possible completion""" rl_completion_append_character.value = '\0' global completion_results if state == 0: line = readline.get_line_buffer() if line.startswith(':'): # Control command completion completion_results = complete_control_command(line, text) else: if line.startswith('!') and text and line.startswith(text): dropped_exclam = True text = text[1:] else: dropped_exclam = False completion_results = [] # Complete local paths completion_results += complete_local_path(text) # Complete from history l = len(text) completion_results += [w + ' ' for w in history_words if \ len(w) > l and w.startswith(text)] if readline.get_begidx() == 0: # Completing first word from $PATH completion_results += [w + ' ' for w in user_commands_in_path \ if len(w) > l and w.startswith(text)] completion_results = remove_dupes(completion_results) if dropped_exclam: completion_results = ['!' + r for r in completion_results] if state < len(completion_results): return completion_results[state] completion_results = None
def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped # get the current command's name (argv[0]) try: name = self.parseline(line)[-1][0] except: name = None # if the cmd name has been entirely typed, then use it's dedicated # complete_*() method, or fallback to completedefault(). if begidx > 0: try: compfunc = getattr(self, 'complete_'+name) except AttributeError: compfunc = self.completedefault # if the cmd name is being typed, completion must suggest the # available commands list, aka completenames() else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state]+' ' except IndexError: return
def complete_readline(self, text, state): log.debug("complete_readline: text:%s, state:%s", text, state) response = None if state == 0: # This is the first time we are called for this text, so build a match list. import readline line = readline.get_line_buffer() words = line.split() index = readline.get_begidx() current = text first = "" if len(words) > 0: first = words[0] try: if len(current) == 0: previous = words[-1] else: previous = words[-2] except IndexError: previous = "" self.current_candidates = self.complete(first, current, previous, words, index) try: response = self.current_candidates[state] if len(self.current_candidates) == 1: # Add space if there is only one candidate response = "{} ".format(response) except IndexError: response = None log.debug("complete_readline(%s, %s) => %s", repr(text), state, response) return response
def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if begidx > 0: cmd, args, foo = self.parseline(line) if cmd == "": compfunc = self.completedefault else: try: compfunc = getattr(self, "complete_" + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def complete(self, text, state): response = None if state == 0: origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() if not words: self.current_candidates = sorted(self.options) else: try: if begin == 0: candidates = self.allcmd else: if origline.endswith(' '):words.append('') basedir,basefile = os.path.split(words[-1]) if words[0].lower()=="select": candidates=alllocalpath("%s/cheung/data/hosts/"%HOME) else: candidates = alllocalpath(basedir) being_completed = basefile if being_completed: self.current_candidates = [ w for w in candidates if w.startswith(being_completed) ] else: self.current_candidates = candidates except (KeyError, IndexError), err: self.current_candidates = []
def complete(self, text, state): """ Perfer Link: http://bbs.chinaunix.net/viewthread.php?tid=614952&extra=&page=1 """ if state == 0: import readline readline.set_completer_delims(' \t\n`~!@#$%^&*()-=+[{]}\\|;:\'",<>;?') origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if begidx > 0 : cmd, args, foo = self.parseline(line) if r'/' in text: compfunc = self.path_matches elif cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def complete(self, text, state): response = None if state == 0: # This is the first time for this text, so build a match list. origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() if not words: self.current_candidates = sorted(self.options.keys()) else: try: if begin == 0: # first word candidates = self.options.keys() else: # later word first = words[0] candidates = self.options[first] if being_completed: # match options with portion of input # being completed self.current_candidates = [ w for w in candidates if w.startswith(being_completed) ] else: # matching empty string so use all candidates self.current_candidates = candidates except (KeyError, IndexError), err: self.current_candidates = []
def complete(self, text, state): reponse = None if state == 0: origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() try: if begin == end: candidates = self.getCandidateList(words, [self.entry]) else: candidates = self.getCandidateList(words[0:-1], [self.entry]) if being_completed: self.candidates = [ w+' ' for w in candidates if w.startswith(being_completed) ] else: self.candidates = candidates except err: self.candidates = [] try: response = self.candidates[state] except IndexError: reponse = None return response
def get_begidx ( self ): if util.isPlatformWindows (): import pyreadline return Readline ().get_begidx () else: import readline return readline.get_begidx ()
def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped wordCnt = len(line[:begidx].split()) if wordCnt <= 0: self.completion_matches = self.completenames(text, line, begidx, endidx) elif wordCnt == 1: self.completion_matches = self.completecommands(text, line, begidx, endidx) else: self.completion_matches = self.completeparams(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ ## todo: improve this thing to, eg, complete in the middle of a token if state == 0: origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped compfunc = self.complete_default if begidx > 0: parts = self._parse_line(line) if len(parts) > 0: command = self.lookup(parts[0]) _compfunc = getattr(self, command.complete) if _compfunc is not None and callable(_compfunc): compfunc = _compfunc else: compfunc = self.complete_names self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def complete(self, text, state, plugin_scope=None): ''' ''' if state is 0: original_line = readline.get_line_buffer() completion_line = original_line[0:readline.get_endidx()] self.logger.debug('Command auto completion, user input: "%s", state is %s, completion_type is %s' \ % (original_line, state, readline.get_completion_type())) self.logger.debug(' begidx=%s endidx=%s completion_line="%s"' % (readline.get_begidx(), readline.get_endidx(), completion_line)) self.completion_user_input = sysadmintoolkit.userinput.UserInput(completion_line, self, plugin_scope, completion=True) self.logger.debug('Completion matches are %s' % self.completion_user_input.completion_matches) if len(self.completion_user_input.completion_matches) is 0 or \ (self.completion_user_input.status is 'label_conflict' and self.completion_user_input.input_keyword_list[-1] is not '' and self.completion_user_input.rest_of_line is not ''): self.print_error_on_user_input(self.completion_user_input) self.completion_matches = [] elif len(self.completion_user_input.completion_matches) is 1: self.completion_user_input.completion_matches[0] += ' ' try: return self.completion_user_input.completion_matches[state] except IndexError: return None
def complete(self, text, state): # pylint: disable=unused-argument ''' Tab complete for the current step. ''' if state == 0: parser = StatementParser(self.features) begidx = readline.get_begidx() endidx = readline.get_endidx() line = readline.get_line_buffer() prefix = line[begidx:endidx] if line else '' line = line[:endidx] if self.complete_single_token: # treat the entire line as a single token args = [line] else: # tokenize the line tokens = parser.tokenize(line) tokens = parser.condense(tokens) args = [t.text for t in tokens if isinstance(t, StringToken)] self.completions = self.active_step.complete(self, args, prefix) if state < len(self.completions): return self.completions[state] return None
def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped # Complete parameters if begidx>0: cmd, args, foo = self.parseline(line) if cmd == '': self.completion_matches = [] else: registered_command = self.get_registered_command(cmd) if registered_command != None: self.completion_matches = registered_command.complete(self.data, text, line, begidx, endidx) else: self.completion_matches = [] # Complete function names else: self.completion_matches = self.completenames(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def complete(self, text, state): if state == 0: origline = readline.get_line_buffer() line = origline.lstrip() # in case '|', ';', '&' used, take last part of line to complete line = re.split('&|\||;', line)[-1].lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if line.split(' ')[0] == 'sudo' and len(line.split(' ')) <= 2: compfunc = self.completesudo elif len (line.split(' ')) > 1 \ and line.split(' ')[0] in self.conf['allowed']: compfunc = self.completechdir elif begidx > 0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def complete(self, text, state): if state == 0: import readline line_buf = readline.get_line_buffer() line = line_buf.lstrip() strip_len = len(line_buf) - len(line) begidx = readline.get_begidx() - strip_len endidx = readline.get_endidx() - strip_len if begidx > 0: cmd, arg, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def complete(input, state): """Performs generic autocompletion action for whatever incomplete input string has been typed into the shell so far. Will be automatically called from somewhere in the `readline` module. Depending on the current content of `readline.get_line_buffer()`, this function retrieves a list of input terms which are considered likely to be in mind of the typing user, for instance because they begin with what the user has typed in so far. This list of candidate terms is put together by the :func:`~.commands.choices_left` function in the :mod:`.commands` module. Read its documentation for more information. """ # http://stackoverflow.com/a/5638688/1933494 buf = readline.get_line_buffer() # http://doughellmann.com/2008/11/pymotw-readline.html # begin = readline.get_begidx() # end = readline.get_endidx() #sgst = [s+' ' for s in commands.choices_left(buf)] # range from position of currently handled term to that of cursor csrng = (readline.get_begidx(), readline.get_endidx()) util.log('User input line: "{}"; current range {}'.format(buf, csrng)) #print '{}-{}'.format(*csrng) sgst = [s for s in commands.choices_left(buf, csrng)] return sgst[state]
def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: original_line = readline.get_line_buffer() line = original_line.lstrip() stripped = len(original_line) - len(line) start_index = readline.get_begidx() - stripped end_index = readline.get_endidx() - stripped if start_index > 0: cmd, args = self.parse_line(line) if cmd == '': complete_function = self.default_completer else: try: complete_function = getattr(self, 'complete_' + cmd) except AttributeError: complete_function = self.default_completer else: complete_function = self.raw_command_completer self.completion_matches = complete_function( text, line, start_index, end_index ) try: return self.completion_matches[state] except IndexError: return None
def list(): """Return a list of servers' name which starts with user's input, in this situation, user want to list servers with specific name.""" origcmd = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origcmd[begin:end] return [x for x in servers.keys() if x.startswith(being_completed)]
def _init_matches(self, text): u"""Init matches for text""" # Get the readline buffer, parse, and lookup the parse object # to fill in the completions. # Note how the bofh.parser module carefully inserts completions. line = readline.get_line_buffer().decode(self.encoding) # parse() raises exception when it could not make sense # of the input, but this should be fairly common for # completions try: parse = parser.parse(self._bofh, line) self.completes = parse.complete(readline.get_begidx(), readline.get_endidx()) except parser.NoGroup, e: idx = readline.get_begidx() if idx == 0 or line[:idx].isspace(): self.completes = e.completions
def completer(txt,state): levels = Levels.getInstance() words = split_buffer() if readline.get_begidx() == readline.get_endidx(): words.append('') matched = lookup_words(levels.completion_tab,words) matched.append(None) return matched[state]
def complete2(self,text,state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if ';' in line: begin, line = line.rsplit(';',1) begidx = begidx - len(begin) - 1 endidx = endidx - len(begin) - 1 if line[:begidx] == ' ' * begidx: begidx=0 if begidx>0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames # correct wrong splittion with '\ ' if line and begidx > 2 and line[begidx-2:begidx] == '\ ': Ntext = line.split(os.path.sep)[-1] self.completion_prefix = Ntext.rsplit('\ ', 1)[0] + '\ ' to_rm = len(self.completion_prefix) - 1 Nbegidx = len(line.rsplit(os.path.sep, 1)[0]) + 1 data = compfunc(Ntext.replace('\ ', ' '), line, Nbegidx, endidx) self.completion_matches = [p[to_rm:] for p in data if len(p)>to_rm] # correct wrong splitting with '-' elif line and line[begidx-1] == '-': try: Ntext = line.split()[-1] self.completion_prefix = Ntext.rsplit('-',1)[0] +'-' to_rm = len(self.completion_prefix) Nbegidx = len(line.rsplit(None, 1)[0]) data = compfunc(Ntext, line, Nbegidx, endidx) self.completion_matches = [p[to_rm:] for p in data if len(p)>to_rm] except Exception, error: print error else: self.completion_prefix = '' self.completion_matches = compfunc(text, line, begidx, endidx)
def _complete(self, text, state): ''' Text completion method, directly called by readline. Finds out what token the user wants completion for, and calls the _dispatch_completion() to get the possible completions. Then implements the state system needed by readline to return those possible completions to readline. @param text: The text to complete. @type text: str @returns: The next possible completion for text. @rtype: str ''' if state == 0: cmdline = readline.get_line_buffer() self._current_completions = [] self._completion_help_topic = '' self._current_parameter = '' (parse_results, path, command, pparams, kparams) = \ self._parse_cmdline(cmdline) beg = readline.get_begidx() end = readline.get_endidx() current_token = None if beg == end: # No text under the cursor, fake it so that the parser # result_trees gives us a token name on a second parser call self.log.debug("Faking text entry on commandline.") parse_results = self._parse_cmdline(cmdline + 'x')[0] if parse_results.command.value == 'x': current_token = 'command' elif 'x' in [x.value for x in parse_results.pparams]: current_token = 'pparam' elif 'x' in [x.value for x in parse_results.kparams]: current_token = 'kparam' elif path and beg == parse_results.path.location: current_token = 'path' elif command and beg == parse_results.command.location: current_token = 'command' elif pparams and beg in [p.location for p in parse_results.pparams]: current_token = 'pparam' elif kparams and beg in [k.location for k in parse_results.kparams]: current_token = 'kparam' self._current_completions = \ self._dispatch_completion(path, command, pparams, kparams, text, current_token) self.log.debug("Returning completions %s to readline." % str(self._current_completions)) if state < len(self._current_completions): return self._current_completions[state] else: return None
def rl_completer(self, curword, state): curline = readline.get_line_buffer() start = readline.get_begidx() end = readline.get_endidx() pfx = curline[:start] sglist = self.find_suggestions(pfx, curword) if state < len(sglist): return sglist[state] return None
def _tab_completer(self, text, state): idx = readline.get_begidx() if idx > 0: # For now, don't do completion of options return None options = [i for i in self.cmd_map if i.startswith(text)] try: return options[state] except IndexError: return None
def _complete(self, text, state): ''' Text completion method, directly called by readline. Finds out what token the user wants completion for, and calls the _dispatch_completion() to get the possible completions. Then implements the state system needed by readline to return those possible completions to readline. @param text: The text to complete. @type text: str @returns: The next possible completion for text. @rtype: str ''' self._set_readline_display_matches() if state == 0: cmdline = readline.get_line_buffer() self._current_completions = [] self._completion_help_topic = '' self._current_parameter = '' (parse_results, path, command, pparams, kparams) = \ self._parse_cmdline(cmdline) beg = readline.get_begidx() end = readline.get_endidx() if beg == end: # No text under the cursor, fake it so that the parser # result_trees gives us a token name on a second parser call self.log.debug("Faking text entry on commandline.") parse_results = self._parse_cmdline(cmdline + 'x')[0] end += 1 if path and beg == parse_results.path.location: current_token = 'path' elif command and beg == parse_results.command.location: current_token = 'command' elif pparams and beg in [p.location for p in parse_results.pparams]: current_token = 'pparam' elif kparams and beg in [k.location for k in parse_results.kparams]: current_token = 'kparam' self._current_completions = \ self._dispatch_completion(path, command, pparams, kparams, text, current_token) self.log.debug("Returning completions %s to readline." % str(self._current_completions)) if state < len(self._current_completions): return self._current_completions[state] else: return None
def complete(self, text, state): if state == 0: self._build_match_list(readline.get_line_buffer(), readline.get_begidx(), readline.get_endidx()) try: return self.matches[state] except IndexError: pass #except Exception as e: # print 'Error: {0}'.format(repr(e)) return None
def completer(self, text, state): if state == 0: options = [] original_line = readline.get_line_buffer() line = original_line.lstrip() stripped = len(original_line) - len(line) start_index = readline.get_begidx() - stripped end_index = readline.get_endidx() - stripped if start_index > 0: command = self.fmt.format_commands(line) if command[0] == "": complete_function = self.default_completer else: commands = self.commands.get_commands() other_commands = self.commands.get_modules_commands() other_commands.update(self.commands.get_plugins_commands()) if command[0] in commands: if hasattr(commands[command[0]], "complete"): complete_function = commands[command[0]].complete else: if 'Options' in commands[command[0]].details: options = commands[ command[0]].details['Options'] else: complete_function = self.default_completer elif command[0] in other_commands: if 'Options' in other_commands[command[0]]: options = other_commands[command[0]]['Options'] else: complete_function = self.default_completer else: complete_function = self.default_completer else: complete_function = self.commands.commands_completer if options: self.matches = self.options_completer(options, text) else: self.matches = complete_function(text) try: return self.matches[state] except IndexError: return None
def complete(self, text, state): response = None if state == 0: # This is the first time for this text, so build a match list. origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() logging.debug('origline=%s', repr(origline)) logging.debug('begin=%s', begin) logging.debug('end=%s', end) logging.debug('being_completed=%s', being_completed) logging.debug('words=%s', words) if not words: self.current_candidates = sorted(self.options.keys()) else: try: if begin == 0: # first word candidates = self.options.keys() else: # later word first = words[0] candidates = self.options[first] if being_completed: # match options with portion of input # being completed self.current_candidates = [ w for w in candidates if w.startswith(being_completed) ] else: # matching empty string so use all candidates self.current_candidates = candidates logging.debug('candidates=%s', self.current_candidates) except (KeyError, IndexError) as err: logging.error('completion error: %s', err) self.current_candidates = [] try: response = self.current_candidates[state] except IndexError: response = None logging.debug('complete(%s, %s) => %s', repr(text), state, response) return response
def complete_me(self, text, state): response = None if state == 0: # This is the first time for this text, so build a match list. origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() logging.debug('origline=%s', repr(origline)) logging.debug('begin=%s', begin) logging.debug('end=%s', end) logging.debug('being_completed=%s', being_completed) logging.debug('words=%s', words) if not words: self.current_candidates = sorted(self.options.keys()) else: try: cnt = 0 base_candidates = self.options max_cnt = len(words) if being_completed: max_cnt -= 1 while cnt < max_cnt: first = words[cnt] cnt += 1 base_candidates = base_candidates[first] candidates = base_candidates.keys() logging.debug('candidates=%s', self.current_candidates) if len(candidates) < 1: return self.complete_max(self, text, state) if being_completed: # match options with portion of input # being completed self.current_candidates = [ w for w in candidates if w.startswith(being_completed) ] else: # matching empty string so use all candidates self.current_candidates = candidates logging.debug('candidates=%s', self.current_candidates) except (KeyError, IndexError), err: logging.error('completion error: %s', err) self.current_candidates = []
def complete(self, text, state): if state == 0: begidx = readline.get_begidx() endidx = readline.get_endidx() line = readline.get_line_buffer() prefix = line[begidx:endidx] if line else '' line = line[:endidx] tokens = self.parser.tokenize(line) tokens = self.parser.condense(tokens) args = [t.text for t in tokens if isinstance(t, StringToken)] self.completions = self.active_step.complete(self, args, prefix) return self.completions[state] if state < len(self.completions) else None
def complete(self, text, state): if state == 0: self.completion_matches = [] begidx = readline.get_begidx() endidx = readline.get_endidx() line = readline.get_line_buffer() prefix = line[begidx:endidx] if line else '' line = line[:endidx] self.completion_matches = self.get_completions(line, prefix) if state < len(self.completion_matches): return self.completion_matches[state] return None
def generate_suggestions(self, text, state): if self._last_state is not None: if self._last_state['text'] == text and \ self._last_state['index'] == readline.get_begidx() and \ self._last_state['state'] == state: return self._last_state['output'] try: if readline.get_begidx() == 0: # First word on buffer, generate names output = self._generate_commands(text, state) else: # This may be a parameter to our current command output = self._generate_parameters(text, state) except Exception as ex: raise ex self._last_state = { 'text' : text, 'index' : readline.get_begidx(), 'state' : state, 'output' : output } return output
def complete(self, text, state): if state == 0: origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped compfunc = self.custom_comp_func self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def main_completer_handler(self, text, state): """ Handler of all input entries, tabs, and history :param text: input text :type text: string. :param state: current state :type state: string. """ response = None # Build match list on first iteration else continue if state == 0: origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() if not words: # option for words list self.current_candidates = sorted(self.options.keys()) else: # traverse all words entries and passing accordingly try: if begin == 0: # first word candidates = self.options.keys() else: # later word first = words[0] candidates = self.options[first] if being_completed: # match options with portion of input being completed self.current_candidates = [w for w in candidates\ if w.lower().startswith(being_completed.lower())] else: # matching empty string so use all candidates self.current_candidates = candidates except (KeyError, IndexError): self.current_candidates = [] # Return the state from the match list if found otherwise return None. try: response = self.current_candidates[state] except IndexError: # No candidate found for state response = None # Response return return response
def li_completer(self, text, state): # pylint: disable=too-many-branches,unused-argument # pylint: disable=too-many-nested-blocks """ The complete function of the input completer """ response = None if state == 0: # This is the first time for this text, # so build a match list. origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() if not words: self.li_candidates = sorted(self.li_command_dict().keys()) else: try: if begin == 0: # first word candidates = self.li_command_dict().keys() else: # later word first = words[0] command = self.li_command_dict()[first] options = command.lc_options candidates = options.cos_candidates() if being_completed: # match options with portion of input # being completed self.li_candidates = [] for candidate in candidates: if not candidate.startswith(being_completed): continue self.li_candidates.append(candidate) if len(words) > 1: paths = options.cos_complete_path(being_completed) if paths is not None: self.li_candidates += paths else: # matching empty string so use all candidates self.li_candidates = candidates except (KeyError, IndexError): self.li_candidates = [] try: response = self.li_candidates[state] except IndexError: response = None return response
def _rl_completer(self, text, state): if state == 0: curr = readline.get_line_buffer() b = readline.get_begidx() if b == 0: complist = self._controller.get_completion_scope("commands") else: # complete based on scope keyed on previous word word = curr[:b].split()[-1] complist = self._controller.get_completion_scope(word) self._complist = [s for s in complist if s.startswith(text)] try: return self._complist[state] except IndexError: return None
def complete(self, text, state): """Return the next possible completion to readline library""" if state == 0: line = readline.get_line_buffer() begidx = readline.get_begidx() endidx = readline.get_endidx() words, incomplete, args = self._parseline(line, begidx, endidx) # print('\n', words, incomplete, args, '\n') self.completion_matches = self._complete_line( words, incomplete, args) try: return self.completion_matches[state] except IndexError: return None
def _init_matches(self, text): """Init matches for text""" # Get the readline buffer, parse, and lookup the parse object # to fill in the completions. # Note how the bofh.parser module carefully inserts completions. line = readline.get_line_buffer().decode(self.encoding) # parse() raises exception when it could not make sense # of the input, but this should be fairly common for # completions try: parse = parser.parse(self._bofh, line) self.completes = parse.complete(readline.get_begidx(), readline.get_endidx()) except parser.NoGroup as e: idx = readline.get_begidx() if idx == 0 or line[:idx].isspace(): self.completes = e.completions except parser.IncompleteParse as e: self.completes = e.parse.complete(readline.get_begidx(), readline.get_endidx()) except: import traceback traceback.print_exc()
def complete(self, text, state): response = None if state == 0: # このテキストは初めてなのでマッチリストを作成する origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() logging.debug('origline=%s', repr(origline)) logging.debug('begin=%s', begin) logging.debug('end=%s', end) logging.debug('being_completed=%s', being_completed) logging.debug('words=%s', words) if not words: self.current_candidates = sorted(self.options.keys()) else: try: if begin == 0: # 最初の単語 candidates = self.options.keys() else: # 後続の単語 first = words[0] candidates = self.options[first] if being_completed: # 補完される入力部をもつオプションにマッチする self.current_candidates = [ w for w in candidates if w.startswith(being_completed) ] else: # 空の文字列がマッチしたので全ての候補を使用する self.current_candidates = candidates logging.debug('candidates=%s', self.current_candidates) except (KeyError, IndexError) as err: logging.error('completion error: %s', err) self.current_candidates = [] try: response = self.current_candidates[state] except IndexError: response = None logging.debug('complete(%s, %s) => %s', repr(text), state, response) return response
def complete(self, text, state): response = None if state == 0: origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() if not words: self.current_candidates = sorted(self.commands.keys()) else: try: if begin == 0: candidates = self.commands.keys() else: first = words[0] candidates = self.commands[first] if being_completed: self.current_candidates = [ w for w in candidates if w.startswith(being_completed) ] else: self.current_candidates = candidates nw = [] for w in words: try: nw.append(w.split('=')[0] + '=') except: pass self.current_candidates = list( filter(lambda c: not c in nw, self.current_candidates)) self.current_candidates = list( filter(lambda c: not c in words, self.current_candidates)) except (KeyError, IndexError) as err: print('completion error: %s'.format(err)) self.current_candidates = [] try: response = self.current_candidates[state] except IndexError: response = None return response
def possible_matches(self, text): """call ``rql.suggestions`` component to complete user's input. """ # readline will only send last token, but we need the entire user's input user_input = readline.get_line_buffer() query_struct = self.match(user_input) if query_struct is None: return [] else: # we must only send completions of the last token => compute where it # starts relatively to the rql query itself. completion_offset = readline.get_begidx() - query_struct['rql_offset'] rql_query = query_struct['rql_query'] return [suggestion[completion_offset:] for suggestion in self.rsb.build_suggestions(rql_query)]
def _completion(self, text, state): line = readline.get_line_buffer()[0:readline.get_begidx()] ctx = None try: result = self.parser.parse(line) if not state: try: self._completion_candidates = list(result.candidates(text)) except Exception, e: Interact.dump_traceback(e) self._force_redisplay() raise if self._completion_candidates: return self._completion_candidates.pop() return None
def completer(text: str, state: int, _last: List[str] = []) -> Optional[str]: if state == 0: send_control([ "complete", readline.get_line_buffer(), text, str(readline.get_begidx()), ]) _last[:] = recv_control() try: return _last[state] except IndexError: return None
def complete(self, text, state): """ Get the next possible completion for 'text'. If no complete command has been entered, then it completes against the commands provided by console and plugins. Otherwise it calls the complete_<command> method of the command. :param text: the input to complete. :param state: how many times has the method been called with the same 'text'. :return: the available completion for 'text' with state 'state'. """ if state == 0: # method has not been called for 'text', build a list of candidates. origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped if begidx > 0: # we have a prefix, hence search for a command completer. cmd, args, foo = self.parseline(line) if cmd == '': # no command has been entered, complete against available commands. compfunc = self._complete_default elif cmd in self._plugin_containers or cmd in self._system_plugin_containers: # command is provided by a Plugin, get the completer from there. if cmd in self._plugin_containers: container = self._plugin_containers[cmd] else: container = self._system_plugin_containers[cmd] try: # we need to get the completer from the container completer = container.get_completer(cmd) compfunc = completer.complete except (AttributeError, PluginError): compfunc = self._complete_default # no completer found for the command, defaulting. else: # command is provided by console. try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self._complete_default # no completer found, defaulting. else: # no prefix, we complete against the command names. compfunc = self._complete_commandnames self._completion_matches = compfunc( line) # get the list from the chosen completer. try: return self._completion_matches[ state] # return the completion entry for 'state'. except IndexError: return None
def _cli_completion(text, state): line = readline.get_line_buffer()[0:readline.get_begidx()] ctx = None try: result = Interact._parser.parse(line) if not state: Interact._completion_candidates = list(result.candidates(text)) if Interact._completion_candidates: return Interact._completion_candidates.pop() return None except cly.Error: return None except Exception as e: Interact._dump_traceback(e) cly.rlext.force_redisplay() raise
def complete(self, text, state): # pylint: disable=unused-argument ''' readline tab completion callback. ''' if state == 0: self.completion_matches = [] begidx = readline.get_begidx() endidx = readline.get_endidx() line = readline.get_line_buffer() prefix = line[begidx:endidx] if line else '' line = line[:endidx] self.completion_matches = self.get_completions(line, prefix) if state < len(self.completion_matches): return self.completion_matches[state] return None
def completer(self, text, state): line = readline.get_line_buffer() items = parse_command(line) if readline.get_begidx() > len(items[0]): if items[0] not in self.commands: return None else: return self.commands[items[0]].completer( self, items, text, state) options = [i for i in self.commands.keys() if i.startswith(text)] if state < len(options): return options[state] + ' ' else: return None
def complete(self, _text, state): response = None # This is the first time Tab has been pressed, so build up a list of matches. if state == 0: origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() self._init_matches(origline, begin, end) try: response = self.currentCandidates[state] except IndexError: response = None return response
def complete(text, state): index = readline.get_begidx() if index == 0: for cmd in COMMANDS: if cmd.startswith(text): if not state: return cmd else: state -= 1 else: if deviceServer: devices = deviceServer.get_devices() for dev in devices: if dev.address.startswith(text): if not state: return dev.address state -= 1
def complete_control_command(line, text): from polysh import control_commands if readline.get_begidx() == 0: # Completing control command name cmds = list_control_commands() prefix = text[1:] matches = [':' + cmd + ' ' for cmd in cmds if cmd.startswith(prefix)] else: # Completing control command parameters cmd = line.split()[0][1:] def def_compl(line): return [] compl_func = getattr(control_commands, 'complete_' + cmd, def_compl) matches = compl_func(line, text) return matches
def cc_completer(self, text, state): # pylint: disable=too-many-branches,unused-argument # pylint: disable=too-many-nested-blocks """ The complete function of the input completer """ response = None if state == 0: # Build a match list line = readline.get_line_buffer() begidx = readline.get_begidx() endidx = readline.get_endidx() self.cc_candidates = self.cc_get_candidates(line, begidx, endidx) if len(self.cc_candidates) > state: return self.cc_candidates[state] else: return response
def complete(self, text, state): if state == 0: original_line = readline.get_line_buffer() line = original_line.lstrip() stripped = len(original_line) - len(line) start_index = readline.get_begidx() - stripped end_index = readline.get_endidx() - stripped if start_index > 0: cmd, args = self.parse_line(line) else: complete_func = self.raw_command_completer self.completion_matches = complete_func(text, line, start_index, end_index) try: return self.completion_matches[state] except: return None
def complete(self, text, state): """ Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: if "readline" in sys.modules: origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if begidx > 0: if ">" in line and begidx > line.index(">"): self.completion_matches = self.completefilename( text, line, begidx, endidx) return self.completion_matches[0] command = self.parseline(line)[0] if command == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + command) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames matches = compfunc(text, line, begidx, endidx) if len(matches) == 1 and matches[0].endswith(os.path.sep): self.completion_matches = matches else: self.completion_matches = [s + " " for s in matches] try: return self.completion_matches[state] except IndexError: return None except TypeError: return None
def editComplete(text, state): """ Specific completer for the edit prompt. This subfunction should stay here because it needs to access to cmd members""" if state == 0: origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if begidx > 0: self.completion_matches = projectAndKeywordCompleter( "", text, line, begidx, endidx, shift=1) else: self.completion_matches = [] try: return self.completion_matches[state] except IndexError: return None