|
| 1 | +# coding: utf-8 |
| 2 | +from __future__ import unicode_literals, print_function |
| 3 | +from prompt_toolkit import prompt |
| 4 | +from prompt_toolkit.history import InMemoryHistory |
| 5 | +from prompt_toolkit.interface import AbortAction |
| 6 | +from prompt_toolkit.auto_suggest import AutoSuggestFromHistory |
| 7 | +from prompt_toolkit.key_binding.manager import KeyBindingManager |
| 8 | +from prompt_toolkit.keys import Keys |
| 9 | +from prompt_toolkit.filters import Condition |
| 10 | + |
| 11 | + |
| 12 | +def cli(): |
| 13 | + # Create some history first. (Easy for testing.) |
| 14 | + history = InMemoryHistory() |
| 15 | + history.append('import os') |
| 16 | + history.append('print("hello")') |
| 17 | + history.append('print("world")') |
| 18 | + history.append('import path') |
| 19 | + |
| 20 | + # ContrlT handling |
| 21 | + hidden = [True] # Nonlocal |
| 22 | + key_bindings_manager = KeyBindingManager() |
| 23 | + |
| 24 | + @key_bindings_manager.registry.add_binding(Keys.ControlT) |
| 25 | + def _(event): |
| 26 | + ' When ControlT has been pressed, toggle visibility. ' |
| 27 | + hidden[0] = not hidden[0] |
| 28 | + |
| 29 | + def prompt_pass(): |
| 30 | + print('Type Control-T to toggle password visible.') |
| 31 | + password = prompt('Password: ', |
| 32 | + is_password=Condition(lambda cli: hidden[0]), |
| 33 | + key_bindings_registry=key_bindings_manager.registry) |
| 34 | + return password |
| 35 | + |
| 36 | + # Print help. |
| 37 | + print('This CLI has fish-style auto-suggestion enable.') |
| 38 | + print('Type for instance "pri", then you\'ll see a suggestion.') |
| 39 | + print('Press the right arrow to insert the suggestion.') |
| 40 | + print('Press Control-C to retry. Control-D to exit.') |
| 41 | + print() |
| 42 | + |
| 43 | + def mprompt(): |
| 44 | + prompt('OnlyKey> ', history=history, |
| 45 | + auto_suggest=AutoSuggestFromHistory(), |
| 46 | + enable_history_search=True, |
| 47 | + on_abort=AbortAction.RETRY) |
| 48 | + |
| 49 | + nexte = mprompt |
| 50 | + |
| 51 | + while 1: |
| 52 | + text = nexte() |
| 53 | + print('You said: %s' % text) |
| 54 | + # nexte = prompt_pass |
| 55 | + |
| 56 | +def main(): |
| 57 | + try: |
| 58 | + cli() |
| 59 | + except EOFError: |
| 60 | + print() |
| 61 | + print('Bye!') |
| 62 | + pass |
0 commit comments