Ejemplo n.º 1
0
def test_substyles():
    style = Style([
        ('a.b', '#ff0000 bold'),
        ('a', '#0000ff'),
        ('b', '#00ff00'),
        ('b.c', '#0000ff italic'),
    ])

    # Starting with a.*
    expected = Attrs(color='0000ff',
                     bgcolor='',
                     bold=False,
                     underline=False,
                     italic=False,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('class:a') == expected

    expected = Attrs(color='ff0000',
                     bgcolor='',
                     bold=True,
                     underline=False,
                     italic=False,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('class:a.b') == expected
    assert style.get_attrs_for_style_str('class:a.b.c') == expected

    # Starting with b.*
    expected = Attrs(color='00ff00',
                     bgcolor='',
                     bold=False,
                     underline=False,
                     italic=False,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('class:b') == expected
    assert style.get_attrs_for_style_str('class:b.a') == expected

    expected = Attrs(color='0000ff',
                     bgcolor='',
                     bold=False,
                     underline=False,
                     italic=True,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('class:b.c') == expected
    assert style.get_attrs_for_style_str('class:b.c.d') == expected
Ejemplo n.º 2
0
def test_style_from_dict():
    style = Style.from_dict({
        'a': '#ff0000 bold underline italic',
        'b': 'bg:#00ff00 blink reverse',
    })

    # Lookup of class:a.
    expected = Attrs(color='ff0000',
                     bgcolor='',
                     bold=True,
                     underline=True,
                     italic=True,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('class:a') == expected

    # Lookup of class:b.
    expected = Attrs(color='',
                     bgcolor='00ff00',
                     bold=False,
                     underline=False,
                     italic=False,
                     blink=True,
                     reverse=True,
                     hidden=False)
    assert style.get_attrs_for_style_str('class:b') == expected

    # Test inline style.
    expected = Attrs(color='ff0000',
                     bgcolor='',
                     bold=False,
                     underline=False,
                     italic=False,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('#ff0000') == expected

    # Combine class name and inline style (Whatever is defined later gets priority.)
    expected = Attrs(color='00ff00',
                     bgcolor='',
                     bold=True,
                     underline=True,
                     italic=True,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('class:a #00ff00') == expected

    expected = Attrs(color='ff0000',
                     bgcolor='',
                     bold=True,
                     underline=True,
                     italic=True,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('#00ff00 class:a') == expected
Ejemplo n.º 3
0
def test_class_combinations_2():
    # In this case, our style has both class 'a' and 'b'.
    # The style that is defined the latest get priority.
    style = Style([
        ('a b', '#ff0000'),
        ('b', '#00ff00'),
        ('a', '#0000ff'),
    ])
    expected = Attrs(color='00ff00',
                     bgcolor='',
                     bold=False,
                     underline=False,
                     italic=False,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('class:a class:b') == expected
    assert style.get_attrs_for_style_str('class:a,b') == expected
    assert style.get_attrs_for_style_str('class:a,b,c') == expected

    # Defining 'a' latest should give priority to 'a'.
    expected = Attrs(color='0000ff',
                     bgcolor='',
                     bold=False,
                     underline=False,
                     italic=False,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('class:b class:a') == expected
    assert style.get_attrs_for_style_str('class:b,a') == expected
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
def test_with_style():
    f = _Capture()
    style = Style.from_dict({
        'hello': '#ff0066',
        'world': '#44ff44 italic',
    })
    tokens = FormattedText([
        ('class:hello', 'Hello '),
        ('class:world', 'world'),
    ])
    pt_print(tokens, style=style, file=f)
    assert b'\x1b[0;38;5;197mHello' in f.data
    assert b'\x1b[0;38;5;83;3mworld' in f.data
def main():
    style = Style.from_dict({
        'hello': '#ff0066',
        'world': '#44ff44 italic',
    })

    # Print using a a list of text fragments.
    text_fragments = FormattedText([
        ('class:hello', 'Hello '),
        ('class:world', 'World'),
        ('', '\n'),
    ])
    print(text_fragments, style=style)

    # Print using an HTML object.
    print(HTML('<hello>hello</hello> <world>world</world>\n'), style=style)

    # Print using an HTML object with inline styling.
    print(
        HTML('<style fg="#ff0066">hello</style> '
             '<style fg="#44ff44"><i>world</i></style>\n'))

    # Print using ANSI escape sequences.
    print(ANSI('\x1b[31mhello \x1b[32mworld\n'))
def main():
    # Printing a manually constructed list of (Token, text) tuples.
    text = [
        (Token.Keyword, 'print'),
        (Token.Punctuation, '('),
        (Token.Literal.String.Double, '"'),
        (Token.Literal.String.Double, 'hello'),
        (Token.Literal.String.Double, '"'),
        (Token.Punctuation, ')'),
        (Token.Text, '\n'),
    ]

    print_formatted_text(PygmentsTokens(text))

    # Printing the output of a pygments lexer.
    tokens = list(pygments.lex('print("Hello")', lexer=PythonLexer()))
    print_formatted_text(PygmentsTokens(tokens))

    # With a custom style.
    style = Style.from_dict({
        'pygments.keyword': 'underline',
        'pygments.literal.string': 'bg:#00ff00 #ffffff',
    })
    print_formatted_text(PygmentsTokens(tokens), style=style)
Ejemplo n.º 8
0
def test_class_combinations_1():
    # In this case, our style has both class 'a' and 'b'.
    # Given that the style for 'a b' is defined at the end, that one is used.
    style = Style([
        ('a', '#0000ff'),
        ('b', '#00ff00'),
        ('a b', '#ff0000'),
    ])
    expected = Attrs(color='ff0000',
                     bgcolor='',
                     bold=False,
                     underline=False,
                     italic=False,
                     blink=False,
                     reverse=False,
                     hidden=False)
    assert style.get_attrs_for_style_str('class:a class:b') == expected
    assert style.get_attrs_for_style_str('class:a,b') == expected
    assert style.get_attrs_for_style_str('class:a,b,c') == expected

    # Changing the order shouldn't matter.
    assert style.get_attrs_for_style_str('class:b class:a') == expected
    assert style.get_attrs_for_style_str('class:b,a') == expected
Ejemplo n.º 9
0
from prompt_toolkit_dev.shortcuts import checkboxlist_dialog, message_dialog
from prompt_toolkit_dev.styles import Style

results = checkboxlist_dialog(title="CheckboxList dialog",
                              text="What would you like in your breakfast ?",
                              values=[("eggs", "Eggs"), ("bacon", "Bacon"),
                                      ("croissants", "20 Croissants"),
                                      ("daily", "The breakfast of the day")],
                              style=Style.from_dict({
                                  'dialog':
                                  'bg:#cdbbb3',
                                  'button':
                                  'bg:#bf99a4',
                                  'checkbox':
                                  '#e8612c',
                                  'dialog.body':
                                  'bg:#a9cfd0',
                                  'dialog shadow':
                                  'bg:#c98982',
                                  'frame.label':
                                  '#fcaca3',
                                  'dialog.body label':
                                  '#fd8bb6',
                              })).run()
if results:
    message_dialog(title="Room service",
                   text="You selected: %s\nGreat choice sir !" %
                   ",".join(results)).run()
else:
    message_dialog("*starves*").run()
# 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',

    # Styling for Dialog widgets.

    'radiolist focused': 'noreverse',
    'radiolist focused radio.selected': 'reverse',

    'button-bar': 'bg:#aaaaff'
})


application = Application(
    layout=Layout(
        root_container,
        focused_element=yes_button,
Ejemplo n.º 11
0
#!/usr/bin/env python
"""
Styled similar to tqdm, another progress bar implementation in Python.

See: https://github.com/noamraph/tqdm
"""
import time

from prompt_toolkit_dev.shortcuts import ProgressBar
from prompt_toolkit_dev.shortcuts.progress_bar import formatters
from prompt_toolkit_dev.styles import Style

style = Style.from_dict({
    'bar-a': 'reverse',
})


def main():
    custom_formatters = [
        formatters.Label(suffix=': '),
        formatters.Percentage(),
        formatters.Bar(start='|', end='|', sym_a=' ', sym_b=' ', sym_c=' '),
        formatters.Text(' '),
        formatters.Progress(),
        formatters.Text(' ['),
        formatters.TimeElapsed(),
        formatters.Text('<'),
        formatters.TimeLeft(),
        formatters.Text(', '),
        formatters.IterationsPerSecond(),
        formatters.Text('it/s]'),
Ejemplo n.º 12
0
A very simple progress bar which keep track of the progress as we consume an
iterator.
"""
import time

from prompt_toolkit_dev.formatted_text import HTML
from prompt_toolkit_dev.shortcuts import ProgressBar
from prompt_toolkit_dev.shortcuts.progress_bar import formatters
from prompt_toolkit_dev.styles import Style

style = Style.from_dict({
    'progressbar title': '#0000ff',
    'item-title': '#ff4400 underline',
    'percentage': '#00ff00',
    'bar-a': 'bg:#00ff00 #004400',
    'bar-b': 'bg:#00ff00 #000000',
    'bar-c': 'bg:#000000 #000000',
    'tildes': '#444488',
    'time-left': 'bg:#88ff88 #ffffff',
    'spinning-wheel': 'bg:#ffff00 #000000',
})


def main():
    custom_formatters = [
        formatters.Label(),
        formatters.Text(' '),
        formatters.SpinningWheel(),
        formatters.Text(' '),
        formatters.Text(HTML('<tildes>~~~</tildes>')),
        formatters.Bar(sym_a='#', sym_b='#', sym_c='.'),
Ejemplo n.º 13
0
    'foreign', 'from', 'full', 'glob', 'group', 'having', 'if', 'ignore',
    'immediate', 'in', 'index', 'indexed', 'initially', 'inner', 'insert',
    'instead', 'intersect', 'into', 'is', 'isnull', 'join', 'key', 'left',
    'like', 'limit', 'match', 'natural', 'no', 'not', 'notnull', 'null', 'of',
    'offset', 'on', 'or', 'order', 'outer', 'plan', 'pragma', 'primary',
    'query', 'raise', 'recursive', 'references', 'regexp', 'reindex',
    'release', 'rename', 'replace', 'restrict', 'right', 'rollback', 'row',
    'savepoint', 'select', 'set', 'table', 'temp', 'temporary', 'then', 'to',
    'transaction', 'trigger', 'union', 'unique', 'update', 'using', 'vacuum',
    'values', 'view', 'virtual', 'when', 'where', 'with', 'without'
],
                              ignore_case=True)

style = Style.from_dict({
    'completion-menu.completion': 'bg:#008888 #ffffff',
    'completion-menu.completion.current': 'bg:#00aaaa #000000',
    'scrollbar.background': 'bg:#88aaaa',
    'scrollbar.button': 'bg:#222222',
})


def main(database):
    connection = sqlite3.connect(database)
    session = PromptSession(lexer=PygmentsLexer(SqlLexer),
                            completer=sql_completer,
                            style=style)

    while True:
        try:
            text = session.prompt('> ')
        except KeyboardInterrupt:
            continue  # Control-C pressed. Try again.
Ejemplo n.º 14
0
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()
Ejemplo n.º 15
0
from prompt_toolkit_dev.styles import Style

operators1 = ['add', 'sub', 'div', 'mul']
operators2 = ['cos', 'sin']


def create_grammar():
    return compile(r"""
        (\s*  (?P<operator1>[a-z]+)   \s+   (?P<var1>[0-9.]+)   \s+   (?P<var2>[0-9.]+)   \s*) |
        (\s*  (?P<operator2>[a-z]+)   \s+   (?P<var1>[0-9.]+)   \s*)
    """)


example_style = Style.from_dict({
    'operator': '#33aa33 bold',
    'number': '#ff0000 bold',
    'trailing-input': 'bg:#662222 #ffffff',
})

if __name__ == '__main__':
    g = create_grammar()

    lexer = GrammarLexer(g,
                         lexers={
                             'operator1': SimpleLexer('class:operator'),
                             'operator2': SimpleLexer('class:operator'),
                             'var1': SimpleLexer('class:number'),
                             'var2': SimpleLexer('class:number'),
                         })

    completer = GrammarCompleter(
"""
Example of a style dialog window.
All dialog shortcuts take a `style` argument in order to apply a custom
styling.

This also demonstrates that the `title` argument can be any kind of formatted
text.
"""
from prompt_toolkit_dev.formatted_text import HTML
from prompt_toolkit_dev.shortcuts import message_dialog
from prompt_toolkit_dev.styles import Style

# Custom color scheme.
example_style = Style.from_dict({
    'dialog': 'bg:#88ff88',
    'dialog frame-label': 'bg:#ffffff #000000',
    'dialog.body': 'bg:#000000 #00ff00',
    'dialog shadow': 'bg:#00aa00',
})


def main():
    message_dialog(title=HTML('<style bg="blue" fg="white">Styled</style> '
                              '<style fg="ansired">dialog</style> window'),
                   text='Do you want to continue?\nPress ENTER to quit.',
                   style=example_style).run()


if __name__ == '__main__':
    main()
Ejemplo n.º 17
0
#!/usr/bin/env python
"""
A very simple progress bar which keep track of the progress as we consume an
iterator.
"""
import time

from prompt_toolkit_dev.shortcuts import ProgressBar
from prompt_toolkit_dev.styles import Style

style = Style.from_dict({
    'title': '#4444ff underline',
    'label': '#ff4400 bold',
    'percentage': '#00ff00',
    'bar-a': 'bg:#00ff00 #004400',
    'bar-b': 'bg:#00ff00 #000000',
    'bar-c': '#000000 underline',
    'current': '#448844',
    'total': '#448844',
    'time-elapsed': '#444488',
    'time-left': 'bg:#88ff88 #000000',
})


def main():
    with ProgressBar(style=style,
                     title='Progress bar example with custom styling.') as pb:
        for i in pb(range(1600), label='Downloading...'):
            time.sleep(.01)


if __name__ == '__main__':
Ejemplo n.º 18
0
#!/usr/bin/env python
"""
Example of a right prompt. This is an additional prompt that is displayed on
the right side of the terminal. It will be hidden automatically when the input
is long enough to cover the right side of the terminal.

This is similar to RPROMPT is Zsh.
"""
from prompt_toolkit_dev import prompt
from prompt_toolkit_dev.formatted_text import ANSI, HTML
from prompt_toolkit_dev.styles import Style

example_style = Style.from_dict({
    # The 'rprompt' gets by default the 'rprompt' class. We can use this
    # for the styling.
    'rprompt': 'bg:#ff0066 #ffffff',
})


def get_rprompt_text():
    return [
        ('', ' '),
        ('underline', '<rprompt>'),
        ('', ' '),
    ]


def main():
    # Option 1: pass a string to 'rprompt':
    answer = prompt('> ', rprompt=' <rprompt> ', style=example_style)
    print('You said: %s' % answer)
Ejemplo n.º 19
0
])

# 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',
})

# create application.
application = Application(layout=Layout(
    root_container,
    focused_element=text_area,
),
                          key_bindings=bindings,
                          enable_page_navigation_bindings=True,
                          mouse_support=True,
                          style=style,
                          full_screen=True)

Ejemplo n.º 20
0
            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,
                          key_bindings=kb,
                          style=style,
                          full_screen=True)


def main():
    application.run()

Ejemplo n.º 21
0
                 children=[
                     MenuItem('Status Bar', handler=do_status_bar),
                 ]),
        MenuItem('Info', children=[
            MenuItem('About', handler=do_about),
        ]),
    ],
    floats=[
        Float(xcursor=True,
              ycursor=True,
              content=CompletionsMenu(max_height=16, scroll_offset=1)),
    ],
    key_bindings=bindings)

style = Style.from_dict({
    'status': 'reverse',
    'shadow': 'bg:#440044',
})

layout = Layout(root_container, focused_element=text_field)

application = Application(layout=layout,
                          enable_page_navigation_bindings=True,
                          style=style,
                          mouse_support=True,
                          full_screen=True)


def run():
    application.run()

#!/usr/bin/env python
"""
Styled just like an apt-get installation.
"""
import time

from prompt_toolkit_dev.shortcuts import ProgressBar
from prompt_toolkit_dev.shortcuts.progress_bar import formatters
from prompt_toolkit_dev.styles import Style

style = Style.from_dict({
    'label': 'bg:#ffff00 #000000',
    'percentage': 'bg:#ffff00 #000000',
    'current': '#448844',
    'bar': '',
})


def main():
    custom_formatters = [
        formatters.Label(),
        formatters.Text(': [', style='class:percentage'),
        formatters.Percentage(),
        formatters.Text(']', style='class:percentage'),
        formatters.Text(' '),
        formatters.Bar(sym_a='#', sym_b='#', sym_c='.'),
        formatters.Text('  '),
    ]

    with ProgressBar(style=style, formatters=custom_formatters) as pb:
        for i in pb(range(1600), label='Installing'):