prompt-toolkit / ptpython

A better Python REPL
BSD 3-Clause "New" or "Revised" License
5.23k stars 281 forks source link

Use tab or enter for autocomplete instead of right arrow key? #198

Open dmitry-saritasa opened 7 years ago

dmitry-saritasa commented 7 years ago

from config.py

    # Enable auto suggestions. (Pressing right arrow will complete the input,
    # based on the history.)
    repl.enable_auto_suggest = True

how to change it to do completion on Tab?

gjeusel commented 4 years ago

I managed to achieve the desired behaviour as follow:

    from prompt_toolkit.key_binding.key_processor import KeyPress
    from prompt_toolkit.keys import Keys

    # Typing 'Tab' will accept auto-complete
    @repl.add_key_binding(Keys.Tab)  # for TAB
    def _(event):
        "Map 'Tab' to 'ctrl-e'. "
        event.cli.key_processor.feed(KeyPress(Keys.ControlE))

Not the best; I could not find a way to correctly call the complete_nextas in this example. But well... It does the work !

gjeusel commented 4 years ago

One could do the same with ctrl-space using the following decorator:

    @repl.add_key_binding("c-space")  # for ctrl-space
marcuscaisey commented 4 years ago

I did some looking to see how the default autosuggestion binds are implemented in python-prompt-toolkit and found a more (i think) idiomatic solution.

from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import Condition
from prompt_toolkit.keys import Keys

@Condition
def suggestion_available():
    app = get_app()
    return (
        app.current_buffer.suggestion is not None
        and app.current_buffer.document.is_cursor_at_the_end
    )

# Typing 'Tab' will accept auto-suggestion
@repl.add_key_binding(Keys.Tab, filter=suggestion_available)
def _(event):
    b = event.current_buffer
    suggestion = b.suggestion
    b.insert_text(suggestion.text)

The text now is inserted from the suggestion object and the bind is only activated when a suggestion is available.