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)
Exemple #2
0
def main():
    bottom_toolbar = HTML(
        ' <b>[f]</b> Print "f" <b>[q]</b> Abort  <b>[x]</b> Send Control-C.')

    # Create custom key bindings first.
    kb = KeyBindings()
    cancel = [False]

    @kb.add('f')
    def _(event):
        print('You pressed `f`.')

    @kb.add('q')
    def _(event):
        " Quit by setting cancel flag. "
        cancel[0] = True

    @kb.add('x')
    def _(event):
        " Quit by sending SIGINT to the main thread. "
        os.kill(os.getpid(), signal.SIGINT)

    # Use `patch_stdout`, to make sure that prints go above the
    # application.
    with patch_stdout():
        with ProgressBar(key_bindings=kb, bottom_toolbar=bottom_toolbar) as pb:
            for i in pb(range(800)):
                time.sleep(.01)

                if cancel[0]:
                    break
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)
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)
Exemple #5
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 create_dummy_layout() -> Layout:
    """
    Create a dummy layout for use in an 'Application' that doesn't have a
    layout specified. When ENTER is pressed, the application quits.
    """
    kb = KeyBindings()

    @kb.add('enter')
    def enter(event: E) -> None:
        event.app.exit()

    control = FormattedTextControl(
        HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'),
        key_bindings=kb)
    window = Window(content=control, height=D(min=1))
    return Layout(container=window, focused_element=window)
def create_key_bindings() -> KeyBindings:
    """
    Key bindings handled by the progress bar.
    (The main thread is not supposed to handle any key bindings.)
    """
    kb = KeyBindings()

    @kb.add('c-l')
    def _(event: E) -> None:
        event.app.renderer.clear()

    @kb.add('c-c')
    def _(event: E) -> None:
        # Send KeyboardInterrupt to the main thread.
        os.kill(os.getpid(), signal.SIGINT)

    return kb
Exemple #8
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 `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)
                     search_field=search_field,
                     lexer=PygmentsLexer(PythonLexer))

root_container = HSplit([
    # The top toolbar.
    Window(content=FormattedTextControl(get_statusbar_text),
           height=D.exact(1),
           style='class:status'),

    # The main content.
    text_area,
    search_field,
])

# Key bindings.
bindings = KeyBindings()


@bindings.add('c-c')
@bindings.add('q')
def _(event):
    " Quit. "
    event.app.exit()


style = Style.from_dict({
    'status': 'reverse',
    'status.position': '#aaaa00',
    'status.key': '#ffaa00',
    'not-searching': '#888888',
})
    'goat',
    'gorilla',
    'kangaroo',
    'leopard',
    'lion',
    'mouse',
    'rabbit',
    'rat',
    'snake',
    'spider',
    'turkey',
    'turtle',
],
                                 ignore_case=True)

kb = KeyBindings()


@kb.add('c-space')
def _(event):
    """
    Start auto completion. If the menu is showing already, select the next
    completion.
    """
    b = event.app.current_buffer
    if b.complete_state:
        b.complete_next()
    else:
        b.start_completion(select_first=False)

# widget. It adapts automatically, unless an explicit `padding` amount is given.
root_container = Box(
    HSplit([
        Label(text='Press `Tab` to move the focus.'),
        VSplit([
            Box(body=HSplit([button1, button2, button3, button4], padding=1),
                padding=1,
                style='class:left-pane'),
            Box(body=Frame(text_area), padding=1, style='class:right-pane'),
        ]),
    ]), )

layout = Layout(container=root_container, focused_element=button1)

# Key bindings.
kb = KeyBindings()
kb.add('tab')(focus_next)
kb.add('s-tab')(focus_previous)

# Styling.
style = Style([
    ('left-pane', 'bg:#888800 #000000'),
    ('right-pane', 'bg:#00aa00 #000000'),
    ('button', '#000000'),
    ('button-arrow', '#000000'),
    ('button focused', 'bg:#ff0000'),
    ('text-area focused', 'bg:#ff0000'),
])

# Build a main application object.
application = Application(layout=layout,
def main():
    # The layout.
    search_field = SearchToolbar()  # For reverse search.

    output_field = TextArea(style='class:output-field', text=help_text)
    input_field = TextArea(height=1,
                           prompt='>>> ',
                           style='class:input-field',
                           multiline=False,
                           wrap_lines=False,
                           search_field=search_field)

    container = HSplit([
        output_field,
        Window(height=1, char='-', style='class:line'),
        input_field,
        search_field,
    ])

    # Attach accept handler to the input field. We do this by assigning the
    # handler to the `TextArea` that we created earlier. it is also possible to
    # pass it to the constructor of `TextArea`.
    # NOTE: It's better to assign an `accept_handler`, rather then adding a
    #       custom ENTER key binding. This will automatically reset the input
    #       field and add the strings to the history.
    def accept(buff):
        # Evaluate "calculator" expression.
        try:
            output = '\n\nIn:  {}\nOut: {}'.format(
                input_field.text,
                eval(input_field.text))  # Don't do 'eval' in real code!
        except BaseException as e:
            output = '\n\n{}'.format(e)
        new_text = output_field.text + output

        # Add text to output buffer.
        output_field.buffer.document = Document(text=new_text,
                                                cursor_position=len(new_text))

    input_field.accept_handler = accept

    # The key bindings.
    kb = KeyBindings()

    @kb.add('c-c')
    @kb.add('c-q')
    def _(event):
        " Pressing Ctrl-Q or Ctrl-C will exit the user interface. "
        event.app.exit()

    # Style.
    style = Style([
        ('output-field', 'bg:#000044 #ffffff'),
        ('input-field', 'bg:#000000 #ffffff'),
        ('line', '#004400'),
    ])

    # Run application.
    application = Application(layout=Layout(container,
                                            focused_element=input_field),
                              key_bindings=kb,
                              style=style,
                              mouse_support=True,
                              full_screen=True)

    application.run()
    MenuItem('View', children=[
        MenuItem('Status Bar'),
    ]),
    MenuItem('Info', children=[
        MenuItem('About'),
    ]),
], floats=[
    Float(xcursor=True,
          ycursor=True,
          content=CompletionsMenu(
              max_height=16,
              scroll_offset=1)),
])

# Global key bindings.
bindings = KeyBindings()
bindings.add('tab')(focus_next)
bindings.add('s-tab')(focus_previous)


style = Style.from_dict({
    'window.border': '#888888',
    'shadow': 'bg:#222222',

    'menu-bar': 'bg:#aaaaaa #888888',
    'menu-bar.selected-item': 'bg:#ffffff #000000',
    'menu': 'bg:#888888 #ffffff',
    'menu.border': '#aaaaaa',
    'window.border shadow': '#444444',

    'focused  button': 'bg:#880000 #ffffff noinherit',