Python prompt_toolkit.completion.WordCompleter() Examples

The following are 24 code examples of prompt_toolkit.completion.WordCompleter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module prompt_toolkit.completion , or try the search function .
Example #1
Source File: prompt.py    From neo-python with MIT License 6 votes vote down vote up
def get_completer(self):
        standard_completions = list({word for d in self._command_descs for word in d.command.split()})  # Use a set to ensure unicity of words
        standard_completions += ['quit', 'help', 'exit']

        if PromptData.Wallet:
            for addr in PromptData.Wallet.Addresses:
                if addr not in self._known_things:
                    self._known_things.append(addr)
            for alias in PromptData.Wallet.NamedAddr:
                if alias.Title not in self._known_things:
                    self._known_things.append(alias.Title)
            for tkn in PromptData.Wallet.GetTokens().values():
                if tkn.symbol not in self._known_things:
                    self._known_things.append(tkn.symbol)

        all_completions = standard_completions + self._known_things

        PromptInterface.prompt_completer = WordCompleter(all_completions)

        return PromptInterface.prompt_completer 
Example #2
Source File: interface.py    From hermit with Apache License 2.0 6 votes vote down vote up
def choose_shard(self,
                     shards) -> Optional[str]:

        if len(shards) == 0:
            raise HermitError("Not enough shards to reconstruct secret.")

        shardnames = [shard.name for shard in shards]
        shardnames.sort()

        shardCompleter = WordCompleter(shardnames, sentence=True)

        while True:
            prompt_string = "Choose shard\n(options: {} or <enter> to quit)\n> "
            prompt_msg = prompt_string.format(", ".join(shardnames))
            shard_name = prompt(prompt_msg,
                                completer=shardCompleter,
                                **self.options).strip()

            if shard_name in shardnames:
                return shard_name

            if shard_name == '':
                return None

            print("Shard not found.") 
Example #3
Source File: toolbar.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def interact(connection):
    # When a client is connected, erase the screen from the client and say
    # Hello.
    connection.send("Welcome!\n")

    # Display prompt with bottom toolbar.
    animal_completer = WordCompleter(["alligator", "ant"])

    def get_toolbar():
        return "Bottom toolbar..."

    session = PromptSession()
    result = await session.prompt_async(
        "Say something: ", bottom_toolbar=get_toolbar, completer=animal_completer
    )

    connection.send("You said: {}\n".format(result))
    connection.send("Bye.\n") 
Example #4
Source File: interactive_release.py    From releases with Apache License 2.0 5 votes vote down vote up
def yes_no_prompt(title, default=True):
    result = prompt(title, completer=WordCompleter(['yes', 'no']),
                    validator=SetValidator(['yes', 'no'],
                                           show_possible=True),
                    default="yes" if default else "no")
    return result == 'yes' 
Example #5
Source File: CurseBreaker.py    From CurseBreaker with GNU General Public License v3.0 5 votes vote down vote up
def setup_completer(self):
        if not self.cfSlugs or not self.wowiSlugs:
            # noinspection PyBroadException
            try:
                self.cfSlugs = pickle.load(gzip.open(io.BytesIO(
                    requests.get('https://storage.googleapis.com/cursebreaker/cfslugs.pickle.gz',
                                 headers=HEADERS).content)))
                self.wowiSlugs = pickle.load(gzip.open(io.BytesIO(
                    requests.get('https://storage.googleapis.com/cursebreaker/wowislugs.pickle.gz',
                                 headers=HEADERS).content)))
            except Exception:
                self.cfSlugs = []
                self.wowiSlugs = []
        commands = ['install', 'uninstall', 'update', 'force_update', 'wa_update', 'status', 'orphans', 'search',
                    'import', 'export', 'toggle_backup', 'toggle_dev', 'toggle_wa', 'set_wa_api', 'set_wa_wow_account',
                    'uri_integration', 'help', 'exit']
        addons = sorted(self.core.config['Addons'], key=lambda k: k['Name'].lower())
        for addon in addons:
            name = f'"{addon["Name"]}"' if ',' in addon["Name"] else addon["Name"]
            commands.extend([f'uninstall {name}', f'update {name}', f'force_update {name}', f'toggle_dev {name}',
                             f'status {name}'])
        for item in self.cfSlugs:
            commands.append(f'install cf:{item}')
        for item in self.wowiSlugs:
            commands.append(f'install wowi:{item}')
        commands.extend(['install ElvUI', 'install ElvUI:Dev', 'install Tukui', 'install SLE:Dev', 'toggle_dev global'])
        accounts = self.core.detect_accounts()
        for account in accounts:
            commands.append(f'set_wa_wow_account {account}')
        self.completer = WordCompleter(commands, ignore_case=True, sentence=True) 
Example #6
Source File: completer.py    From pyvim with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_command_completer(editor):
    commands = [c + ' ' for c in get_commands()]

    return GrammarCompleter(COMMAND_GRAMMAR, {
        'command': WordCompleter(commands),
        'location': PathCompleter(expanduser=True),
        'set_option': WordCompleter(sorted(SET_COMMANDS)),
        'buffer_name': BufferNameCompleter(editor),
        'colorscheme': ColorSchemeCompleter(editor),
        'shell_command': SystemCompleter(),
    }) 
Example #7
Source File: card.py    From gtd.py with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def manipulate_attachments(self):
        '''Give the user a CRUD interface for attachments on this card'''
        print('Enter a URL, "delete", "open", or "print". Ctrl+D to exit')
        attachment_completer = WordCompleter(['delete', 'print', 'open', 'http://', 'https://'], ignore_case=True)
        while True:
            user_input = prompt('gtd.py > attach > ', completer=attachment_completer).strip()
            if re.search(VALID_URL_REGEX, user_input):
                # attach this link
                self.attach_url(user_input)
                print(f'Attached {user_input}')
            elif user_input in ['delete', 'open']:
                attachment_opts = {a['name']: a for a in self.fetch_attachments()}
                if not attachment_opts:
                    print('This card is free of attachments')
                    continue
                dest = single_select(attachment_opts.keys())
                if dest is not None:
                    target = attachment_opts[dest]
                    if user_input == 'delete':
                        self.remove_attachment(target['id'])
                        self.fetch_attachments(force=True)
                    elif user_input == 'open':
                        with DevNullRedirect():
                            webbrowser.open(target['url'])
            elif user_input == 'print':
                existing_attachments = self.fetch_attachments(force=True)
                if existing_attachments:
                    print('Attachments:')
                    for a in existing_attachments:
                        print('  ' + a['name']) 
Example #8
Source File: completer.py    From pymux with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        # Completer for full command names.
        self._command_completer = WordCompleter(
            sorted(COMMANDS_TO_HANDLERS.keys()),
            ignore_case=True, WORD=True, match_middle=True)

        # Completer for aliases.
        self._aliases_completer = WordCompleter(
            sorted(ALIASES.keys()),
            ignore_case=True, WORD=True, match_middle=True) 
Example #9
Source File: rpsgame.py    From python-for-absolute-beginners-course with MIT License 5 votes vote down vote up
def get_roll(player_name, roll_names):
    if os.environ.get('PYCHARM_HOSTED') == "1":
        print(Fore.LIGHTRED_EX + "Warning: Cannot use fancy prompt dialog in PyCharm.")
        print(Fore.LIGHTRED_EX + "Run this app outside of PyCharm to see it in action.")
        val = input(Fore.LIGHTYELLOW_EX + "What is your roll: ")
        print(Fore.WHITE)
        return val

    print(f"Available rolls: {', '.join(roll_names)}.")

    # word_comp = WordCompleter(roll_names)
    word_comp = PlayComplete()

    roll = prompt(f"{player_name}, what is your roll: ", completer=word_comp)

    if not roll or roll not in roll_names:
        print(f"Sorry {player_name}, {roll} not valid!")
        return None

    return roll


# def get_roll(player_name, roll_names):
#     print("Available rolls:")
#     for index, r in enumerate(roll_names, start=1):
#         print(f"{index}. {r}")
#
#     text = input(f"{player_name}, what is your roll? ")
#     selected_index = int(text) - 1
#
#     if selected_index < 0 or selected_index >= len(rolls):
#         print(f"Sorry {player_name}, {text} is out of bounds!")
#         return None
#
#     return roll_names[selected_index]
# 
Example #10
Source File: maininterface.py    From polymorph with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        """Runs the interface and waits for user input commands."""
        completer = WordCompleter(['capture', 'spoof', 'clear', 'import'])
        history = FileHistory(self._polym_path + '/.minterface_history')
        session = PromptSession(history=history)
        while True:
            try:
                command = session.prompt(HTML("<bold><red>PH</red> > </bold>"),
                                         completer=completer,
                                         complete_style=CompleteStyle.READLINE_LIKE,
                                         auto_suggest=AutoSuggestFromHistory(),
                                         enable_history_search=True)
            except KeyboardInterrupt:
                self.exit_program()
                continue
            command = command.split(" ")
            if command[0] in self.EXIT:
                self.exit_program()
            elif command[0] in ["capture", "c"]:
                self._capture(command)
            elif command[0] in ["spoof", "s"]:
                self._spoof(command)
            elif command[0] in ["import", "i"]:
                self._import(command)
            elif command[0] == "clear":
                Interface._clear()
            elif command[0] == "":
                continue
            else:
                Interface._wrong_command() 
Example #11
Source File: tlistinterface.py    From polymorph with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        """Runs the interface and waits for user input commands."""
        completer = WordCompleter(['show', 'dissect', 'template', 'wireshark',
                                   'clear', 'back'])
        history = FileHistory(self._polym_path + '/.tlinterface_history')
        session = PromptSession(history=history)
        while True:
            try:
                command = session.prompt(HTML("<bold>PH:<red>cap</red> > </bold>"),
                                         completer=completer,
                                         complete_style=CompleteStyle.READLINE_LIKE,
                                         auto_suggest=AutoSuggestFromHistory(),
                                         enable_history_search=True)
            except KeyboardInterrupt:
                self.exit_program()
                continue
            command = command.split(" ")
            if command[0] in self.EXIT:
                self.exit_program()
            elif command[0] in self.RET:
                break
            elif command[0] in ["show", "s"]:
                self._show(command)
            elif command[0] == "dissect":
                self._dissect(command)
            elif command[0] in ["template", "t"]:
                self._template(command)
            elif command[0] in ["wireshark", "w"]:
                self._wireshark(command)
            elif command[0] == "clear":
                Interface._clear()
            elif command[0] == "":
                continue
            else:
                Interface._wrong_command() 
Example #12
Source File: layerinterface.py    From polymorph with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        """Runs the interface and waits for user input commands."""
        completer = WordCompleter(['show', 'name', 'field', 'fields',
                                   'dump', 'recalculate', 'clear', 'back'])
        history = FileHistory(self._polym_path + '/.linterface_history')
        session = PromptSession(history=history)
        while True:
            try:
                command = session.prompt(HTML("<bold>PH:cap/t%d/<red>%s</red> > </bold>" %
                                              (self._tindex, self._l.name)),
                                         completer=completer,
                                         complete_style=CompleteStyle.READLINE_LIKE,
                                         auto_suggest=AutoSuggestFromHistory(),
                                         enable_history_search=True)
            except KeyboardInterrupt:
                self.exit_program()
                continue
            # Argument parsing
            command = command.split(" ")
            if command[0] in self.EXIT:
                self.exit_program()
            elif command[0] in self.RET:
                break
            elif command[0] in ["s", "show"]:
                self._show(command)
            elif command[0] == "name":
                self._name(command)
            elif command[0] in ["field", "f"]:
                self._field(command)
            elif command[0] in ["fields", "fs"]:
                self._fields(command)
            elif command[0] in ["dump", "d"]:
                self._dump(command)
            elif command[0] in ["recalculate", "r"]:
                self._recalculate(command)
            elif command[0] == "clear":
                Interface._clear()
            elif command[0] == "":
                continue
            else:
                Interface._wrong_command() 
Example #13
Source File: aiocmd.py    From msldap with MIT License 5 votes vote down vote up
def _completer_for_command(self, command):
        if not hasattr(self, "_%s_completions" % command):
            return WordCompleter([])
        return getattr(self, "_%s_completions" % command)() 
Example #14
Source File: example.py    From msldap with MIT License 5 votes vote down vote up
def _sleep_completions(self):
        return WordCompleter([str(i) for i in range(1, 60)]) 
Example #15
Source File: example.py    From msldap with MIT License 5 votes vote down vote up
def _add_completions(self):
        return WordCompleter([str(i) for i in range(9)]) 
Example #16
Source File: Exploiter.py    From drupwn with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request, logger, config):
        self.request = request
        self.config = config
        self.logger = logger
        self.cmds = {
            "exploit": self._exploit,
            "check": self._check,
            "list": self._list,
        }

        self.auto_cmds = WordCompleter(["quit", "list", "check", "exploit"], ignore_case=True)
        self.history = FileHistory('.drupwn-history')
        self._load() 
Example #17
Source File: prompt.py    From Pytify with MIT License 5 votes vote down vote up
def completer():
    s = set()

    history_strings = history().load_history_strings()

    for name in history_strings:
        s.add(name)

    return WordCompleter(list(s), ignore_case=True) 
Example #18
Source File: __init__.py    From asn1tools with MIT License 5 votes vote down vote up
def _do_shell(_args):
    commands = ['compile', 'convert', 'help', 'exit']
    completer = WordCompleter(commands, WORD=True)
    user_home = os.path.expanduser('~')
    history = FileHistory(os.path.join(user_home, '.asn1tools-history.txt'))
    session = PromptSession(completer=completer,
                            complete_while_typing=True,
                            auto_suggest=AutoSuggestFromHistory(),
                            enable_history_search=True,
                            history=history)
    input_spec = None
    output_spec = None
    output_codec = None

    print("\nWelcome to the asn1tools shell!\n")

    while True:
        try:
            line = session.prompt(u'$ ')
        except EOFError:
            return

        line = line.strip()

        if line:
            if line.startswith('compile'):
                input_spec, output_spec, output_codec = _handle_command_compile(line)
            elif line.startswith('convert'):
                _handle_command_convert(line,
                                        input_spec,
                                        output_spec,
                                        output_codec)
            elif line == 'help':
                _handle_command_help()
            elif line == 'exit':
                return
            else:
                print('{}: command not found'.format(line)) 
Example #19
Source File: templateinterface.py    From polymorph with GNU General Public License v2.0 4 votes vote down vote up
def run(self):
        """Runs the interface and waits for user input commands."""
        completer = WordCompleter(['show', 'name', 'layer', 'dump', 'layers',
                                   'preconditions', 'postconditions', 'executions',
                                   'intercept', 'timestamp', 'version', 'save',
                                   'description', 'spoof', 'clear', 'back'])
        # Initialization of the command history
        history = FileHistory(join(self._polym_path, '.tinterface_history'))
        session = PromptSession(history=history)
        while True:
            try:
                command = session.prompt(HTML("<bold>PH:cap/<red>t%d</red> > </bold>" %
                                              self._index),
                                         completer=completer,
                                         complete_style=CompleteStyle.READLINE_LIKE,
                                         auto_suggest=AutoSuggestFromHistory(),
                                         enable_history_search=True)
            except KeyboardInterrupt:
                self.exit_program()
                continue
            command = command.split(" ")
            if command[0] in self.EXIT:
                self.exit_program()
            elif command[0] in self.RET:
                break
            elif command[0] == "name":
                self._name(command)
            elif command[0] in ["dump", "d"]:
                self._dump(command)
            elif command[0] in ["layer", "l"]:
                self._layer(command)
            elif command[0] in ['precs', 'preconditions']:
                self._conditions(command, 'preconditions')
            elif command[0] in ['posts', 'postconditions']:
                self._conditions(command, 'postconditions')
            elif command[0] in ['execs', 'executions']:
                self._conditions(command, 'executions')
            elif command[0] in ["show", "s"]:
                self._show(command)
            elif command[0] in ["intercept", "i"]:
                self._intercept(command)
            elif command[0] in ["layers", "ls"]:
                self._layers(command)
            elif command[0] == "timestamp":
                print(self._t.timestamp, '\n')
            elif command[0] == "version":
                self._version(command)
            elif command[0] in ['desc', 'description']:
                self._description(command)
            elif command[0] == "save":
                self._save(command)
            elif command[0] in ["spoof"]:
                self._spoof(command)
            elif command[0] == "clear":
                Interface._clear()
            elif command[0] == "":
                continue
            else:
                Interface._wrong_command() 
Example #20
Source File: fieldinterface.py    From polymorph with GNU General Public License v2.0 4 votes vote down vote up
def run(self):
        """Runs the interface and waits for user input commands."""
        completer = WordCompleter(['value', 'type', 'show', 'name', 'slice',
                                   'custom', 'size', 'dump', 'clear', 'back'])
        history = FileHistory(self._polym_path + '/.finterface_history')
        session = PromptSession(history=history)
        while True:
            try:
                command = session.prompt(HTML("<bold>PH:cap/t%d/%s/<red>%s</red> > </bold>" %
                                              (self._tindex, self._lname, self._f.name)),
                                         completer=completer,
                                         complete_style=CompleteStyle.READLINE_LIKE,
                                         auto_suggest=AutoSuggestFromHistory(),
                                         enable_history_search=True)
            except KeyboardInterrupt:
                self.exit_program()
                continue
            command = command.split(" ")
            if command[0] in self.EXIT:
                self.exit_program()
            elif command[0] in self.RET:
                break
            elif command[0] in ['t', 'type']:
                self._type(command)
            elif command[0] in ['v', 'value']:
                self._value(command)
            elif command[0] in ['s', 'show']:
                self._show(command)
            elif command[0] == 'name':
                self._name(command)
            elif command[0] == "slice":
                print(self._f.slice, '\n')
            elif command[0] == "custom":
                self._custom(command)
            elif command[0] == "size":
                print(self._f.size, '\n')
            elif command[0] in ['d', 'dump']:
                Interface.color_dump(self._f.raw,
                                     self._f.slice.start,
                                     self._f.slice.stop)
            elif command[0] == "clear":
                Interface._clear()
            elif command[0] == "":
                continue
            else:
                Interface._wrong_command() 
Example #21
Source File: completer.py    From pymux with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get_completions_for_parts(parts, last_part, complete_event, pymux):
    completer = None

    # Resolve aliases.
    if len(parts) > 0:
        parts = [ALIASES.get(parts[0], parts[0])] + parts[1:]

    if len(parts) == 0:
        # New command.
        completer = _command_completer

    elif len(parts) >= 1 and last_part.startswith('-'):
        flags = get_option_flags_for_command(parts[0])
        completer = WordCompleter(sorted(flags), WORD=True)

    elif len(parts) == 1 and parts[0] in ('set-option', 'set-window-option'):
        options = pymux.options if parts[0] == 'set-option' else pymux.window_options

        completer = WordCompleter(sorted(options.keys()), sentence=True)

    elif len(parts) == 2 and parts[0] in ('set-option', 'set-window-option'):
        options = pymux.options if parts[0] == 'set-option' else pymux.window_options

        option = options.get(parts[1])
        if option:
            completer = WordCompleter(sorted(option.get_all_values(pymux)), sentence=True)

    elif len(parts) == 1 and parts[0] == 'select-layout':
        completer = _layout_type_completer

    elif len(parts) == 1 and parts[0] == 'send-keys':
        completer = _keys_completer

    elif parts[0] == 'bind-key':
        if len(parts) == 1:
            completer = _keys_completer

        elif len(parts) == 2:
            completer = _command_completer

    # Recursive, for bind-key options.
    if parts and parts[0] == 'bind-key' and len(parts) > 2:
        for c in get_completions_for_parts(parts[2:], last_part, complete_event, pymux):
            yield c

    if completer:
        for c in completer.get_completions(Document(last_part), complete_event):
            yield c 
Example #22
Source File: repl.py    From hermit with Apache License 2.0 4 votes vote down vote up
def repl(commands:Dict, mode="", help_command=None):
    commandCompleter = WordCompleter(
        [c for c in commands],
        sentence=True # allows hyphens
    )

    oldSession = state.Session
    state.Session = PromptSession(key_bindings=Bindings,
                            bottom_toolbar=bottom_toolbar,
                            refresh_interval=0.1)
    state.Wallet.shards.interface.options = {'bottom_toolbar': bottom_toolbar}
    done = None
    with patch_stdout():
        while not done:
            try:
                unlocked = ' '
                if state.Wallet.unlocked():
                    unlocked = '*'
                command_line = state.Session.prompt(HTML('<b>{}{}></b> '.format(unlocked, mode)),
                                              completer=commandCompleter,
                                              ).split()

                if len(command_line) == 0:
                    continue

                if command_line[0] in commands:
                    command_fn = commands[command_line[0]]
                    try:
                        done = command_fn(*(command_line[1:]))
                    except TypeError as err:
                        if state.Debug:
                            raise err
                        if help_command is not None:
                            help_command(command_line[0])
                else:
                    raise HermitError("Unknown command")

            except KeyboardInterrupt:
                continue
            except HermitError as e:
                print(e)
                if state.Debug:
                    traceback.print_exc()
                continue
            except EOFError:
                break
            except Exception as err:
                print(err)
                if state.Debug:
                    traceback.print_exc()
                break
    state.Session = oldSession 
Example #23
Source File: end_combat.py    From dndme with MIT License 4 votes vote down vote up
def do_command(self, *args):
        combat = self.game.combat
        if not combat.tm:
            print("Combat hasn't started yet.")
            return

        cur_turn = combat.tm.cur_turn

        combat.tm = None
        Show.show_defeated(self)
        combat.defeated = []

        # Allow some leftover monsters to remain in the combat group;
        # perhaps some are friendly NPCs along for the ride?
        choices = WordCompleter(['keep', 'remove', 'stash'])
        for monster in list(combat.monsters.values()):
            choice = self.session.prompt(
                f"What should we do with {monster.name}? "
                "[R]emove [S]tash [K]eep (default: Keep) ",
                completer=choices
            ).lower()
            if choice in ('r', 'remove'):
                RemoveCombatant.do_command(self, monster.name)
            elif choice in ('s', 'stash'):
                StashCombatant.do_command(self, monster.name)
            else:
                print(f"Okay, keeping {monster.name}")

        if cur_turn:
            rounds = cur_turn[0]
            duration_sec = cur_turn[0] * 6
        else:
            rounds = 0
            duration_sec = 0

        if duration_sec > 60:
            duration = f"{duration_sec // 60} min {duration_sec % 60} sec"
        else:
            duration = f"{duration_sec} sec"

        print(f"Combat ended in {rounds} rounds ({duration})")

        self.game.clock.adjust_time(minutes=math.ceil(duration_sec / 60))
        print(f"Game time is now {self.game.clock}")

        self.game.changed = True 
Example #24
Source File: console.py    From gsheets-db-api with MIT License 4 votes vote down vote up
def main():
    history = FileHistory(os.path.expanduser('~/.gsheetsdb_history'))

    arguments = docopt(__doc__, version=__version__.__version__)

    auth = {
        'service_account_file': arguments['--service-account-file'],
        'subject': arguments['--subject'],
    }
    credentials = get_credentials_from_auth(**auth)
    connection = connect(credentials)
    headers = int(arguments['--headers'])
    cursor = connection.cursor()

    lexer = PygmentsLexer(SqlLexer)
    words = keywords + aggregate_functions + scalar_functions
    completer = WordCompleter(words, ignore_case=True)
    style = style_from_pygments_cls(get_style_by_name('manni'))

    while True:
        try:
            query = prompt(
                'sql> ', lexer=lexer, completer=completer,
                style=style, history=history)
        except (EOFError, KeyboardInterrupt):
            break  # Control-D pressed.

        # run query
        query = query.strip('; ').replace('%', '%%')
        if query:
            try:
                result = cursor.execute(query, headers=headers)
            except Exception as e:
                if arguments['--raise']:
                    raise
                print(e)
                continue

            columns = [t[0] for t in cursor.description or []]
            print(tabulate(result, headers=columns))

    print('See ya!')