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): """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. """ try: self.dprint('{0}.complete(text="{1}", state="{2}")'.format( self.name, text, state)) origline = readline.get_line_buffer() or "" try: if state == 0: line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped menu = self.get_submenu_completer_for_text(origline) readline.set_completion_display_matches_hook( menu._completer_display) self.dprint( 'Complete(): text:{0}, origline:{1}, begidx:{2}, endidz:{3}' .format(text, line, begidx, endidx)) if begidx >= 0: #cmd, args, foo = self.parseline(line) cmd, args, foo = menu.parseline(text) compfunc = menu.completedefault if cmd and hasattr( menu, 'complete_' + cmd, ): compfunc = getattr(menu, 'complete_' + cmd) menu.dprint('Complete(): got method complete_' + str(cmd)) else: menu.dprint('Complete(): non-zero state sending to ' 'completenames(), state:{0}'.format(state)) compfunc = menu.completenames try: self.completion_matches = compfunc( text, line, begidx, endidx) except: print_exc() raise try: self.dprint( 'Returning {0}.complete(text={1}, state={2}) = "{3}"'. format(self.name, text, state, self.completion_matches[state])) return self.completion_matches[state] except IndexError: return None finally: readline.set_completion_display_matches_hook( self._completer_display) except Exception as E: # readline will often fail silently, and not always show/raise errors self.stderr.write('{0}\nError in complete: "{1}"'.format( get_traceback(), E)) raise
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(text, state): """Tab complete for readline.""" line = readline.get_line_buffer() # there is a difference in the way line buffer is handled by GNU readline # and by libedit, which is what runs by default on OSX. With GNU readline # the line buffer is empty after each command; with libedit, old buffer # remains, and gets overwritten from the beginning on (if the previous # line was 'foobaz', and someone types 'xxx' on new line, then the line # buffer is 'xxxbaz'). This is why the content of the line buffer needs to # be trimmed, if completion decisions are to be made based on the buffer # content. # line = line[:readline.get_endidx()] # first token if text == line: matches = [c+" " for c in completions['commands'] if c.startswith(text.lower())] else: command = line.split(" ")[0].lower() if command in ['view', 'open']: matches = [h['_id'] for h in completions['hits'] if h['_id'].startswith(text)] elif command in ['count', 'search']: matches = [f for f in completions['fields'] if f.startswith(text)] response = sorted(matches)[state] 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) if cmd == '': complete_func = self.completer else: try: complete_func = getattr(self, 'complete_' + cmd) except: complete_func = self.completer 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): response = None if state == 0: # This is the first time for this text, so build a match list. orgline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = orgline[begin:end] unpack_words = orgline[:begin].split() try: candidates = self._unpack(self.options, *unpack_words) 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), err: self.current_candidates = []
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): 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 tab_complete(self, text, state): """Called by readline to handle tab-completion.""" # readline will call this function with state=0..n until we # return None indicating no more matches. I.e. we should only # check for matches when state=0, and cache the results for # answering the next calls. See the gnu-readline (C-version) # docs for details line = readline.get_line_buffer() endidx = readline.get_endidx() args = CommandLine.split_command(line[:endidx]) if state == 0: try: lvl = len(args) - 1 if endidx > 0 and line[endidx - 1] == ' ': lvl += 1 args.append('') self.__matches = self._find_matches_at(args, lvl) except AnalyzeCommandException: return None except: logger.error("Unexpected tab-complete exception", exc_info=1) try: if state == len(self.__matches) - 1: # The readline doc su**s. This ugly hack aparently # makes appending a space to the match work. return self.__matches[state] + ' ' return self.__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: 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): """ 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 completer(text, state): global _last_line global _last_res global rl_completion_suppress_append if rl_completion_suppress_append is not None: rl_completion_suppress_append.value = 1 try: line = readline.get_line_buffer()[:readline.get_endidx()] if _last_line != line: _last_res = _completer_get_subs(line) _last_line = line (dir, name, qtype, lastword, subs) = _last_res if state < len(subs): sn = subs[state] sn1 = sn.try_resolve() # find the type of any symlink target fullname = os.path.join(dir, sn.name) if stat.S_ISDIR(sn1.mode): ret = shquote.what_to_add(qtype, lastword, fullname+'/', terminate=False) else: ret = shquote.what_to_add(qtype, lastword, fullname, terminate=True) + ' ' return text + ret except Exception as e: log('\n') try: import traceback traceback.print_tb(sys.exc_traceback) except Exception as e2: log('Error printing traceback: %s\n' % e2) log('\nError in completion: %s\n' % e)
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 completer(text, state): global _last_line global _last_res global rl_completion_suppress_append if rl_completion_suppress_append is not None: rl_completion_suppress_append.value = 1 try: line = readline.get_line_buffer()[:readline.get_endidx()] if _last_line != line: _last_res = _completer_get_subs(line) _last_line = line (dir, name, qtype, lastword, subs) = _last_res if state < len(subs): sn = subs[state] sn1 = sn.resolve('') # deref symlinks fullname = os.path.join(dir, sn.name) if stat.S_ISDIR(sn1.mode): ret = shquote.what_to_add(qtype, lastword, fullname+'/', terminate=False) else: ret = shquote.what_to_add(qtype, lastword, fullname, terminate=True) + ' ' return text + ret except Exception, e: log('\nerror in completion: %s\n' % e)
def generate_parameters(self, text, state): if state == 0: self.available = [] self.current = 0 try: line = readline.get_line_buffer()[:readline.get_endidx( )].split(' ') cmd = self.manager.find(line[0]) except: return 0 current_params = list( filter(lambda x: len(x.strip()) > 0, line[1:-1] if len(line) > 2 else [])) if ',' in text: text = text.split(',')[-1] for i in cmd.parameters(self.mole, current_params): if i[:len(text)] == text: self.available.append(i) self.available.sort() if len(self.available) == 1: text = self.available[0] self.available = [] self.current = len(self.available) return text + cmd.parameter_separator(current_params) return self.get_completion(text, state)
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: 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 completer(text, state): global _last_line global _last_res global rl_completion_suppress_append if rl_completion_suppress_append is not None: rl_completion_suppress_append.value = 1 try: line = readline.get_line_buffer()[:readline.get_endidx()] if _last_line != line: _last_res = _completer_get_subs(line) _last_line = line (dir, name, qtype, lastword, subs) = _last_res if state < len(subs): sn = subs[state] sn1 = sn.try_resolve() # find the type of any symlink target fullname = os.path.join(dir, sn.name) if stat.S_ISDIR(sn1.mode): ret = shquote.what_to_add(qtype, lastword, fullname+'/', terminate=False) else: ret = shquote.what_to_add(qtype, lastword, fullname, terminate=True) + ' ' return text + ret except Exception, e: log('\n') try: import traceback traceback.print_tb(sys.exc_traceback) except Exception, e2: log('Error printing traceback: %s\n' % e2)
def get_endidx(self): if util.isPlatformWindows(): import pyreadline return Readline().get_endidx() else: import readline return readline.get_endidx()
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): 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): """Return the next possible completion for 'text'.""" if state == 0: try: import readline except ImportError: import pyreadline as readline origline = readline.get_line_buffer() begidx = readline.get_begidx() endidx = readline.get_endidx() if begidx > 0: cmd, args, foo = self.parseline(origline) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd.lower()) except AttributeError: try: compfunc = self.ctx.lookup_compfunction(cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames arglist = [item.strip() for item in origline.strip().split()] comp_state = self.get_compstate(text, arglist) self.completion_matches = compfunc(text, origline, arglist, comp_state, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
def _complete(self, text: str, state: int) -> Optional[Sequence[str]]: """ Return the next possible completion for `text`. If a command has not been entered, then complete against command list. Otherwise try to call specific command completer function 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 and line: cmd, *_ = self._parse_line(line) try: complete_function = self._get_command(cmd).complete except CommandError: return 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
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): """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 tab_complete(self, text, state): """Called by readline to handle tab-completion.""" # readline will call this function with state=0..n until we # return None indicating no more matches. I.e. we should only # check for matches when state=0, and cache the results for # answering the next calls. See the gnu-readline (C-version) # docs for details line = readline.get_line_buffer() endidx = readline.get_endidx() args = CommandLine.split_command(line[:endidx]) if state == 0: try: lvl = len(args) - 1 if endidx > 0 and line[endidx-1] == ' ': lvl += 1 args.append('') self.__matches = self._find_matches_at(args, lvl) except AnalyzeCommandException: return None except: logger.error("Unexpected tab-complete exception", exc_info=1) try: if state == len(self.__matches)-1: # The readline doc su**s. This ugly hack aparently # makes appending a space to the match work. return self.__matches[state] + ' ' return self.__matches[state] except IndexError: return None
def _GetNextCompletion(self, state): if state == 0: # TODO: Tokenize it according to our language. If this is $PS2, we also # need previous lines! Could make a VirtualLineReader instead of # StringLineReader? buf = readline.get_line_buffer() # Begin: the index of the first char of the 'word' in the line. Words # are parsed according to readline delims (which we won't use). begin = readline.get_begidx() # The current position of the cursor. The thing being completed. end = readline.get_endidx() if self.debug: self.status_out.Write(0, 'line: %r / begin - end: %d - %d, part: %r', buf, begin, end, buf[begin:end]) self.comp_iter = self.root_comp.Matches(buf, self.status_out) if self.comp_iter is None: self.status_out.Write(0, "ASSERT comp_iter shouldn't be None") try: next_completion = self.comp_iter.next() except StopIteration: next_completion = None # sentinel? return next_completion
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 completer_hook(self, text, state): if state == 0: linebuf = readline.get_line_buffer() line = linebuf.lstrip() stripped = len(linebuf) - len(line) begin = readline.get_begidx() - stripped end = readline.get_endidx() - stripped if begin > 0: try: cmd, args = self.cmd_split(line) except KeyError: return None cfunc = cmd.complete else: cfunc = self.complete_names if self.pad_completion: pad = lambda x: x + ' ' if not x.endswith(' ') or \ x.endswith(r'\ ') else x else: pad = lambda x: x choices = self.complete_wrap(cfunc, text, line, begin, end) self.completer_cache = list(map(pad, choices)) try: return self.completer_cache[state] except IndexError: return None
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 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): """ auto-complete selection based on given text and state parameters """ 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: mod, args, foo = self.parseline(line) if mod == '': return self.complete_modules(text)[state] elif not mod in self.modules: logger.error("BUG: mod '{}' not found!".format(mod)) else: module = self.modules[mod] self.completion_matches = \ self.complete_functions(module, text, line, begidx, endidx) else: self.completion_matches = self.complete_modules(text) try: return self.completion_matches[state] except IndexError: return ['']
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 None
def get_endidx ( self ): if util.isPlatformWindows (): import pyreadline return Readline ().get_endidx () else: import readline return readline.get_endidx ()
class BofhCompleter(object): """ Completer functor for bofh completion. An instance of this class should be usable as a completer to send to GNU readline. """ def __init__(self, bofh, encoding): """ Create a bofhcompleter object. :param bofh: The bofh object. :param encoding: The encoding used """ self._bofh = bofh # completes is tested and filled in __call__ self.completes = [] self.encoding = encoding def __call__(self, text, num): """Complete a text. Readline will call this repeatedly with the same text parameter, and an increasing num parameter. :param text: The text to complete :param num: The index starting with 0 :type num: int :returns: The num'th completion or None when no more completions exists """ if num == 0: self._init_matches(text) if len(self.completes) == 1: return self.completes[0] + u' ' try: return self.completes[num] except IndexError: return None 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 except parser.IncompleteParse, e: self.completes = e.parse.complete(readline.get_begidx(), readline.get_endidx())
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 format_completions(self, substitution: str, matches: Sequence[str], longest_match_length: int) -> None: import readline print() files, dirs = [], [] for m in matches: if m.endswith('/'): if len(m) > 1: m = m[:-1] dirs.append(m) else: files.append(m) ss = screen_size_function()() if dirs: print(styled('Directories', bold=True, fg_intense=True)) print_table(dirs, ss, self.dircolors) if files: print(styled('Files', bold=True, fg_intense=True)) print_table(files, ss, self.dircolors) buf = readline.get_line_buffer() x = readline.get_endidx() buflen = wcswidth(buf) print(self.prompt, buf, sep='', end='') if x < buflen: pos = x + self.prompt_len print(f"\r\033[{pos}C", end='') print(sep='', end='', flush=True)
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(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: # 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): """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 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): """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): """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 completer(text, iteration): global repo global _last_line global _last_res global rl_completion_suppress_append if rl_completion_suppress_append is not None: rl_completion_suppress_append.value = 1 try: line = readline.get_line_buffer()[:readline.get_endidx()] if _last_line != line: _last_res = _completer_get_subs(repo, line) _last_line = line (dir, name, qtype, lastword, subs) = _last_res if iteration < len(subs): path = subs[iteration] leaf_name, leaf_item = path[-1] res = vfs.try_resolve(repo, leaf_name, parent=path[:-1]) leaf_name, leaf_item = res[-1] fullname = os.path.join(*(name for name, item in res)) if stat.S_ISDIR(vfs.item_mode(leaf_item)): ret = shquote.what_to_add(qtype, lastword, fullname+'/', terminate=False) else: ret = shquote.what_to_add(qtype, lastword, fullname, terminate=True) + ' ' return text + ret except Exception as e: log('\n') try: import traceback traceback.print_tb(sys.exc_traceback) except Exception as e2: log('Error printing traceback: %s\n' % e2) log('\nError in completion: %s\n' % e)
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 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 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 complete(self, text, state): # pylint: disable=broad-except try: entire_text = readline.get_line_buffer()[:readline.get_endidx()] completions = self._get_completions(entire_text, text) return completions[state] except Exception: traceback.print_exc()
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 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 get_line_buffer(self): """Returns current line through cursor position with leading whitespace stripped """ if readline is None: return '' else: line = readline.get_line_buffer()[:readline.get_endidx()] return line.lstrip()
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 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)