prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.28k stars 715 forks source link

Add example for converting from readline-based key bindings to Prompt Toolkit #335

Open evandrone opened 8 years ago

evandrone commented 8 years ago

The keybinding example shows how to do some fancy things with key bindings (CtrlT to print "hello world"), so it's clear how to execute an arbitrary callable for a given key combination (or at least, for key combinations defined in from prompt_toolkit.keys.Keys), but if I just want to customize key combinations for existing cursor functions, where would I go? For instance, my .inputrc contains:

C-f: backward-word
C-g: backward-kill-word

The prompt-toolkit alternative should be something like:

from prompt_toolkit import prompt
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
manager = KeyBindingManager.for_prompt()

@manager.registry.add_binding(Keys.ControlF)
def _(event):
    # < Function call to move cursor backward one word>

@manager.registry.add_binding(Keys.ControlG)
def _(event):
    # < Function call to kill backward one word>

I'd be happy to add something like this to the keybinding example, if someone can tell me what functions to call. Cheers!

jonathanslenders commented 8 years ago

Hi @evandrone,

This was not obvious indeed. Your question inspired me to improve the key bindings. Now there is a new file called prompt_toolkit.key_binding.bindings.named_commands: https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/key_binding/bindings/named_commands.py

This is a start; it can be improved; but the idea is that we separate the implementation of the commands from the actual keys to which they are bound, so that it is easier to bind them to another key. Have a look at all the functions in this file, it should give you an idea of how to convert a readline config.

evandrone commented 8 years ago

That's really excellent, Jonathan. Thanks! I'd started poking at key_bindings.bindings.emacs with something similar in mind, but your solution is more complete and much appreciated. Cheers.

westurner commented 8 years ago

See also: #56 "detect key-bindings from .inputrc"

pronobis commented 5 years ago

A follow up related question: inputrc allows for assigning custom terminal codes to actions, e.g.: "\e[255;3u": kill-word

How can this be achieved in prompt-toolkit?