def test_html_interpolation():
    # %-style interpolation.
    value = HTML('<b>%s</b>') % 'hello'
    assert to_formatted_text(value) == [
        ('class:b', 'hello')
    ]

    value = HTML('<b>%s</b>') % ('hello', )
    assert to_formatted_text(value) == [
        ('class:b', 'hello')
    ]

    value = HTML('<b>%s</b><u>%s</u>') % ('hello', 'world')
    assert to_formatted_text(value) == [
        ('class:b', 'hello'),
        ('class:u', 'world')
    ]

    # Format function.
    value = HTML('<b>{0}</b><u>{1}</u>').format('hello', 'world')
    assert to_formatted_text(value) == [
        ('class:b', 'hello'),
        ('class:u', 'world')
    ]

    value = HTML('<b>{a}</b><u>{b}</u>').format(a='hello', b='world')
    assert to_formatted_text(value) == [
        ('class:b', 'hello'),
        ('class:u', 'world')
    ]
Ejemplo n.º 2
0
def get_line_prefix(lineno, wrap_count):
    if wrap_count == 0:
        return HTML(
            '[%s] <style bg="orange" fg="black">--&gt;</style> ') % lineno

    text = str(lineno) + '-' + '*' * (lineno // 2) + ': '
    return HTML('[%s.%s] <style bg="ansigreen" fg="ansiblack">%s</style>') % (
        lineno, wrap_count, text)
def main():
    title = HTML(
        'Downloading <style bg="yellow" fg="black">4 files...</style>')
    label = HTML('<ansired>some file</ansired>: ')

    with ProgressBar(title=title) as pb:
        for i in pb(range(800), label=label):
            time.sleep(.01)
def test_merge_formatted_text():
    html1 = HTML('<u>hello</u>')
    html2 = HTML('<b>world</b>')
    result = merge_formatted_text([html1, html2])

    assert to_formatted_text(result) == [
        ('class:u', 'hello'),
        ('class:b', 'world'),
    ]
Ejemplo n.º 5
0
    def format(self, progress_bar: 'ProgressBar',
               progress: 'ProgressBarCounter[object]',
               width: int) -> AnyFormattedText:

        # Subtract left, bar_b and right.
        width -= get_cwidth(self.start + self.sym_b + self.end)

        if progress.total:
            pb_a = int(progress.percentage * width / 100)
            bar_a = self.sym_a * pb_a
            bar_b = self.sym_b
            bar_c = self.sym_c * (width - pb_a)
        else:
            # Total is unknown.
            pb_a = int(time.time() * 20  % 100 * width / 100)
            bar_a = self.sym_c * pb_a
            bar_b = self.unknown
            bar_c = self.sym_c * (width - pb_a)

        return HTML(self.template).format(
            start=self.start,
            end=self.end,
            bar_a=bar_a,
            bar_b=bar_b,
            bar_c=bar_c)
Ejemplo n.º 6
0
    def format(self, progress_bar: 'ProgressBar',
               progress: 'ProgressBarCounter[object]',
               width: int) -> AnyFormattedText:

        return HTML(self.template).format(
            current=progress.items_completed,
            total=progress.total or '?')
def test_html_with_fg_bg():
    html = HTML('<style bg="ansired">hello</style>')
    assert to_formatted_text(html) == [
        ('bg:ansired', 'hello'),
    ]

    html = HTML('<style bg="ansired" fg="#ff0000">hello</style>')
    assert to_formatted_text(html) == [
        ('fg:#ff0000 bg:ansired', 'hello'),
    ]

    html = HTML('<style bg="ansired" fg="#ff0000">hello <world fg="ansiblue">world</world></style>')
    assert to_formatted_text(html) == [
        ('fg:#ff0000 bg:ansired', 'hello '),
        ('class:world fg:ansiblue bg:ansired', 'world'),
    ]
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)
def test_interpolation():
    value = Template(' {} ').format(HTML('<b>hello</b>'))

    assert to_formatted_text(value) == [
        ('', ' '),
        ('class:b', 'hello'),
        ('', ' '),
    ]

    value = Template('a{}b{}c').format(HTML('<b>hello</b>'), 'world')

    assert to_formatted_text(value) == [
        ('', 'a'),
        ('class:b', 'hello'),
        ('', 'b'),
        ('', 'world'),
        ('', 'c'),
    ]
    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
Ejemplo n.º 11
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)
def test_basic_html():
    html = HTML('<i>hello</i>')
    assert to_formatted_text(html) == [('class:i', 'hello')]

    html = HTML('<i><b>hello</b></i>')
    assert to_formatted_text(html) == [('class:i,b', 'hello')]

    html = HTML('<i><b>hello</b>world<strong>test</strong></i>after')
    assert to_formatted_text(html) == [
        ('class:i,b', 'hello'),
        ('class:i', 'world'),
        ('class:i,strong', 'test'),
        ('', 'after'),
    ]

    # It's important that `to_formatted_text` returns a `FormattedText`
    # instance. Otherwise, `print_formatted_text` won't recognise it and will
    # print a list literal instead.
    assert isinstance(to_formatted_text(html), FormattedText)
Ejemplo n.º 13
0
    def format(self, progress_bar: 'ProgressBar',
               progress: 'ProgressBarCounter[object]',
               width: int) -> AnyFormattedText:

        time_left = progress.time_left
        if time_left is not None:
            formatted_time_left = _format_timedelta(time_left)
        else:
            formatted_time_left = self.unknown

        return HTML(self.template).format(time_left=formatted_time_left.rjust(width))
Ejemplo n.º 14
0
def test_with_style():
    """
    Text `print_formatted_text` with `HTML` wrapped in `to_formatted_text`.
    """
    f = _Capture()

    html = HTML('<ansigreen>hello</ansigreen> <b>world</b>')
    formatted_text = to_formatted_text(html, style='class:myhtml')
    pt_print(formatted_text, file=f)

    assert f.data == \
        b'\x1b[0m\x1b[?7h\x1b[0;32mhello\x1b[0m \x1b[0;1mworld\x1b[0m\r\n\x1b[0m'
Ejemplo n.º 15
0
def main():
    result = radiolist_dialog(values=[
        ('red', 'Red'),
        ('green', 'Green'),
        ('blue', 'Blue'),
        ('orange', 'Orange'),
    ],
                              title='Radiolist dialog example',
                              text='Please select a color:').run()

    print('Result = {}'.format(result))

    # With HTML.
    result = radiolist_dialog(
        values=[
            ('red', HTML('<style bg="red" fg="white">Red</style>')),
            ('green', HTML('<style bg="green" fg="white">Green</style>')),
            ('blue', HTML('<style bg="blue" fg="white">Blue</style>')),
            ('orange', HTML('<style bg="orange" fg="white">Orange</style>')),
        ],
        title=HTML('Radiolist dialog example <reverse>with colors</reverse>'),
        text='Please select a color:').run()

    print('Result = {}'.format(result))
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'))
Ejemplo n.º 17
0
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
Ejemplo n.º 18
0
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)
Ejemplo n.º 19
0
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='.'),
        formatters.Text(' left: '),
        formatters.TimeLeft(),
    ]
    with ProgressBar(title='Progress bar example with custom formatter.',
                     formatters=custom_formatters,
                     style=style) as pb:

        for i in pb(range(20), label='Downloading...'):
            time.sleep(1)
    def get_completions(self, document, complete_event):
        word = document.get_word_before_cursor()
        for animal in animals:
            if animal.startswith(word):
                if animal in animal_family:
                    family = animal_family[animal]
                    family_color = family_colors.get(family, 'default')

                    display = HTML('%s<b>:</b> <ansired>(<' + family_color +
                                   '>%s</' + family_color +
                                   '>)</ansired>') % (animal, family)
                else:
                    display = animal

                yield Completion(animal,
                                 start_position=-len(word),
                                 display=display,
                                 display_meta=meta.get(animal))
def main():
    print(HTML('\n<u>True color test.</u>'))

    for template in [
            'bg:#{0:02x}0000',  # Red.
            'bg:#00{0:02x}00',  # Green.
            'bg:#0000{0:02x}',  # Blue.
            'bg:#{0:02x}{0:02x}00',  # Yellow.
            'bg:#{0:02x}00{0:02x}',  # Magenta.
            'bg:#00{0:02x}{0:02x}',  # Cyan.
            'bg:#{0:02x}{0:02x}{0:02x}',  # Gray.
    ]:
        fragments = []
        for i in range(0, 256, 4):
            fragments.append((template.format(i), ' '))

        print(FormattedText(fragments), color_depth=ColorDepth.DEPTH_4_BIT)
        print(FormattedText(fragments), color_depth=ColorDepth.DEPTH_8_BIT)
        print(FormattedText(fragments), color_depth=ColorDepth.DEPTH_24_BIT)
        print()
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
    def format(self, progress_bar: 'ProgressBar',
               progress: 'ProgressBarCounter[object]',
               width: int) -> AnyFormattedText:

        index = int(time.time() * 3) % len(self.characters)
        return HTML('<spinning-wheel>{0}</spinning-wheel>').format(self.characters[index])
Ejemplo n.º 24
0
    def format(self, progress_bar: 'ProgressBar',
               progress: 'ProgressBarCounter[object]',
               width: int) -> AnyFormattedText:

        value = progress.items_completed / progress.time_elapsed.total_seconds()
        return HTML(self.template.format(iterations_per_second=value))
Ejemplo n.º 25
0
    def format(self, progress_bar: 'ProgressBar',
               progress: 'ProgressBarCounter[object]',
               width: int) -> AnyFormattedText:

        text = _format_timedelta(progress.time_elapsed).rjust(width)
        return HTML('<time-elapsed>{time_elapsed}</time-elapsed>').format(time_elapsed=text)
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()
Ejemplo n.º 27
0
def main():
    wide_space = ('', '       ')
    space = ('', ' ')

    print(HTML('\n<u>Foreground colors</u>'))
    print(
        FormattedText([
            ('ansiblack', 'ansiblack'),
            wide_space,
            ('ansired', 'ansired'),
            wide_space,
            ('ansigreen', 'ansigreen'),
            wide_space,
            ('ansiyellow', 'ansiyellow'),
            wide_space,
            ('ansiblue', 'ansiblue'),
            wide_space,
            ('ansimagenta', 'ansimagenta'),
            wide_space,
            ('ansicyan', 'ansicyan'),
            wide_space,
            ('ansigray', 'ansigray'),
            wide_space,
            ('', '\n'),
            ('ansibrightblack', 'ansibrightblack'),
            space,
            ('ansibrightred', 'ansibrightred'),
            space,
            ('ansibrightgreen', 'ansibrightgreen'),
            space,
            ('ansibrightyellow', 'ansibrightyellow'),
            space,
            ('ansibrightblue', 'ansibrightblue'),
            space,
            ('ansibrightmagenta', 'ansibrightmagenta'),
            space,
            ('ansibrightcyan', 'ansibrightcyan'),
            space,
            ('ansiwhite', 'ansiwhite'),
            space,
        ]))

    print(HTML('\n<u>Background colors</u>'))
    print(
        FormattedText([
            ('bg:ansiblack ansiwhite', 'ansiblack'),
            wide_space,
            ('bg:ansired', 'ansired'),
            wide_space,
            ('bg:ansigreen', 'ansigreen'),
            wide_space,
            ('bg:ansiyellow', 'ansiyellow'),
            wide_space,
            ('bg:ansiblue ansiwhite', 'ansiblue'),
            wide_space,
            ('bg:ansimagenta', 'ansimagenta'),
            wide_space,
            ('bg:ansicyan', 'ansicyan'),
            wide_space,
            ('bg:ansigray', 'ansigray'),
            wide_space,
            ('', '\n'),
            ('bg:ansibrightblack', 'ansibrightblack'),
            space,
            ('bg:ansibrightred', 'ansibrightred'),
            space,
            ('bg:ansibrightgreen', 'ansibrightgreen'),
            space,
            ('bg:ansibrightyellow', 'ansibrightyellow'),
            space,
            ('bg:ansibrightblue', 'ansibrightblue'),
            space,
            ('bg:ansibrightmagenta', 'ansibrightmagenta'),
            space,
            ('bg:ansibrightcyan', 'ansibrightcyan'),
            space,
            ('bg:ansiwhite', 'ansiwhite'),
            space,
        ]))
    print()
Ejemplo n.º 28
0
    def format(self, progress_bar: 'ProgressBar',
               progress: 'ProgressBarCounter[object]',
               width: int) -> AnyFormattedText:

        return HTML(self.template).format(
            percentage=round(progress.percentage, 1))
Ejemplo n.º 29
0
def title(text):
    print(HTML('\n<u><b>{}</b></u>').format(text))
    'duck': 'bird',
    'eagle': 'bird',
    'elephant': 'mammal',
}

family_colors = {
    'mammal': 'ansimagenta',
    'insect': 'ansigreen',
    'reptile': 'ansired',
    'bird': 'ansiyellow',
}

meta = {
    'alligator':
    HTML(
        'An <ansired>alligator</ansired> is a <u>crocodilian</u> in the genus Alligator of the family Alligatoridae.'
    ),
    'ant':
    HTML(
        '<ansired>Ants</ansired> are eusocial <u>insects</u> of the family Formicidae.'
    ),
    'ape':
    HTML(
        '<ansired>Apes</ansired> (Hominoidea) are a branch of Old World tailless anthropoid catarrhine <u>primates</u>.'
    ),
    'bat':
    HTML(
        '<ansired>Bats</ansired> are mammals of the order <u>Chiroptera</u>.'),
    'bee':
    HTML(
        '<ansired>Bees</ansired> are flying <u>insects</u> closely related to wasps and ants.'