diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 17:35:20 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 17:35:20 +0000 |
commit | e106bf94eff07d9a59771d9ccc4406421e18ab64 (patch) | |
tree | edb6545500e39df9c67aa918a6125bffc8ec1aee /examples/prompts/custom-key-binding.py | |
parent | Initial commit. (diff) | |
download | prompt-toolkit-upstream/3.0.36.tar.xz prompt-toolkit-upstream/3.0.36.zip |
Adding upstream version 3.0.36.upstream/3.0.36upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rwxr-xr-x | examples/prompts/custom-key-binding.py | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/examples/prompts/custom-key-binding.py b/examples/prompts/custom-key-binding.py new file mode 100755 index 0000000..32d889e --- /dev/null +++ b/examples/prompts/custom-key-binding.py @@ -0,0 +1,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() |