Python prompt_toolkit.key_binding.KeyBindings() Examples

The following are 19 code examples of prompt_toolkit.key_binding.KeyBindings(). 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.key_binding , or try the search function .
Example #1
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 #2
Source File: bindings.py    From kafka-shell with Apache License 2.0 6 votes vote down vote up
def get_bindings(settings):
    bindings = KeyBindings()

    @bindings.add(Keys.F2)
    def _(event):
        settings.set_next_cluster()

    @bindings.add(Keys.F3)
    def _(event):
        settings.set_enable_fuzzy_search(not settings.enable_fuzzy_search)

    @bindings.add(Keys.F9)
    def _(event):
        settings.set_enable_help(not settings.enable_help)

    @bindings.add(Keys.F10)
    def _(event):
        current.get_app().exit(exception=EOFError)

    return bindings 
Example #3
Source File: dummy.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_dummy_layout() -> Layout:
    """
    Create a dummy layout for use in an 'Application' that doesn't have a
    layout specified. When ENTER is pressed, the application quits.
    """
    kb = KeyBindings()

    @kb.add("enter")
    def enter(event: E) -> None:
        event.app.exit()

    control = FormattedTextControl(
        HTML("No layout specified. Press <reverse>ENTER</reverse> to quit."),
        key_bindings=kb,
    )
    window = Window(content=control, height=D(min=1))
    return Layout(container=window, focused_element=window) 
Example #4
Source File: key_bindings.py    From pymux with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, pymux):
        self.pymux = pymux

        def get_search_state():
            " Return the currently active SearchState. (The one for the focused pane.) "
            return pymux.arrangement.get_active_pane().search_state

        self.custom_key_bindings = KeyBindings()

        self.key_bindings = merge_key_bindings([
            self._load_builtins(),
            self.custom_key_bindings,
        ])

        self._prefix = ('c-b', )
        self._prefix_binding = None

        # Load initial bindings.
        self._load_prefix_binding()

        # Custom user configured key bindings.
        # { (needs_prefix, key) -> (command, handler) }
        self.custom_bindings = {} 
Example #5
Source File: switch-between-vi-emacs.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run():
    # Create a `KeyBindings` that contains the default key bindings.
    bindings = KeyBindings()

    # Add an additional key binding for toggling this flag.
    @bindings.add("f4")
    def _(event):
        " Toggle between Emacs and Vi mode. "
        if event.app.editing_mode == EditingMode.VI:
            event.app.editing_mode = EditingMode.EMACS
        else:
            event.app.editing_mode = EditingMode.VI

    def bottom_toolbar():
        " Display the current input mode. "
        if get_app().editing_mode == EditingMode.VI:
            return " [F4] Vi "
        else:
            return " [F4] Emacs "

    prompt("> ", key_bindings=bindings, bottom_toolbar=bottom_toolbar) 
Example #6
Source File: autocorrection.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    # We start with a `KeyBindings` for our extra key bindings.
    bindings = KeyBindings()

    # We add a custom key binding to space.
    @bindings.add(" ")
    def _(event):
        """
        When space is pressed, we check the word before the cursor, and
        autocorrect that.
        """
        b = event.app.current_buffer
        w = b.document.get_word_before_cursor()

        if w is not None:
            if w in corrections:
                b.delete_before_cursor(count=len(w))
                b.insert_text(corrections[w])

        b.insert_text(" ")

    # Read input.
    text = prompt("Say something: ", key_bindings=bindings)
    print("You said: %s" % text) 
Example #7
Source File: base.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_key_bindings() -> KeyBindings:
    """
    Key bindings handled by the progress bar.
    (The main thread is not supposed to handle any key bindings.)
    """
    kb = KeyBindings()

    @kb.add("c-l")
    def _clear(event: E) -> None:
        event.app.renderer.clear()

    @kb.add("c-c")
    def _interrupt(event: E) -> None:
        # Send KeyboardInterrupt to the main thread.
        os.kill(os.getpid(), signal.SIGINT)

    return kb 
Example #8
Source File: key_bindings.py    From ptpython with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_confirm_exit_bindings(python_input):
    """
    Handle yes/no key presses when the exit confirmation is shown.
    """
    bindings = KeyBindings()

    handle = bindings.add
    confirmation_visible = Condition(lambda: python_input.show_exit_confirmation)

    @handle("y", filter=confirmation_visible)
    @handle("Y", filter=confirmation_visible)
    @handle("enter", filter=confirmation_visible)
    @handle("c-d", filter=confirmation_visible)
    def _(event):
        """
        Really quit.
        """
        event.app.exit(exception=EOFError, style="class:exiting")

    @handle(Keys.Any, filter=confirmation_visible)
    def _(event):
        """
        Cancel exit.
        """
        python_input.show_exit_confirmation = False

    return bindings 
Example #9
Source File: aiocmd.py    From msldap with MIT License 5 votes vote down vote up
def _get_bindings(self):
        bindings = KeyBindings()
        bindings.add("c-c")(lambda event: self._interrupt_handler(event))
        return bindings 
Example #10
Source File: test_keybinding.py    From crash with Apache License 2.0 5 votes vote down vote up
def test_bindings(self):
        kb = KeyBindings()
        bind_keys(Buffer(), kb)

        self.assertTrue('on_backspace' in handlers_for_key(kb, Keys.Backspace))
        self.assertTrue('on_tab' in handlers_for_key(kb, Keys.Tab)) 
Example #11
Source File: custom-key-bindings.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    bottom_toolbar = HTML(
        ' <b>[f]</b> Print "f" <b>[q]</b> Abort  <b>[x]</b> Send Control-C.'
    )

    # Create custom key bindings first.
    kb = KeyBindings()
    cancel = [False]

    @kb.add("f")
    def _(event):
        print("You pressed `f`.")

    @kb.add("q")
    def _(event):
        " Quit by setting cancel flag. "
        cancel[0] = True

    @kb.add("x")
    def _(event):
        " Quit by sending SIGINT to the main thread. "
        os.kill(os.getpid(), signal.SIGINT)

    # Use `patch_stdout`, to make sure that prints go above the
    # application.
    with patch_stdout():
        with ProgressBar(key_bindings=kb, bottom_toolbar=bottom_toolbar) as pb:
            for i in pb(range(800)):
                time.sleep(0.01)

                if cancel[0]:
                    break 
Example #12
Source File: base.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_key_bindings(self) -> KeyBindings:
        return self._key_bindings 
Example #13
Source File: base.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(
        self,
        title: AnyFormattedText = None,
        formatters: Optional[Sequence[Formatter]] = None,
        bottom_toolbar: AnyFormattedText = None,
        style: Optional[BaseStyle] = None,
        key_bindings: Optional[KeyBindings] = None,
        file: Optional[TextIO] = None,
        color_depth: Optional[ColorDepth] = None,
        output: Optional[Output] = None,
        input: Optional[Input] = None,
    ) -> None:

        self.title = title
        self.formatters = formatters or create_default_formatters()
        self.bottom_toolbar = bottom_toolbar
        self.counters: List[ProgressBarCounter[object]] = []
        self.style = style
        self.key_bindings = key_bindings

        # Note that we use __stderr__ as default error output, because that
        # works best with `patch_stdout`.
        self.color_depth = color_depth
        self.output = output or get_app_session().output
        self.input = input or get_app_session().input

        self._thread: Optional[threading.Thread] = None

        self._loop = get_event_loop()
        self._app_loop = new_event_loop()

        self._previous_winch_handler = None
        self._has_sigwinch = False

        if TYPE_CHECKING:
            # Infer type from getsignal result, as defined in typeshed. Too
            # complex to repeat here.
            self._previous_winch_handler = signal.getsignal(_SIGWINCH) 
Example #14
Source File: get-password-with-toggle-display-shortcut.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    hidden = [True]  # Nonlocal
    bindings = KeyBindings()

    @bindings.add("c-t")
    def _(event):
        " When ControlT has been pressed, toggle visibility. "
        hidden[0] = not hidden[0]

    print("Type Control-T to toggle password visible.")
    password = prompt(
        "Password: ", is_password=Condition(lambda: hidden[0]), key_bindings=bindings
    )
    print("You said: %s" % password) 
Example #15
Source File: custom-key-binding.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def main():
    # We start with a `KeyBindings` of default key bindings.
    bindings = KeyBindings()

    # Add our own key binding.
    @bindings.add("f4")
    def _(event):
        """
        When F4 has been pressed. Insert "hello world" as text.
        """
        event.app.current_buffer.insert_text("hello world")

    @bindings.add("x", "y")
    def _(event):
        """
        (Useless, but for demoing.)
        Typing 'xy' will insert 'z'.

        Note that when you type for instance 'xa', the insertion of 'x' is
        postponed until the 'a' is typed. because we don't know earlier whether
        or not a 'y' will follow. However, prompt-toolkit should already give
        some visual feedback of the typed character.
        """
        event.app.current_buffer.insert_text("z")

    @bindings.add("a", "b", "c")
    def _(event):
        " Typing 'abc' should insert 'd'. "
        event.app.current_buffer.insert_text("d")

    @bindings.add("c-t")
    def _(event):
        """
        Print 'hello world' in the terminal when ControlT is pressed.

        We use ``run_in_terminal``, because that ensures that the prompt is
        hidden right before ``print_hello`` gets executed and it's drawn again
        after it. (Otherwise this would destroy the output.)
        """

        def print_hello():
            print("hello world")

        run_in_terminal(print_hello)

    # Read input.
    print('Press F4 to insert "hello world", type "xy" to insert "z":')
    text = prompt("> ", key_bindings=bindings)
    print("You said: %s" % text) 
Example #16
Source File: custom-vi-operator-and-text-object.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def main():
    # We start with a `Registry` of default key bindings.
    bindings = KeyBindings()

    # Create the decorators to be used for registering text objects and
    # operators in this registry.
    operator = create_operator_decorator(bindings)
    text_object = create_text_object_decorator(bindings)

    # Create a custom operator.

    @operator("R")
    def _(event, text_object):
        " Custom operator that reverses text. "
        buff = event.current_buffer

        # Get relative start/end coordinates.
        start, end = text_object.operator_range(buff.document)
        start += buff.cursor_position
        end += buff.cursor_position

        text = buff.text[start:end]
        text = "".join(reversed(text))

        event.app.current_buffer.text = buff.text[:start] + text + buff.text[end:]

    # Create a text object.

    @text_object("A")
    def _(event):
        " A custom text object that involves everything. "
        # Note that a `TextObject` has coordinates, relative to the cursor position.
        buff = event.current_buffer
        return TextObject(
            -buff.document.cursor_position,  # The start.
            len(buff.text) - buff.document.cursor_position,
        )  # The end.

    # Read input.
    print('There is a custom text object "A" that applies to everything')
    print('and a custom operator "r" that reverses the text object.\n')

    print("Things that are possible:")
    print("-  Riw    - reverse inner word.")
    print("-  yA     - yank everything.")
    print("-  RA     - reverse everything.")

    text = prompt(
        "> ", default="hello world", key_bindings=bindings, editing_mode=EditingMode.VI
    )
    print("You said: %s" % text) 
Example #17
Source File: __init__.py    From edgedb with Apache License 2.0 4 votes vote down vote up
def build_propmpt(self) -> pt_shortcuts.PromptSession:
        history = pt_history.FileHistory(
            os.path.expanduser('~/.edgedbhistory'))

        bindings = pt_key_binding.KeyBindings()
        handle = bindings.add

        @handle('f3')  # type: ignore
        def _mode_toggle(event: Any) -> None:
            self.context.toggle_query_mode()

        @handle('f4')  # type: ignore
        def _implicit_toggle(event: Any) -> None:
            self.context.toggle_implicit()

        @handle('f5')  # type: ignore
        def _introspect_toggle(event: Any) -> None:
            self.context.toggle_introspect_types()

            if self.context.introspect_types:
                self.ensure_connection()
                self.introspect_db(self.connection)
            else:
                self.context.typenames = None

        @handle('tab')  # type: ignore
        def _tab(event: Any) -> None:
            b = prompt.app.current_buffer
            before_cursor = b.document.current_line_before_cursor
            if b.text and (not before_cursor or before_cursor.isspace()):
                b.insert_text('    ')

        prompt = pt_shortcuts.PromptSession(
            lexer=pt_lexers.PygmentsLexer(eql_pygments.EdgeQLLexer),
            include_default_pygments_style=False,

            completer=pt_complete.DummyCompleter(),
            reserve_space_for_menu=6,

            message=self.get_prompt_tokens,
            prompt_continuation=self.get_continuation_tokens,
            bottom_toolbar=self.get_toolbar_tokens,
            multiline=is_multiline,
            history=history,
            complete_while_typing=pt_filters.Always(),
            key_bindings=bindings,
            style=self.style,
            editing_mode=pt_enums.EditingMode.VI,
            search_ignore_case=True,
        )

        return prompt 
Example #18
Source File: repl.py    From crash with Apache License 2.0 4 votes vote down vote up
def loop(cmd, history_file):
    buf = create_buffer(cmd, history_file)
    key_bindings = KeyBindings()
    bind_keys(buf, key_bindings)
    layout = create_layout(
        buffer=buf,
        multiline=True,
        lexer=PostgresLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ],
        get_bottom_toolbar_tokens=lambda: get_toolbar_tokens(cmd),
        get_prompt_tokens=lambda: [('class:prompt', 'cr> ')]
    )
    output = get_default_output()
    app = Application(
        layout=layout,
        style=style_from_pygments_cls(CrateStyle),
        key_bindings=merge_key_bindings([
            key_bindings,
            load_open_in_editor_bindings()
        ]),
        editing_mode=_get_editing_mode(),
        output=output
    )
    cmd.get_num_columns = lambda: output.get_size().columns

    while True:
        try:
            text = app.run()
            if text:
                cmd.process(text)
            buf.reset()
        except ProgrammingError as e:
            if '401' in e.message:
                username = cmd.username
                password = cmd.password
                cmd.username = input('Username: ')
                cmd.password = getpass()
                try:
                    cmd.process(text)
                except ProgrammingError as ex:
                    # fallback to existing user/pw
                    cmd.username = username
                    cmd.password = password
                    cmd.logger.warn(str(ex))
            else:
                cmd.logger.warn(str(e))
        except KeyboardInterrupt:
            if isinstance(app.layout.current_control, SearchBufferControl):
                app.layout.current_control = app.layout.previous_control
            else:
                cmd.logger.warn("Query not cancelled. Run KILL <jobId> to cancel it")
                buf.reset()
        except EOFError:
            cmd.logger.warn('Bye!')
            return 
Example #19
Source File: key_bindings.py    From ptpython with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def load_sidebar_bindings(python_input):
    """
    Load bindings for the navigation in the sidebar.
    """
    bindings = KeyBindings()

    handle = bindings.add
    sidebar_visible = Condition(lambda: python_input.show_sidebar)

    @handle("up", filter=sidebar_visible)
    @handle("c-p", filter=sidebar_visible)
    @handle("k", filter=sidebar_visible)
    def _(event):
        " Go to previous option. "
        python_input.selected_option_index = (
            python_input.selected_option_index - 1
        ) % python_input.option_count

    @handle("down", filter=sidebar_visible)
    @handle("c-n", filter=sidebar_visible)
    @handle("j", filter=sidebar_visible)
    def _(event):
        " Go to next option. "
        python_input.selected_option_index = (
            python_input.selected_option_index + 1
        ) % python_input.option_count

    @handle("right", filter=sidebar_visible)
    @handle("l", filter=sidebar_visible)
    @handle(" ", filter=sidebar_visible)
    def _(event):
        " Select next value for current option. "
        option = python_input.selected_option
        option.activate_next()

    @handle("left", filter=sidebar_visible)
    @handle("h", filter=sidebar_visible)
    def _(event):
        " Select previous value for current option. "
        option = python_input.selected_option
        option.activate_previous()

    @handle("c-c", filter=sidebar_visible)
    @handle("c-d", filter=sidebar_visible)
    @handle("c-d", filter=sidebar_visible)
    @handle("enter", filter=sidebar_visible)
    @handle("escape", filter=sidebar_visible)
    def _(event):
        " Hide sidebar. "
        python_input.show_sidebar = False
        event.app.layout.focus_last()

    return bindings