Ejemplo n.º 1
0
    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()

            # Offer completion just for commands that starts
            # with the trigger :
            if origline and not origline.startswith(':'):
                return None

            line = origline.lstrip().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
Ejemplo n.º 2
0
def complete(text, state):
    '''completion routine for when user presses tab'''
    global last_clist
    global rline_mpstate
    if state != 0 and last_clist is not None:
        return last_clist[state]

    # split the command so far
    cmd = re.split(" +", readline.get_line_buffer())

    if len(cmd) != 0 and cmd[0] in rline_mpstate.completions:
        # we have a completion rule for this command
        last_clist = complete_rules(rline_mpstate.completions[cmd[0]], cmd[1:])
    elif len(cmd) == 0 or len(cmd) == 1:
        # if on first part then complete on commands and aliases
        last_clist = complete_command(text) + complete_alias(text)
    else:
        # assume completion by filename
        last_clist = glob.glob(text + '*')
    ret = []
    for c in last_clist:
        if c.startswith(text) or c.startswith(text.upper()):
            ret.append(c)
    if len(ret) == 0:
        # if we had no matches then try case insensitively
        text = text.lower()
        for c in last_clist:
            if c.lower().startswith(text):
                ret.append(c)
    ret.append(None)
    last_clist = ret
    return last_clist[state]
Ejemplo n.º 3
0
    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
Ejemplo n.º 4
0
    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:
            # 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,
                        # 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(self, text, state):
        response = None
        if state == 0:
            # Questa è la prima volta per questo testo, quindi si costruisce
            # un elenco di corrispondenze

            origline = readline.get_line_buffer()
            begin = readline.get_begidx()
            end = readline.get_endidx()
            being_completed = origline[begin:end]
            words = origline.split()

            logging.debug('riga originale=%s', repr(origline))
            logging.debug('inizio=%s', begin)
            logging.debug('fine=%s', end)
            logging.debug('in completamento=%s', being_completed)
            logging.debug('parole=%s', words)

            if not words:
                self.current_candidates = sorted(self.options.keys())
            else:
                try:
                    if begin == 0:
                        # prima parola
                        candidates = self.options.keys()
                    else:
                        # parola ulteriore
                        first = words[0]
                        candidates = self.options[first]

                    if being_completed:
                        # cerca corrispondenza di opzioni con la
                        # porzione di input che si sta completando
                        self.current_candidates = [
                            w for w in candidates
                            if w.startswith(being_completed)
                        ]
                    else:
                        # corrispondenza con una stringa vuota,
                        # quindi si usano tutti i candidati
                        self.current_candidates = candidates

                    logging.debug('candidati=%s', self.current_candidates)

                except (KeyError, IndexError) as err:
                    logging.error('errore di completamento: %s', err)
                    self.current_candidates = []

        try:
            response = self.current_candidates[state]
        except IndexError:
            response = None
        logging.debug('completato(%s, %s) => %s', repr(text), state, response)
        return response
    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,
                        # 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
Ejemplo n.º 8
0
    def blank_readline(self):
        rows, cols = struct.unpack(
            'hh', fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234'))

        if cols == 0:
            cols = 80

        text_len = len(readline.get_line_buffer()) + 2
        sys.stdout.write('\x1b[2K')
        sys.stdout.write('\x1b[1A\x1b[2K' * (text_len / cols))
        sys.stdout.write('\x1b[0G')
Ejemplo n.º 9
0
    def blank_readline(self):
        rows, cols = struct.unpack('hh', fcntl.ioctl(
            sys.stdout, TIOCGWINSZ, '1234'))

        if cols == 0:
            cols = 80

        text_len = len(readline.get_line_buffer()) + 2
        sys.stdout.write('\x1b[2K')
        sys.stdout.write('\x1b[1A\x1b[2K' * int(text_len / cols))
        sys.stdout.write('\x1b[0G')
Ejemplo n.º 10
0
 def complete(self, text, state):
     "Generic readline completion entry point."
     buffer = gnureadline.get_line_buffer()
     line = gnureadline.get_line_buffer().split()
     # show all commands
     if not line:
         return [c + ' ' for c in self.commands][state]
     # account for last argument ending in a space
     if RE_SPACE.match(buffer):
         line.append('')
     # resolve command to the implementation function
     cmd = line[0].strip()
     if cmd in self.commands:
         impl = getattr(self, 'complete_%s' % cmd)
         args = line[1:]
         if args:
             return (impl(args) + [None])[state]
         return [cmd + ' '][state]
     results = [c + ' '
                for c in self.commands if c.startswith(cmd)] + [None]
     return results[state]
Ejemplo n.º 11
0
def test_subcommand_tab_completion_add_quote(sc_app):
    # This makes sure an opening quote is added to the readline line buffer
    text = 'Space'
    line = 'base sport {}'.format(text)
    endidx = len(line)
    begidx = endidx - len(text)

    first_match = complete_tester(text, line, begidx, endidx, sc_app)

    # No matches are returned when an opening quote is added to the screen
    assert first_match is None
    assert readline.get_line_buffer() == 'base sport "Space Ball" '
    def print_out(self, text, app_name=None, end=os.linesep):
        if not app_name:
            app_name = self._main_log_name

        if self._awaiting_input or self._attached_app:
            # We've printed a prompt - let's overwrite it.
            sys.stdout.write("{}{}".format(TERMINAL_CARRIAGE_RETURN, TERMINAL_ESCAPE_CLEAR_LINE))

        lines = self._get_cleaned_wrapped_and_styled_text(text, app_name)
        for i, line in enumerate(lines, start=1):
            # This should be the ONLY direct call to print - everything else should go through this `print_out`.
            print("{}{}".format(TERMINAL_CARRIAGE_RETURN, line), flush=True, end=end if i == len(lines) else os.linesep)

        # We cleared the prompt before displaying the log line; we should show the prompt (and any input) again.
        if not self._shutdown.is_set() and (self._attached_app or self._awaiting_input):
            sys.stdout.write("{} {}".format(self._prompt_string, readline.get_line_buffer()))
            sys.stdout.flush()
Ejemplo n.º 13
0
    def complete(self, text, state):
        tokens = shlex.split(readline.get_line_buffer(), posix=False)
        obj = self.get_relative_object(self.cwd, tokens)

        if issubclass(type(obj), Namespace):
            choices = [x.get_name() for x in obj.namespaces()] + \
                obj.commands().keys() + \
                self.builtin_commands.keys()
            choices = [i + ' ' for i in choices]

        elif issubclass(type(obj), Command):
            choices = obj.complete(self.context, tokens)

        else:
            choices = []

        options = [i for i in choices if i.startswith(text)]
        if state < len(options):
            return options[state]
        else:
            return None
Ejemplo n.º 14
0
    def complete(self, text, state):
        tokens = shlex.split(readline.get_line_buffer(), posix=False)
        obj = self.get_relative_object(self.cwd, tokens)

        if issubclass(type(obj), Namespace):
            choices = [x.get_name() for x in obj.namespaces()] + \
                obj.commands().keys() + \
                self.builtin_commands.keys()
            choices = [i + ' ' for i in choices]

        elif issubclass(type(obj), Command):
            choices = obj.complete(self.context, tokens)

        else:
            choices = []

        options = [i for i in choices if i.startswith(text)]
        if state < len(options):
            return options[state]
        else:
            return None
Ejemplo n.º 15
0
 def restore_readline(self):
     sys.stdout.write(self.__get_prompt() +
                      readline.get_line_buffer().rstrip())
     sys.stdout.flush()
Ejemplo n.º 16
0
 def restore_readline(self):
     if not self.skip_prompt_print:
         sys.stdout.write(self.__get_prompt() + readline.get_line_buffer().rstrip())
         sys.stdout.flush()
Ejemplo n.º 17
0
    def complete(self, text, state):
        readline_buffer = readline.get_line_buffer()
        tokens = shlex.split(readline_buffer.split('|')[-1].strip(), posix=False)

        if "|" in readline_buffer:
            choices = [x + ' ' for x in list(self.pipe_commands.keys())]
            options = [i for i in choices if i.startswith(text)]
            if state < len(options):
                return options[state]
            else:
                return None
        cwd = self.cwd

        if tokens:
            if tokens[0][0] == '/':
                cwd = self.root_path[0]

        obj = self.cached_values['obj']
        if (
            cwd != self.cached_values['rel_cwd'] or
            tokens != self.cached_values['rel_tokens'] or
            self.cached_values['obj'] is None
           ):
            obj = self.get_relative_object(cwd, tokens[:])
            self.cached_values.update({
                'rel_cwd': cwd,
                'rel_tokens': tokens,
                })

        if issubclass(type(obj), Namespace):
            if self.cached_values['obj'] != obj:
                obj_namespaces = obj.namespaces()
                new_choices = [x.get_name() for x in obj_namespaces] + list(obj.commands().keys())
                self.cached_values.update({
                    'obj': obj,
                    'choices': new_choices,
                    'obj_namespaces': obj_namespaces,
                })
            choices = self.cached_values['choices'][:]
            if (
                len(tokens) == 0 or
                (len(tokens) <= 1 and text not in ['', None])
               ):
                choices += list(self.base_builtin_commands.keys()) + ['..', '/', '-']
            elif 'help' not in choices:
                choices += ['help']
            choices = [i + ' ' for i in choices]

        elif issubclass(type(obj), Command):
            if (
                self.cached_values['obj'] != obj or
                self.cached_values['choices'] is None
               ):
                new_choices = obj.complete(self.context, tokens)
                self.cached_values.update({
                    'obj': obj,
                    'choices': new_choices,
                    'obj_namespaces': None,
                })
            choices = self.cached_values['choices'][:]
        else:
            choices = []

        options = [i for i in choices if i.startswith(text)]
        if state < len(options):
            return options[state]
        else:
            return None
Ejemplo n.º 18
0
 def emit_line(self, line):
     """Write string line to output without breaking input"""
     buf = readline.get_line_buffer()
     self.emit('\r', line, end='\n')
     self.emit(self.prompt, buf)