summaryrefslogtreecommitdiffstats
path: root/examples/prompts/custom-key-binding.py
blob: 32d889ede04786c3788a3cdb6465e26b02676018 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python
"""
Example of adding a custom key binding to a prompt.
"""
import asyncio

from prompt_toolkit import prompt
from prompt_toolkit.application import in_terminal, run_in_terminal
from prompt_toolkit.key_binding import KeyBindings


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)

    @bindings.add("c-k")
    async def _(event):
        """
        Example of asyncio coroutine as a key binding.
        """
        try:
            for i in range(5):
                async with in_terminal():
                    print("hello")
                await asyncio.sleep(1)
        except asyncio.CancelledError:
            print("Prompt terminated before we completed.")

    # Read input.
    print('Press F4 to insert "hello world", type "xy" to insert "z":')
    text = prompt("> ", key_bindings=bindings)
    print("You said: %s" % text)


if __name__ == "__main__":
    main()