Python prompt_toolkit.completion.Completer() Examples

The following are 13 code examples of prompt_toolkit.completion.Completer(). 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: test_regular_languages.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_completer():
    class completer1(Completer):
        def get_completions(self, document, complete_event):
            yield Completion("before-%s-after" % document.text, -len(document.text))
            yield Completion("before-%s-after-B" % document.text, -len(document.text))

    class completer2(Completer):
        def get_completions(self, document, complete_event):
            yield Completion("before2-%s-after2" % document.text, -len(document.text))
            yield Completion("before2-%s-after2-B" % document.text, -len(document.text))

    # Create grammar.  "var1" + "whitespace" + "var2"
    g = compile(r"(?P<var1>[a-z]*) \s+ (?P<var2>[a-z]*)")

    # Test 'get_completions()'
    completer = GrammarCompleter(g, {"var1": completer1(), "var2": completer2()})
    completions = list(
        completer.get_completions(Document("abc def", len("abc def")), CompleteEvent())
    )

    assert len(completions) == 2
    assert completions[0].text == "before2-def-after2"
    assert completions[0].start_position == -3
    assert completions[1].text == "before2-def-after2-B"
    assert completions[1].start_position == -3 
Example #2
Source File: hummingbot_cli.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 input_handler: Callable,
                 bindings: KeyBindings,
                 completer: Completer):
        self.search_field = create_search_field()
        self.input_field = create_input_field(completer=completer)
        self.output_field = create_output_field()
        self.log_field = create_log_field(self.search_field)
        self.layout = generate_layout(self.input_field, self.output_field, self.log_field, self.search_field)
        # add self.to_stop_config to know if cancel is triggered
        self.to_stop_config: bool = False

        self.bindings = bindings
        self.input_handler = input_handler
        self.input_field.accept_handler = self.accept
        self.app = Application(layout=self.layout, full_screen=True, key_bindings=self.bindings, style=load_style(),
                               mouse_support=True, clipboard=PyperclipClipboard())

        # settings
        self.prompt_text = ">>> "
        self.pending_input = None
        self.input_event = None
        self.hide_input = False 
Example #3
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 #4
Source File: nested_completer.py    From msldap with MIT License 5 votes vote down vote up
def __init__(self, options: Dict[str, Optional[Completer]],
                 ignore_case: bool = True) -> None:

        self.options = options
        self.ignore_case = ignore_case 
Example #5
Source File: nested_completer.py    From msldap with MIT License 5 votes vote down vote up
def from_nested_dict(cls, data: NestedDict) -> 'NestedCompleter':
        """
        Create a `NestedCompleter`, starting from a nested dictionary data
        structure, like this:
        .. code::
            data = {
                'show': {
                    'version': None,
                    'interfaces': None,
                    'clock': None,
                    'ip': {'interface': {'brief'}}
                },
                'exit': None
                'enable': None
            }
        The value should be `None` if there is no further completion at some
        point. If all values in the dictionary are None, it is also possible to
        use a set instead.
        Values in this data structure can be a completers as well.
        """
        options = {}
        for key, value in data.items():
            if isinstance(value, Completer):
                options[key] = value
            elif isinstance(value, dict):
                options[key] = cls.from_nested_dict(value)
            elif isinstance(value, set):
                options[key] = cls.from_nested_dict({item: None for item in value})
            else:
                assert value is None
                options[key] = None

        return cls(options) 
Example #6
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 #7
Source File: nested.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(
        self, options: Dict[str, Optional[Completer]], ignore_case: bool = True
    ) -> None:

        self.options = options
        self.ignore_case = ignore_case 
Example #8
Source File: nested.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def from_nested_dict(cls, data: NestedDict) -> "NestedCompleter":
        """
        Create a `NestedCompleter`, starting from a nested dictionary data
        structure, like this:

        .. code::

            data = {
                'show': {
                    'version': None,
                    'interfaces': None,
                    'clock': None,
                    'ip': {'interface': {'brief'}}
                },
                'exit': None
                'enable': None
            }

        The value should be `None` if there is no further completion at some
        point. If all values in the dictionary are None, it is also possible to
        use a set instead.

        Values in this data structure can be a completers as well.
        """
        options: Dict[str, Optional[Completer]] = {}
        for key, value in data.items():
            if isinstance(value, Completer):
                options[key] = value
            elif isinstance(value, dict):
                options[key] = cls.from_nested_dict(value)
            elif isinstance(value, set):
                options[key] = cls.from_nested_dict({item: None for item in value})
            else:
                assert value is None
                options[key] = None

        return cls(options) 
Example #9
Source File: dialogs.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def input_dialog(
    title: AnyFormattedText = "",
    text: AnyFormattedText = "",
    ok_text: str = "OK",
    cancel_text: str = "Cancel",
    completer: Optional[Completer] = None,
    password: FilterOrBool = False,
    style: Optional[BaseStyle] = None,
) -> Application[str]:
    """
    Display a text input box.
    Return the given text, or None when cancelled.
    """

    def accept(buf: Buffer) -> bool:
        get_app().layout.focus(ok_button)
        return True  # Keep text.

    def ok_handler() -> None:
        get_app().exit(result=textfield.text)

    ok_button = Button(text=ok_text, handler=ok_handler)
    cancel_button = Button(text=cancel_text, handler=_return_none)

    textfield = TextArea(
        multiline=False, password=password, completer=completer, accept_handler=accept
    )

    dialog = Dialog(
        title=title,
        body=HSplit(
            [Label(text=text, dont_extend_height=True), textfield,],
            padding=D(preferred=1, max=1),
        ),
        buttons=[ok_button, cancel_button],
        with_background=True,
    )

    return _create_app(dialog, style) 
Example #10
Source File: completion.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(
        self, compiled_grammar: _CompiledGrammar, completers: Dict[str, Completer]
    ) -> None:

        self.compiled_grammar = compiled_grammar
        self.completers = completers 
Example #11
Source File: completers.py    From vexbot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, command_completer: Completer):
        self._command_completer = command_completer
        self.service_command_map = {} 
Example #12
Source File: completers.py    From vexbot with GNU General Public License v3.0 5 votes vote down vote up
def set_service_completer(self, service: str, completer: Completer):
        self.service_command_map[service] = completer 
Example #13
Source File: layout.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def create_input_field(lexer=None, completer: Completer = None):
    return TextArea(
        height=10,
        prompt='>>> ',
        style='class:input-field',
        multiline=False,
        focus_on_click=True,
        lexer=lexer,
        auto_suggest=AutoSuggestFromHistory(),
        completer=completer,
        complete_while_typing=True,
    )