python-2.7prompt-toolkit

How to make the prompt_toolkit prompt provide completions before a key is pressed?


The prompt function under python prompt_toolkit can be used with a default string which appears at the prompt as if the user has typed it.

defaultWord = u"cat"
prompt( u"Enter a word", completer=SomeCompleter, default=defaultWord)

I've found that even though the default is set the completion menu doesn't open up as if the user had actually typed it. You have to hit at least one key to get it to do so.

Is there a way to force the completion menu to show before a user has hit a key?


Solution

  • If you are using a PromptSession you can use the pre_run argument to PromptSession.prompt:

    from prompt_toolkit import PromptSession
    from prompt_toolkit.completion import WordCompleter
    completer = WordCompleter([u"Hello", u"World"])
    session = PromptSession(u"> ", completer=completer)
    session.prompt(pre_run=session.default_buffer.start_completion)