def main():
    # Validate when pressing ENTER.
    text = prompt('Enter e-mail address: ',
                  validator=validator,
                  validate_while_typing=False)
    print('You said: %s' % text)

    # While typing
    text = prompt('Enter e-mail address: ',
                  validator=validator,
                  validate_while_typing=True)
    print('You said: %s' % text)
def main():
    swapped = [False]  # Nonlocal
    bindings = KeyBindings()

    @bindings.add('c-t')
    def _(event):
        ' When ControlT has been pressed, toggle light/dark colors. '
        swapped[0] = not swapped[0]

    def bottom_toolbar():
        if swapped[0]:
            on = 'on=true'
        else:
            on = 'on=false'

        return HTML('Press <style bg="#222222" fg="#ff8888">[control-t]</style> '
                    'to swap between dark/light colors. '
                    '<style bg="ansiblack" fg="ansiwhite">[%s]</style>') % on

    text = prompt(HTML('<style fg="#aaaaaa">Give some animals</style>: '),
                  completer=html_completer,
                  complete_while_typing=True,
                  bottom_toolbar=bottom_toolbar,
                  key_bindings=bindings,
                  lexer=PygmentsLexer(HtmlLexer),
                  swap_light_and_dark_colors=Condition(lambda: swapped[0]))
    print('You said: %s' % text)
예제 #3
0
def main():
    # Example 1: fixed text.
    text = prompt('Say something: ', bottom_toolbar='This is a toolbar')
    print('You said: %s' % text)

    # Example 2: fixed text from a callable:
    def get_toolbar():
        return 'Bottom toolbar: time=%r' % time.time()

    text = prompt('Say something: ',
                  bottom_toolbar=get_toolbar,
                  refresh_interval=.5)
    print('You said: %s' % text)

    # Example 3: Using HTML:
    text = prompt(
        'Say something: ',
        bottom_toolbar=HTML(
            '(html) <b>This</b> <u>is</u> a <style bg="ansired">toolbar</style>'
        ))
    print('You said: %s' % text)

    # Example 4: Using ANSI:
    text = prompt(
        'Say something: ',
        bottom_toolbar=ANSI(
            '(ansi): \x1b[1mThis\x1b[0m \x1b[4mis\x1b[0m a \x1b[91mtoolbar'))
    print('You said: %s' % text)

    # Example 5: styling differently.
    style = Style.from_dict({
        'bottom-toolbar': '#aaaa00 bg:#ff0000',
        'bottom-toolbar.text': '#aaaa44 bg:#aa4444',
    })

    text = prompt('Say something: ',
                  bottom_toolbar='This is a toolbar',
                  style=style)
    print('You said: %s' % text)

    # Example 6: Using a list of tokens.
    def get_bottom_toolbar():
        return [
            ('', ' '),
            ('bg:#ff0000 fg:#000000', 'This'),
            ('', ' is a '),
            ('bg:#ff0000 fg:#000000', 'toolbar'),
            ('', '. '),
        ]

    text = prompt('Say something: ', bottom_toolbar=get_bottom_toolbar)
    print('You said: %s' % text)

    # Example 7: multiline fixed text.
    text = prompt('Say something: ',
                  bottom_toolbar='This is\na multiline toolbar')
    print('You said: %s' % text)
예제 #4
0
def run():
    # Create a `KeyBindings` that contains the default key bindings.
    bindings = KeyBindings()

    # Add an additional key binding for toggling this flag.
    @bindings.add('f4')
    def _(event):
        " Toggle between Emacs and Vi mode. "
        if event.app.editing_mode == EditingMode.VI:
            event.app.editing_mode = EditingMode.EMACS
        else:
            event.app.editing_mode = EditingMode.VI

    def bottom_toolbar():
        " Display the current input mode. "
        if get_app().editing_mode == EditingMode.VI:
            return ' [F4] Vi '
        else:
            return ' [F4] Emacs '

    prompt('> ', key_bindings=bindings, bottom_toolbar=bottom_toolbar)
def main():
    # We start with a `Registry` of default key bindings.
    bindings = KeyBindings()

    # Create the decorators to be used for registering text objects and
    # operators in this registry.
    operator = create_operator_decorator(bindings)
    text_object = create_text_object_decorator(bindings)

    # Create a custom operator.

    @operator('R')
    def _(event, text_object):
        " Custom operator that reverses text. "
        buff = event.current_buffer

        # Get relative start/end coordinates.
        start, end = text_object.operator_range(buff.document)
        start += buff.cursor_position
        end += buff.cursor_position

        text = buff.text[start:end]
        text = ''.join(reversed(text))

        event.app.current_buffer.text = buff.text[:start] + text + buff.text[
            end:]

    # Create a text object.

    @text_object('A')
    def _(event):
        " A custom text object that involves everything. "
        # Note that a `TextObject` has coordinates, relative to the cursor position.
        buff = event.current_buffer
        return TextObject(
            -buff.document.cursor_position,  # The start.
            len(buff.text) - buff.document.cursor_position)  # The end.

    # Read input.
    print('There is a custom text object "A" that applies to everything')
    print('and a custom operator "r" that reverses the text object.\n')

    print('Things that are possible:')
    print('-  Riw    - reverse inner word.')
    print('-  yA     - yank everything.')
    print('-  RA     - reverse everything.')

    text = prompt('> ',
                  default='hello world',
                  key_bindings=bindings,
                  editing_mode=EditingMode.VI)
    print('You said: %s' % text)
예제 #6
0
def main():
    # Option 1: pass a string to 'rprompt':
    answer = prompt('> ', rprompt=' <rprompt> ', style=example_style)
    print('You said: %s' % answer)

    # Option 2: pass HTML:
    answer = prompt('> ',
                    rprompt=HTML(' <u>&lt;rprompt&gt;</u> '),
                    style=example_style)
    print('You said: %s' % answer)

    # Option 3: pass ANSI:
    answer = prompt('> ',
                    rprompt=ANSI(' \x1b[4m<rprompt>\x1b[0m '),
                    style=example_style)
    print('You said: %s' % answer)

    # Option 4: Pass a callable. (This callable can either return plain text,
    #           an HTML object, an ANSI object or a list of (style, text)
    #           tuples.
    answer = prompt('> ', rprompt=get_rprompt_text, style=example_style)
    print('You said: %s' % answer)
def main():
    hidden = [True]  # Nonlocal
    bindings = KeyBindings()

    @bindings.add('c-t')
    def _(event):
        ' When ControlT has been pressed, toggle visibility. '
        hidden[0] = not hidden[0]

    print('Type Control-T to toggle password visible.')
    password = prompt('Password: '******'You said: %s' % password)
예제 #8
0
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)

    # Read input.
    print('Press F4 to insert "hello world", type "xy" to insert "z":')
    text = prompt('> ', key_bindings=bindings)
    print('You said: %s' % text)
def main():
    # Print a counter every second in another thread.
    running = True

    def thread():
        i = 0
        while running:
            i += 1
            print('i=%i' % i)
            time.sleep(1)

    t = threading.Thread(target=thread)
    t.daemon = True
    t.start()

    # Now read the input. The print statements of the other thread
    # should not disturb anything.
    with patch_stdout():
        result = prompt('Say something: ')
    print('You said: %s' % result)

    # Stop thread.
    running = False
def main():
    # We start with a `KeyBindings` for our extra key bindings.
    bindings = KeyBindings()

    # We add a custom key binding to space.
    @bindings.add(' ')
    def _(event):
        """
        When space is pressed, we check the word before the cursor, and
        autocorrect that.
        """
        b = event.app.current_buffer
        w = b.document.get_word_before_cursor()

        if w is not None:
            if w in corrections:
                b.delete_before_cursor(count=len(w))
                b.insert_text(corrections[w])

        b.insert_text(' ')

    # Read input.
    text = prompt('Say something: ', key_bindings=bindings)
    print('You said: %s' % text)
예제 #11
0
#!/usr/bin/env python
from prompt_toolkit_dev import prompt
from prompt_toolkit_dev.formatted_text import HTML


def prompt_continuation(width, line_number, wrap_count):
    """
    The continuation: display line numbers and '->' before soft wraps.

    Notice that we can return any kind of formatted text from here.

    The prompt continuation doesn't have to be the same width as the prompt
    which is displayed before the first line, but in this example we choose to
    align them. The `width` input that we receive here represents the width of
    the prompt.
    """
    if wrap_count > 0:
        return ' ' * (width - 3) + '-> '
    else:
        text = ('- %i - ' % (line_number + 1)).rjust(width)
        return HTML('<strong>%s</strong>') % text


if __name__ == '__main__':
    print('Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.')
    answer = prompt('Multiline input: ',
                    multiline=True,
                    prompt_continuation=prompt_continuation)
    print('You said: %s' % answer)
예제 #12
0
#!/usr/bin/env python
from prompt_toolkit_dev import prompt

if __name__ == '__main__':
    password = prompt('Password: '******'You said: %s' % password)
예제 #13
0
#!/usr/bin/env python
"""
Demonstration of how the input can be indented.
"""
from prompt_toolkit_dev import prompt

if __name__ == '__main__':
    answer = prompt(
        'Give me some input: (ESCAPE followed by ENTER to accept)\n > ',
        multiline=True)
    print('You said: %s' % answer)
예제 #14
0
def main():
    text = prompt('Enter HTML: ', lexer=PygmentsLexer(HtmlLexer))
    print('You said: %s' % text)
예제 #15
0
#!/usr/bin/env python
from prompt_toolkit_dev import prompt

if __name__ == '__main__':
    # System prompt.
    print(
        '(1/3) If you press meta-! or esc-! at the following prompt, you can enter system commands.'
    )
    answer = prompt('Give me some input: ', enable_system_prompt=True)
    print('You said: %s' % answer)

    # Enable suspend.
    print('(2/3) If you press Control-Z, the application will suspend.')
    answer = prompt('Give me some input: ', enable_suspend=True)
    print('You said: %s' % answer)

    # Enable open_in_editor
    print(
        '(3/3) If you press Control-X Control-E, the prompt will open in $EDITOR.'
    )
    answer = prompt('Give me some input: ', enable_open_in_editor=True)
    print('You said: %s' % answer)
#!/usr/bin/env python
"""
Example of `accept_default`, a way to automatically accept the input that the
user typed without allowing him/her to edit it.

This should display the prompt with all the formatting like usual, but not
allow any editing.
"""
from prompt_toolkit_dev import HTML, prompt

if __name__ == '__main__':
    answer = prompt(HTML('<b>Type <u>some input</u>: </b>'),
                    accept_default=True,
                    default='test')

    print('You said: %s' % answer)
예제 #17
0
                             'var1': SimpleLexer('class:number'),
                             'var2': SimpleLexer('class:number'),
                         })

    completer = GrammarCompleter(
        g, {
            'operator1': WordCompleter(operators1),
            'operator2': WordCompleter(operators2),
        })

    try:
        # REPL loop.
        while True:
            # Read input and parse the result.
            text = prompt('Calculate: ',
                          lexer=lexer,
                          completer=completer,
                          style=example_style)
            m = g.match(text)
            if m:
                vars = m.variables()
            else:
                print('Invalid command\n')
                continue

            print(vars)
            if vars.get('operator1') or vars.get('operator2'):
                try:
                    var1 = float(vars.get('var1', 0))
                    var2 = float(vars.get('var2', 0))
                except ValueError:
                    print('Invalid command (2)\n')
예제 #18
0
AFTER_PROMPT = '\033]133;B\a'
BEFORE_OUTPUT = '\033]133;C\a'
AFTER_OUTPUT = '\033]133;D;{command_status}\a'  # command_status is the command status, 0-255


def get_prompt_text():
    # Generate the text fragments for the prompt.
    # Important: use the `ZeroWidthEscape` fragment only if you are sure that
    #            writing this as raw text to the output will not introduce any
    #            cursor movements.
    return [
        ('[ZeroWidthEscape]', BEFORE_PROMPT),
        ('', 'Say something: # '),
        ('[ZeroWidthEscape]', AFTER_PROMPT),
    ]


if __name__ == '__main__':
    # Option 1: Using a `get_prompt_text` function:
    answer = prompt(get_prompt_text)

    # Option 2: Using ANSI escape sequences.
    before = '\001' + BEFORE_PROMPT + '\002'
    after = '\001' + AFTER_PROMPT + '\002'
    answer = prompt(ANSI('{}Say something: # {}'.format(before, after)))

    # Output.
    sys.stdout.write(BEFORE_OUTPUT)
    print('You said: %s' % answer)
    sys.stdout.write(AFTER_OUTPUT.format(command_status=0))
예제 #19
0
def main():
    completer = merge_completers([animal_completer, color_completer])

    text = prompt('Give some animals: ', completer=completer,
                  complete_while_typing=False)
    print('You said: %s' % text)
#!/usr/bin/env python
"""
Demonstration of a custom clipboard class.
This requires the 'pyperclip' library to be installed.
"""
from prompt_toolkit_dev import prompt
from prompt_toolkit_dev.clipboard.pyperclip import PyperclipClipboard

if __name__ == '__main__':
    print('Emacs shortcuts:')
    print('    Press Control-Y to paste from the system clipboard.')
    print('    Press Control-Space or Control-@ to enter selection mode.')
    print('    Press Control-W to cut to clipboard.')
    print('')

    answer = prompt('Give me some input: ', clipboard=PyperclipClipboard())
    print('You said: %s' % answer)
예제 #21
0
#!/usr/bin/env python
from prompt_toolkit_dev import prompt

if __name__ == '__main__':
    print(
        'This is multiline input. press [Meta+Enter] or [Esc] followed by [Enter] to accept input.'
    )
    print('You can click with the mouse in order to select text.')
    answer = prompt('Multiline input: ', multiline=True, mouse_support=True)
    print('You said: %s' % answer)
#!/usr/bin/env python
"""
Example of a call to `prompt` with a default value.
The input is pre-filled, but the user can still edit the default.
"""
import getpass

from prompt_toolkit_dev import prompt

if __name__ == '__main__':
    answer = prompt('What is your name: ', default='%s' % getpass.getuser())
    print('You said: %s' % answer)
def main():
    text = prompt('Give some animals: ',
                  completer=animal_completer,
                  complete_while_typing=False,
                  key_bindings=kb)
    print('You said: %s' % text)
#!/usr/bin/env python
from prompt_toolkit_dev import prompt

if __name__ == '__main__':
    print("You have Vi keybindings here. Press [Esc] to go to navigation mode.")
    answer = prompt('Give me some input: ', multiline=False, vi_mode=True)
    print('You said: %s' % answer)
예제 #25
0
#!/usr/bin/env python
from prompt_toolkit_dev import prompt

if __name__ == '__main__':
    answer = prompt('Give me some input: ', wrap_lines=False, multiline=True)
    print('You said: %s' % answer)
예제 #26
0
#!/usr/bin/env python
from prompt_toolkit_dev import prompt
from prompt_toolkit_dev.shortcuts import set_title

if __name__ == '__main__':
    set_title('This is the terminal title')
    answer = prompt('Give me some input: ')
    set_title('')

    print('You said: %s' % answer)