Python prompt_toolkit.completion.Completion() Examples

The following are 30 code examples of prompt_toolkit.completion.Completion(). 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: rpsgame.py    From python-for-absolute-beginners-course with MIT License 6 votes vote down vote up
def get_completions(self, document, complete_event):
        roll_names = list(rolls.keys())
        word = document.get_word_before_cursor()
        complete_all = not word if not word.strip() else word == '.'
        completions = []

        for roll in roll_names:
            is_substring = word in roll
            if complete_all or is_substring:

                completion = Completion(
                    roll,
                    start_position=-len(word),
                    style="fg:white bg:darkgreen",
                    selected_style="fg:yellow bg:green")

                completions.append(completion)

        return completions 
Example #2
Source File: test_smart_completion_public_schema_only.py    From litecli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_un_escaped_table_names(completer, complete_event):
    text = "SELECT  from réveillé"
    position = len("SELECT ")
    result = list(
        completer.get_completions(
            Document(text=text, cursor_position=position), complete_event
        )
    )
    assert result == list(
        [
            Completion(text="*", start_position=0),
            Completion(text="`ABC`", start_position=0),
            Completion(text="`insert`", start_position=0),
            Completion(text="id", start_position=0),
        ]
        + list(map(Completion, completer.functions))
        + [Completion(text="réveillé", start_position=0)]
        + list(map(Completion, sorted(completer.keywords)))
    ) 
Example #3
Source File: test_smart_completion_public_schema_only.py    From litecli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_suggested_column_names_with_table_dot(completer, complete_event):
    """Suggest column names on table name and dot.

    :param completer:
    :param complete_event:
    :return:

    """
    text = "SELECT users. from users"
    position = len("SELECT users.")
    result = list(
        completer.get_completions(
            Document(text=text, cursor_position=position), complete_event
        )
    )
    assert result == list(
        [
            Completion(text="*", start_position=0),
            Completion(text="email", start_position=0),
            Completion(text="first_name", start_position=0),
            Completion(text="id", start_position=0),
            Completion(text="last_name", start_position=0),
        ]
    ) 
Example #4
Source File: test_smart_completion_public_schema_only.py    From litecli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_auto_escaped_col_names(completer, complete_event):
    text = "SELECT  from `select`"
    position = len("SELECT ")
    result = list(
        completer.get_completions(
            Document(text=text, cursor_position=position), complete_event
        )
    )
    assert result == [
        Completion(text="*", start_position=0),
        Completion(text="`ABC`", start_position=0),
        Completion(text="`insert`", start_position=0),
        Completion(text="id", start_position=0),
    ] + list(map(Completion, completer.functions)) + [
        Completion(text="`select`", start_position=0)
    ] + list(
        map(Completion, sorted(completer.keywords))
    ) 
Example #5
Source File: test_smart_completion_public_schema_only.py    From litecli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_suggested_tables_after_on_right_side(completer, complete_event):
    text = "SELECT users.name, orders.id FROM users JOIN orders ON orders.user_id = "
    position = len(
        "SELECT users.name, orders.id FROM users JOIN orders ON orders.user_id = "
    )
    result = list(
        completer.get_completions(
            Document(text=text, cursor_position=position), complete_event
        )
    )
    assert list(result) == list(
        [
            Completion(text="orders", start_position=0),
            Completion(text="users", start_position=0),
        ]
    ) 
Example #6
Source File: test_smart_completion_public_schema_only.py    From litecli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_suggested_multiple_column_names_with_dot(completer, complete_event):
    """Suggest column names on table names and dot when selecting multiple
    columns from table.

    :param completer:
    :param complete_event:
    :return:

    """
    text = "SELECT users.id, users. from users u"
    position = len("SELECT users.id, users.")
    result = list(
        completer.get_completions(
            Document(text=text, cursor_position=position), complete_event
        )
    )
    assert result == list(
        [
            Completion(text="*", start_position=0),
            Completion(text="email", start_position=0),
            Completion(text="first_name", start_position=0),
            Completion(text="id", start_position=0),
            Completion(text="last_name", start_position=0),
        ]
    ) 
Example #7
Source File: test_smart_completion_public_schema_only.py    From litecli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_suggested_column_names_with_alias(completer, complete_event):
    """Suggest column names on table alias and dot.

    :param completer:
    :param complete_event:
    :return:

    """
    text = "SELECT u. from users u"
    position = len("SELECT u.")
    result = list(
        completer.get_completions(
            Document(text=text, cursor_position=position), complete_event
        )
    )
    assert result == list(
        [
            Completion(text="*", start_position=0),
            Completion(text="email", start_position=0),
            Completion(text="first_name", start_position=0),
            Completion(text="id", start_position=0),
            Completion(text="last_name", start_position=0),
        ]
    ) 
Example #8
Source File: test_smart_completion_public_schema_only.py    From litecli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_suggested_column_names_in_function(completer, complete_event):
    """Suggest column and function names when selecting multiple columns from
    table.

    :param completer:
    :param complete_event:
    :return:

    """
    text = "SELECT MAX( from users"
    position = len("SELECT MAX(")
    result = completer.get_completions(
        Document(text=text, cursor_position=position), complete_event
    )
    assert list(result) == list(
        [
            Completion(text="*", start_position=0),
            Completion(text="email", start_position=0),
            Completion(text="first_name", start_position=0),
            Completion(text="id", start_position=0),
            Completion(text="last_name", start_position=0),
        ]
    ) 
Example #9
Source File: ptk.py    From pyq with Apache License 2.0 6 votes vote down vote up
def get_completions(self, document, complete_event):
        """Yield completions"""
        # Detect a file handle
        m = HSYM_RE.match(document.text_before_cursor)
        if m:
            text = m.group(1)
            doc = Document(text, len(text))
            for c in self.path_completer.get_completions(doc, complete_event):
                yield c
        else:
            # Get word/text before cursor.
            word_before_cursor = document.get_word_before_cursor(False)
            for words, meta in self.words_info:
                for a in words:
                    if a.startswith(word_before_cursor):
                        yield Completion(a, -len(word_before_cursor),
                                         display_meta=meta) 
Example #10
Source File: completer.py    From contrail-api-cli with MIT License 6 votes vote down vote up
def get_option_value_completion(self, option, word_before_cursor):
        logger.debug('Complete option value')
        # complete choices
        if option.kwargs.get('choices'):
            logger.debug('Complete using choices %s' % option.kwargs['choices'])
            for choice in option.kwargs['choices']:
                yield Completion(choice,
                                 -len(word_before_cursor))
        # complete resources
        elif option.complete is not None:
            logger.debug('Complete using option matcher %s' % option.complete)
            completer_name = option.complete.split(':')[0]
            if completer_name in self.completers:
                for c in self.completers[completer_name].get_completions(word_before_cursor, self.context, option):
                    yield c
            else:
                logger.warning('No completer found for %s' % completer_name) 
Example #11
Source File: test_naive_completion.py    From pgcli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_alter_well_known_keywords_completion(completer, complete_event):
    text = "ALTER "
    position = len(text)
    result = completions_to_set(
        completer.get_completions(
            Document(text=text, cursor_position=position),
            complete_event,
            smart_completion=True,
        )
    )
    assert result > completions_to_set(
        [
            Completion(text="DATABASE", display_meta="keyword"),
            Completion(text="TABLE", display_meta="keyword"),
            Completion(text="SYSTEM", display_meta="keyword"),
        ]
    )
    assert (
        completions_to_set([Completion(text="CREATE", display_meta="keyword")])
        not in result
    ) 
Example #12
Source File: console.py    From brownie with MIT License 6 votes vote down vote up
def get_completions(self, document, complete_event):
        try:
            base, current = _parse_document(self.locals, document.text)

            if isinstance(base, dict):
                completions = sorted(base)
            else:
                completions = dir(base)
            if current:
                completions = [i for i in completions if i.startswith(current)]
            else:
                completions = [i for i in completions if not i.startswith("_")]
            for key in completions:
                yield Completion(key, start_position=-len(current))

        except Exception:
            return 
Example #13
Source File: test_smart_completion_public_schema_only.py    From litecli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_suggested_aliases_after_on_right_side(completer, complete_event):
    text = "SELECT u.name, o.id FROM users u JOIN orders o ON o.user_id = "
    position = len("SELECT u.name, o.id FROM users u JOIN orders o ON o.user_id = ")
    result = list(
        completer.get_completions(
            Document(text=text, cursor_position=position), complete_event
        )
    )
    assert result == list(
        [Completion(text="o", start_position=0), Completion(text="u", start_position=0)]
    ) 
Example #14
Source File: test_smart_completion_public_schema_only.py    From litecli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_suggested_aliases_after_on(completer, complete_event):
    text = "SELECT u.name, o.id FROM users u JOIN orders o ON "
    position = len("SELECT u.name, o.id FROM users u JOIN orders o ON ")
    result = list(
        completer.get_completions(
            Document(text=text, cursor_position=position), complete_event
        )
    )
    assert result == list(
        [Completion(text="o", start_position=0), Completion(text="u", start_position=0)]
    ) 
Example #15
Source File: test_smart_completion_public_schema_only.py    From litecli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_suggested_tables_after_on(completer, complete_event):
    text = "SELECT users.name, orders.id FROM users JOIN orders ON "
    position = len("SELECT users.name, orders.id FROM users JOIN orders ON ")
    result = list(
        completer.get_completions(
            Document(text=text, cursor_position=position), complete_event
        )
    )
    assert result == list(
        [
            Completion(text="orders", start_position=0),
            Completion(text="users", start_position=0),
        ]
    ) 
Example #16
Source File: completer.py    From kafka-shell with Apache License 2.0 5 votes vote down vote up
def yield_config_completer(self, word_after_key, document, completer_name):
        config_completer = get_completer(completer_name)["values"]
        valid_keys = self.get_valid_config_values(document, word_after_key, config_completer)
        descriptions = self.get_completer_descriptions(config_completer)
        for key in valid_keys:
            display_meta = self.get_display_meta(descriptions, key)
            yield Completion(key, start_position=-len(word_after_key), display_meta=display_meta) 
Example #17
Source File: resource.py    From contrail-api-cli with MIT License 5 votes vote down vote up
def get_completions(self, word_before_cursor, context, option=None):
        cache_type, type, attr = option.complete.split(':')

        if attr == 'path':
            path = context.current_path / word_before_cursor
            if type and path.base != type:
                raise StopIteration
        else:
            path = Path('/')
            if type:
                path = path / type
            path = path / word_before_cursor

        logger.debug('Search for %s' % path)
        results = getattr(self, 'search_' + cache_type)([text_type(path)])
        seen = set()
        for r in results:
            if (r.type, r.uuid) in seen:
                continue
            seen.add((r.type, r.uuid))
            if attr == 'path':
                value = text_type(r.path.relative_to(context.current_path))
            else:
                value = text_type(getattr(r, attr))
            if attr == 'fq_name':
                meta = r.uuid
            else:
                meta = text_type(r.fq_name)
            if value:
                yield Completion(value,
                                 -len(word_before_cursor),
                                 display_meta=meta) 
Example #18
Source File: manager.py    From contrail-api-cli with MIT License 5 votes vote down vote up
def get_completions(self, word_before_cursor, context, option=None):
        for cmd_name, cmd in self.list:
            if cmd_name.startswith(word_before_cursor):
                yield Completion(cmd_name,
                                 -len(word_before_cursor),
                                 display_meta=cmd.description) 
Example #19
Source File: completer.py    From kafka-shell with Apache License 2.0 5 votes vote down vote up
def yield_clusters(self, word_before_cursor):
        clusters = self.settings.user_config["clusters"].keys()
        valid_keys = self.fuzzy(word_before_cursor, clusters)
        for key in valid_keys:
            yield Completion(u"{0}".format(key), start_position=-len(word_before_cursor), display_meta=None)

    # descriptions 
Example #20
Source File: completer.py    From we-get with MIT License 5 votes vote down vote up
def get_completions(self, document, complete_event):
        """get_completion: main call from the abstract base class "Completer"
          in prompt_toolkit.
        """
        self.word_before_cursor = document.get_word_before_cursor(WORD=True)
        self.word_after_cursor = document.text_after_cursor

        if self.words_count(document.text) == 1:
            self.words = COMMANDS
        elif self.words_count(document.text) == 2:
            try:
                if COMMANDS[document.text[:-1].split()[0]][
                    'required_argument'
                ]:
                    self.words = self.torrents
                else:
                    self.words = list()
            except KeyError:
                self.words = list()
        elif self.words_count(document.text) == 3:
            self.words = self.word_command_flags(document.text)
        else:
            self.words = COMMANDS

        for word in self.words:
            if self.word_matches(word):
                yield Completion(word, -len(self.word_before_cursor)) 
Example #21
Source File: completer.py    From contrail-api-cli with MIT License 5 votes vote down vote up
def get_option_name_completion(self, word_before_cursor):
        logger.debug('Complete option names')
        for option in self.parser.available_options:
            option_name = option.short_name or option.long_name
            if word_before_cursor.startswith('--'):
                option_name = option.long_name
            if option_name.startswith(word_before_cursor):
                yield Completion(option_name,
                                 -len(word_before_cursor),
                                 display_meta=option.help) 
Example #22
Source File: panctl.py    From pantalaimon with Apache License 2.0 5 votes vote down vote up
def complete_rooms(self, pan_user, last_word, words):
        rooms = self.rooms[pan_user]
        compl_words = self.filter_words(list(rooms), last_word)

        for compl_word in compl_words:
            yield Completion(compl_word, -len(last_word))

        return "" 
Example #23
Source File: panctl.py    From pantalaimon with Apache License 2.0 5 votes vote down vote up
def complete_pan_users(self, last_word):
        servers = self.ctl.ListServers()
        users = [item[0] for sublist in servers.values() for item in sublist]
        compl_words = self.filter_words(users, last_word)

        for compl_word in compl_words:
            yield Completion(compl_word, -len(last_word)) 
Example #24
Source File: panctl.py    From pantalaimon with Apache License 2.0 5 votes vote down vote up
def complete_devices(self, last_word, pan_user, user_id):
        devices = self.devices.ListUserDevices(pan_user, user_id)
        device_ids = [device["device_id"] for device in devices]
        compl_words = self.filter_words(device_ids, last_word)

        for compl_word in compl_words:
            yield Completion(compl_word, -len(last_word))

        return "" 
Example #25
Source File: panctl.py    From pantalaimon with Apache License 2.0 5 votes vote down vote up
def complete_users(self, last_word, pan_user):
        devices = self.devices.List(pan_user)
        users = set(device["user_id"] for device in devices)
        compl_words = self.filter_words(users, last_word)

        for compl_word in compl_words:
            yield Completion(compl_word, -len(last_word))

        return "" 
Example #26
Source File: panctl.py    From pantalaimon with Apache License 2.0 5 votes vote down vote up
def complete_commands(self, last_word):
        """Complete the available commands."""
        compl_words = self.filter_words(self.commands, last_word)
        for compl_word in compl_words:
            yield Completion(compl_word, -len(last_word)) 
Example #27
Source File: PromptCompleter.py    From topydo with GNU General Public License v3.0 5 votes vote down vote up
def _completion_generator(self, p_word, is_first_word):
        candidates = super().get_completions(p_word, is_first_word)
        for candidate in candidates:
            yield Completion(candidate, -len(p_word)) 
Example #28
Source File: nested_completer.py    From msldap with MIT License 5 votes vote down vote up
def get_completions(self, document: Document,
                        complete_event: CompleteEvent) -> Iterable[Completion]:
        # Split document.
        text = document.text_before_cursor.lstrip()

        # If there is a space, check for the first term, and use a
        # subcompleter.
        if ' ' in text:
            first_term = text.split()[0]
            completer = self.options.get(first_term)

            # If we have a sub completer, use this for the completions.
            if completer is not None:
                remaining_text = document.text[len(first_term):].lstrip()
                move_cursor = len(document.text) - len(remaining_text)

                new_document = Document(
                    remaining_text,
                    cursor_position=document.cursor_position - move_cursor)

                for c in completer.get_completions(new_document, complete_event):
                    yield c

        # No space in the input: behave exactly like `WordCompleter`.
        else:
            completer = WordCompleter(list(self.options.keys()), ignore_case=self.ignore_case)
            for c in completer.get_completions(document, complete_event):
                yield c 
Example #29
Source File: repl.py    From crash with Apache License 2.0 5 votes vote down vote up
def get_completions(self, document, complete_event):
        if not self.cmd.should_autocomplete():
            return
        line = document.text
        word_before_cursor = document.get_word_before_cursor()
        if line.startswith('\\'):
            for w in self.get_command_completions(line):
                yield Completion(w, -len(word_before_cursor))
            return
        # start autocomplete on 3rd character for non-command keys
        if len(word_before_cursor) >= 3:
            for keyword in self.keywords:
                if keyword.startswith(word_before_cursor.lower()):
                    yield Completion(keyword.upper(), -len(word_before_cursor)) 
Example #30
Source File: sqlcompleter.py    From litecli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def find_files(self, word):
        """Yield matching directory or file names.

        :param word:
        :return: iterable

        """
        base_path, last_path, position = parse_path(word)
        paths = suggest_path(word)
        for name in sorted(paths):
            suggestion = complete_path(name, last_path)
            if suggestion:
                yield Completion(suggestion, position)