def display(page):
        # Display completions.
        page_completions = completions[page * completions_per_page:
                                       (page + 1) * completions_per_page]

        page_row_count = int(math.ceil(len(page_completions) / float(column_count)))
        page_columns = [page_completions[i * page_row_count:(i + 1) * page_row_count]
                   for i in range(column_count)]

        result = []  # FormattedText list: (style,text) tuples.

        for r in range(page_row_count):
            for c in range(column_count):
                try:
                    completion = page_columns[c][r]
                    style = 'class:readline-like-completions.completion ' + (completion.style or '')

                    result.extend(to_formatted_text(completion.display, style=style))

                    # Add padding.
                    padding = max_compl_width - get_cwidth(completion.display_text)
                    result.append((completion.style, ' ' * padding,))
                except IndexError:
                    pass
            result.append(('', '\n'))

        app.print_text(to_formatted_text(result, 'class:readline-like-completions'))
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')
    ]
def test_ansi_formatting():
    value = ANSI('\x1b[32mHe\x1b[45mllo')

    assert to_formatted_text(value) == [
        ('ansigreen', 'H'),
        ('ansigreen', 'e'),
        ('ansigreen bg:ansimagenta', 'l'),
        ('ansigreen bg:ansimagenta', 'l'),
        ('ansigreen bg:ansimagenta', 'o'),
    ]

    # Bold and italic.
    value = ANSI('\x1b[1mhe\x1b[0mllo')

    assert to_formatted_text(value) == [
        ('bold', 'h'),
        ('bold', 'e'),
        ('', 'l'),
        ('', 'l'),
        ('', 'o'),
    ]

    # Zero width escapes.
    value = ANSI('ab\001cd\002ef')

    assert to_formatted_text(value) == [
        ('', 'a'),
        ('', 'b'),
        ('[ZeroWidthEscape]', 'cd'),
        ('', 'e'),
        ('', 'f'),
    ]

    assert isinstance(to_formatted_text(value), FormattedText)
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'),
    ]
Example #5
0
    def _get_text_fragments(self):
        result = []
        for i, value in enumerate(self.values):
            checked = (value[0] == self.current_value)
            selected = (i == self._selected_index)

            style = ''
            if checked:
                style += ' class:radio-checked'
            if selected:
                style += ' class:radio-selected'

            result.append((style, '<'))

            if selected:
                result.append(('[SetCursorPosition]', ''))

            if checked:
                result.append((style, ' '))
            else:
                result.append((style, ' '))

            result.append((style, '>'))
            result.append(('class:radio', ' '))
            result.extend(to_formatted_text(value[1], style='class:radio'))
            result.append(('', '\n'))
        #result.pop()  # Remove last newline.
        #result.append(('',self.description))
        return result
 def send_above_prompt(self, formatted_text: AnyFormattedText) -> None:
     """
     Send text to the client.
     This is asynchronous, returns a `Future`.
     """
     formatted_text = to_formatted_text(formatted_text)
     return self._run_in_terminal(lambda: self.send(formatted_text))
    def create_margin(self, window_render_info, width, height):
        get_continuation = self.get_continuation
        result = []

        # First line.
        result.extend(to_formatted_text(self.get_prompt()))

        # Next lines.
        if get_continuation:
            last_y = None

            for y in window_render_info.displayed_lines[1:]:
                result.append(('', '\n'))
                result.extend(to_formatted_text(get_continuation(width, y, y == last_y)))
                last_y = y

        return result
 def apply_transformation(self, ti: TransformationInput) -> Transformation:
     # Insert fragments after the last line.
     if ti.lineno == ti.document.line_count - 1:
         # Get fragments.
         fragments_after = to_formatted_text(self.text, self.style)
         return Transformation(fragments=ti.fragments + fragments_after)
     else:
         return Transformation(fragments=ti.fragments)
Example #9
0
def formatted_text(
    draw,
    html_strategy: Optional[SearchStrategy[str]] = None,
    ansi_strategy: Optional[SearchStrategy[str]] = None,
) -> SearchStrategy[FormattedText]:
    """Composite strategy to build basic instances of FormattedText."""

    return draw(
        sampled_from([
            to_formatted_text(
                HTML(
                    draw(html_strategy
                         if html_strategy else just("<b>Hello, World!</b>")))),
            to_formatted_text(
                ANSI(
                    draw(ansi_strategy if ansi_strategy else just(
                        "\x1b[1mHello, World!\x1b[0m")))),
        ]))
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'),
    ]
Example #11
0
        def _find(event: E) -> None:
            # We first check values after the selected value, then all values.
            values = list(self.values)
            for value in values[self._selected_index + 1 :] + values:
                text = fragment_list_to_text(to_formatted_text(value[1])).lower()

                if text.startswith(event.data.lower()):
                    self._selected_index = self.values.index(value)
                    return
Example #12
0
 def test_no_mouse_handler(self):
     mouse_event = MouseEvent(Point(0, 0), MouseEventType.MOUSE_UP)
     handler = mock.MagicMock()
     formatted_text = to_formatted_text([("", "hello"),
                                         ("", "world", lambda x: handler(x))
                                         ])
     text_area = FormattedTextArea(formatted_text)
     text_area.control.mouse_handler(mouse_event)
     handler.assert_not_called()
Example #13
0
 def apply_transformation(self, transformation_input):
     formatted_lines = transformation_input.buffer_control.formatted_lines
     lineno = transformation_input.lineno
     max_lineno = len(formatted_lines) - 1
     if lineno > max_lineno:
         line = ""
     else:
         line = formatted_lines[lineno]
     return Transformation(to_formatted_text(line))
Example #14
0
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"),
    ]
Example #15
0
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"),
    ]
    def create_margin(self, window_render_info, width, height):
        get_continuation = self.get_continuation
        result = []

        # First line.
        result.extend(to_formatted_text(self.get_prompt()))

        # Next lines.
        if get_continuation:
            last_y = None

            for y in window_render_info.displayed_lines[1:]:
                result.append(('', '\n'))
                result.extend(
                    to_formatted_text(get_continuation(width, y, y == last_y)))
                last_y = y

        return result
Example #17
0
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'),
    ]
Example #18
0
 def send(self, formatted_text: AnyFormattedText) -> None:
     """
     Send text to the client.
     """
     if self.vt100_output is None:
         return
     formatted_text = to_formatted_text(formatted_text)
     print_formatted_text(self.vt100_output, formatted_text, self.style
                          or DummyStyle())
 def _get_formatted_text_cached(self) -> StyleAndTextTuples:
     """
     Get fragments, but only retrieve fragments once during one render run.
     (This function is called several times during one rendering, because
     we also need those for calculating the dimensions.)
     """
     return self._fragment_cache.get(
         get_app().render_counter,
         lambda: to_formatted_text(self.text, self.style))
 def _get_formatted_text_cached(self) -> StyleAndTextTuples:
     """
     Get fragments, but only retrieve fragments once during one render run.
     (This function is called several times during one rendering, because
     we also need those for calculating the dimensions.)
     """
     return self._fragment_cache.get(
         get_app().render_counter,
         lambda: to_formatted_text(self.text, self.style))
Example #21
0
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'),
    ]
Example #22
0
 def _get_title(self):
     book_title = self.chapter.book.metadata["title"]
     return to_formatted_text([
         ("class:title", book_title),
         ("", " "),
         ("class:seperator", ">"),
         ("", " "),
         ("class:title", self.chapter.title),
     ])
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'),
    ]
Example #24
0
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'),
    ]
Example #25
0
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 create_content(self, width: int, height: int) -> UIContent:
        all_fragments: StyleAndTextTuples = []

        complete_state = get_app().current_buffer.complete_state
        if complete_state:
            completions = complete_state.completions
            index = complete_state.complete_index  # Can be None!

            # Width of the completions without the left/right arrows in the margins.
            content_width = width - 6

            # Booleans indicating whether we stripped from the left/right
            cut_left = False
            cut_right = False

            # Create Menu content.
            fragments: StyleAndTextTuples = []

            for i, c in enumerate(completions):
                # When there is no more place for the next completion
                if fragment_list_len(fragments) + len(c.display_text) >= content_width:
                    # If the current one was not yet displayed, page to the next sequence.
                    if i <= (index or 0):
                        fragments = []
                        cut_left = True
                    # If the current one is visible, stop here.
                    else:
                        cut_right = True
                        break

                fragments.extend(to_formatted_text(
                    c.display_text,
                    style=('class:completion-toolbar.completion.current'
                           if i == index else 'class:completion-toolbar.completion')
                ))
                fragments.append(('', ' '))

            # Extend/strip until the content width.
            fragments.append(('', ' ' * (content_width - fragment_list_len(fragments))))
            fragments = fragments[:content_width]

            # Return fragments
            all_fragments.append(('', ' '))
            all_fragments.append(('class:completion-toolbar.arrow', '<' if cut_left else ' '))
            all_fragments.append(('', ' '))

            all_fragments.extend(fragments)

            all_fragments.append(('', ' '))
            all_fragments.append(('class:completion-toolbar.arrow', '>' if cut_right else ' '))
            all_fragments.append(('', ' '))

        def get_line(i: int) -> StyleAndTextTuples:
            return all_fragments

        return UIContent(get_line=get_line, line_count=1)
    def create_content(self, width, height):
        complete_state = get_app().current_buffer.complete_state
        if complete_state:
            completions = complete_state.completions
            index = complete_state.complete_index  # Can be None!

            # Width of the completions without the left/right arrows in the margins.
            content_width = width - 6

            # Booleans indicating whether we stripped from the left/right
            cut_left = False
            cut_right = False

            # Create Menu content.
            fragments = []

            for i, c in enumerate(completions):
                # When there is no more place for the next completion
                if fragment_list_len(fragments) + len(c.display_text) >= content_width:
                    # If the current one was not yet displayed, page to the next sequence.
                    if i <= (index or 0):
                        fragments = []
                        cut_left = True
                    # If the current one is visible, stop here.
                    else:
                        cut_right = True
                        break

                fragments.extend(to_formatted_text(
                    c.display_text,
                    style=('class:completion-toolbar.completion.current'
                           if i == index else 'class:completion-toolbar.completion')
                ))
                fragments.append(('', ' '))

            # Extend/strip until the content width.
            fragments.append(('', ' ' * (content_width - fragment_list_len(fragments))))
            fragments = fragments[:content_width]

            # Return fragments
            all_fragments = [
                ('', ' '),
                ('class:completion-toolbar.arrow', '<' if cut_left else ' '),
                ('', ' '),
            ] + fragments + [
                ('', ' '),
                ('class:completion-toolbar.arrow', '>' if cut_right else ' '),
                ('', ' '),
            ]
        else:
            all_fragments = []

        def get_line(i):
            return all_fragments

        return UIContent(get_line=get_line, line_count=1)
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)
Example #29
0
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)
Example #30
0
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)
Example #31
0
    def create_margin(self, window_render_info: "WindowRenderInfo", width: int,
                      height: int) -> StyleAndTextTuples:
        get_continuation = self.get_continuation
        result: StyleAndTextTuples = []

        # First line.
        result.extend(to_formatted_text(self.get_prompt()))

        # Next lines.
        if get_continuation:
            last_y = None

            for y in window_render_info.displayed_lines[1:]:
                result.append(("", "\n"))
                result.extend(
                    to_formatted_text(get_continuation(width, y, y == last_y)))
                last_y = y

        return result
Example #32
0
File: ui.py Project: czinn/ebb
def draw_table(columns, data):
    column_widths = [0 for _ in columns]
    data = [[to_formatted_text(cell) for cell in row] for row in data]
    for row in data:
        for i, cell in enumerate(row):
            column_widths[i] = max(column_widths[i], fragment_list_width(cell))
    row_output = []
    for i, column in enumerate(columns):
        column_widths[i] = max(column_widths[i], len(column.header))
        column_widths[i] = min(column_widths[i], column.max_width)
        row_output += trim_pad(
            to_formatted_text(HTML(f'<b>{column.header}</b>')),
            column_widths[i], 'l') + [('', '  ')]
    print(FormattedText(row_output))
    for row in data:
        row_output = []
        for i, cell in enumerate(row):
            row_output += trim_pad(cell, column_widths[i], columns[i].align) + \
                    [('', '  ')]
        print(FormattedText(row_output))
Example #33
0
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')]
    def _get_text_fragments(self) -> StyleAndTextTuples:
        style = 'class:completion-menu.multi-column-meta'
        state = get_app().current_buffer.complete_state

        if state and state.current_completion and state.current_completion.display_meta_text:
            return to_formatted_text(cast(StyleAndTextTuples, [('', ' ')]) +
                                     state.current_completion.display_meta +
                                     [('', ' ')],
                                     style=style)

        return []
Example #35
0
 def get_width():
     if width is None:
         text_fragments = to_formatted_text(self.text)
         text = fragment_list_to_text(text_fragments)
         if text:
             longest_line = max(get_cwidth(line) for line in text.splitlines())
         else:
             return D(preferred=0)
         return D(preferred=longest_line)
     else:
         return width
Example #36
0
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")]
Example #37
0
 def get_width(self, progress_bar: "Progress") -> AnyDimension:
     all_values = [
         self.get_render_text(c) for c in progress_bar.models
         if isinstance(c, PlayerModel)
     ]
     if all_values:
         max_widths = max(
             fragment_list_width(to_formatted_text(v, ''))
             for v in all_values)
         return max_widths
     return 0
Example #38
0
 def get_width() -> AnyDimension:
     if width is None:
         text_fragments = to_formatted_text(self.text)
         text = fragment_list_to_text(text_fragments)
         if text:
             longest_line = max(get_cwidth(line) for line in text.splitlines())
         else:
             return D(preferred=0)
         return D(preferred=longest_line)
     else:
         return width
Example #39
0
 def apply_transformation(self, ti):
     try:
         fragments = to_formatted_text(
             HTML(fragment_list_to_text(ti.fragments)))
     except Exception as ex:
         # xml.parsers.expat.ExpatError
         # not well-formed (invalid token): line 1, column 138
         logger.error('FormatText: {} {}'.format(type(ex), str(ex)))
         #return Transformation([('', ' ')])
         return Transformation([])
     return Transformation(fragments)
def test_pygments_tokens():
    text = [
        (('A', 'B'), 'hello'),  # Token.A.B
        (('C', 'D', 'E'), 'hello'),  # Token.C.D.E
        ((), 'world'),  # Token
    ]

    assert to_formatted_text(PygmentsTokens(text)) == [
        ('class:pygments.a.b', 'hello'),
        ('class:pygments.c.d.e', 'hello'),
        ('class:pygments', 'world'),
    ]
Example #41
0
def sql_line_prefix(line_number: int, wrap_count: int,
                    my_app: "sqlApp") -> StyleAndTextTuples:
    if my_app.active_conn is not None:
        sqlConn = my_app.active_conn
        prompt = sqlConn.username + "@" + sqlConn.dsn + ":" + sqlConn.current_catalog(
        ) + " > "
    else:
        prompt = "> "
    if line_number == 0 and wrap_count == 0:
        return to_formatted_text([("class:prompt", prompt)])
    prompt_width = len(prompt)
    return [("class:prompt.dots", "." * (prompt_width - 1) + " ")]
    def _get_text_fragments(self):
        style = 'class:completion-menu.multi-column-meta'
        state = get_app().current_buffer.complete_state

        if state and state.current_completion and state.current_completion.display_meta_text:
            return to_formatted_text(
                [('', ' ')] +
                state.current_completion.display_meta +
                [('', ' ')],
                style=style)

        return []
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'
Example #44
0
def test_pygments_tokens():
    text = [
        (('A', 'B'), 'hello'),  # Token.A.B
        (('C', 'D', 'E'), 'hello'),  # Token.C.D.E
        ((), 'world'),  # Token
    ]

    assert to_formatted_text(PygmentsTokens(text)) == [
        ('class:pygments.a.b', 'hello'),
        ('class:pygments.c.d.e', 'hello'),
        ('class:pygments', 'world'),
    ]
Example #45
0
def get_info_app(app: Flask):
    left_part = HTML("<left-part>"
                     " <import_name>%s</import_name> "
                     "<path>%s</path>"
                     "</left-part>") % (app.import_name, app.root_path)
    right_part = HTML("<right-part> "
                      " <env>%s</env> "
                      " <time>%s</time> "
                      "</right-part>") % (os.environ["ZEMFROG_ENV"],
                                          datetime.datetime.now().isoformat())

    used_width = sum([
        fragment_list_width(to_formatted_text(left_part)),
        fragment_list_width(to_formatted_text(right_part)),
    ])

    total_width = get_app().output.get_size().columns
    padding_size = total_width - used_width

    padding = HTML("<padding>%s</padding>") % (" " * padding_size, )
    return left_part, padding, right_part, "\n"
Example #46
0
def test_pygments_tokens():
    text = [
        (("A", "B"), "hello"),  # Token.A.B
        (("C", "D", "E"), "hello"),  # Token.C.D.E
        ((), "world"),  # Token
    ]

    assert to_formatted_text(PygmentsTokens(text)) == [
        ("class:pygments.a.b", "hello"),
        ("class:pygments.c.d.e", "hello"),
        ("class:pygments", "world"),
    ]
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'
    def format(self, progress_bar, progress, width):
        # Get formatted text from nested formatter, and explode it in
        # text/style tuples.
        result = self.formatter.format(progress_bar, progress, width)
        result = explode_text_fragments(to_formatted_text(result))

        # Insert colors.
        result2 = []
        shift = int(time.time() * 3) % len(self.colors)

        for i, (style, text) in enumerate(result):
            result2.append((style + ' ' + self.colors[(i + shift) % len(self.colors)], text))
        return result2
    def _get_menu_item_meta_fragments(self, completion, is_current_completion, width):
        if is_current_completion:
            style_str = 'class:completion-menu.meta.completion.current'
        else:
            style_str = 'class:completion-menu.meta.completion'

        text, tw = _trim_formatted_text(completion.display_meta, width - 2)
        padding = ' ' * (width - 1 - tw)

        return to_formatted_text(
            [('', ' ')] +
            text +
            [('', padding)],
            style=style_str)
    def _get_text_fragments(self) -> StyleAndTextTuples:
        def mouse_handler(mouse_event: MouseEvent) -> None:
            """
            Set `_selected_index` and `current_value` according to the y
            position of the mouse click event.
            """
            if mouse_event.event_type == MouseEventType.MOUSE_UP:
                self._selected_index = mouse_event.position.y
                self._handle_enter()

        result: StyleAndTextTuples = []
        for i, value in enumerate(self.values):
            if self.multiple_selection:
                checked = (value[0] in self.current_values)
            else:
                checked = (value[0] == self.current_value)
            selected = (i == self._selected_index)

            style = ''
            if checked:
                style += ' ' + self.checked_style
            if selected:
                style += ' ' + self.selected_style

            result.append((style, self.open_character))

            if selected:
                result.append(('[SetCursorPosition]', ''))

            if checked:
                result.append((style, '*'))
            else:
                result.append((style, ' '))

            result.append((style, self.close_character))
            result.append((self.default_style, ' '))
            result.extend(to_formatted_text(value[1], style=self.default_style))
            result.append(('', '\n'))

        # Add mouse handler to all fragments.
        for i in range(len(result)):
            result[i] = (result[i][0], result[i][1], mouse_handler)

        result.pop()  # Remove last newline.
        return result
    def create_content(self, width, height):
        items = []
        for pr in self.progress_bar.counters:
            try:
                text = self.formatter.format(self.progress_bar, pr, width)
            except BaseException:
                traceback.print_exc()
                text = 'ERROR'

            items.append(to_formatted_text(text))

        def get_line(i):
            return items[i]

        return UIContent(
            get_line=get_line,
            line_count=len(items),
            show_cursor=False)
    def apply_transformation(self, ti: TransformationInput) -> Transformation:
        source_to_display: Optional[SourceToDisplay]
        display_to_source: Optional[DisplayToSource]

        if ti.lineno == 0:
            # Get fragments.
            fragments_before = to_formatted_text(self.text, self.style)
            fragments = fragments_before + ti.fragments

            shift_position = fragment_list_len(fragments_before)
            source_to_display = lambda i: i + shift_position
            display_to_source = lambda i: i - shift_position
        else:
            fragments = ti.fragments
            source_to_display = None
            display_to_source = None

        return Transformation(fragments, source_to_display=source_to_display,
                              display_to_source=display_to_source)
    def __init__(self, text: str, start_position: int = 0,
                 display: Optional[AnyFormattedText] = None,
                 display_meta: Optional[AnyFormattedText] = None,
                 style: str = '', selected_style: str = '') -> None:

        from prompt_toolkit.formatted_text import to_formatted_text
        self.text = text
        self.start_position = start_position
        self._display_meta = display_meta

        if display is None:
            display = text

        self.display = to_formatted_text(display)

        self.style = style
        self.selected_style = selected_style

        assert self.start_position <= 0
    def _get_text_fragments(self):
        def mouse_handler(mouse_event):
            """
            Set `_selected_index` and `current_value` according to the y
            position of the mouse click event.
            """
            if mouse_event.event_type == MouseEventType.MOUSE_UP:
                self._selected_index = mouse_event.position.y
                self.current_value = self.values[self._selected_index][0]

        result = []
        for i, value in enumerate(self.values):
            checked = (value[0] == self.current_value)
            selected = (i == self._selected_index)

            style = ''
            if checked:
                style += ' class:radio-checked'
            if selected:
                style += ' class:radio-selected'

            result.append((style, '('))

            if selected:
                result.append(('[SetCursorPosition]', ''))

            if checked:
                result.append((style, '*'))
            else:
                result.append((style, ' '))

            result.append((style, ')'))
            result.append(('class:radio', ' '))
            result.extend(to_formatted_text(value[1], style='class:radio'))
            result.append(('', '\n'))

        # Add mouse handler to all fragments.
        for i in range(len(result)):
            result[i] = (result[i][0], result[i][1], mouse_handler)

        result.pop()  # Remove last newline.
        return result
    def _get_continuation(self, width, line_number, wrap_count):
        """
        Insert the prompt continuation.

        :param width: The width that was used for the prompt. (more or less can
            be used.)
        :param line_number:
        :param wrap_count: Amount of times that the line has been wrapped.
        """
        prompt_continuation = self.prompt_continuation

        if callable(prompt_continuation):
            prompt_continuation = prompt_continuation(width, line_number, wrap_count)

        # When the continuation prompt is not given, choose the same width as
        # the actual prompt.
        if not prompt_continuation and is_true(self.multiline):
            prompt_continuation = ' ' * width

        return to_formatted_text(
            prompt_continuation, style='class:prompt-continuation')
    def __init__(self, text, start_position=0, display=None, display_meta=None,
                 style='', selected_style=''):
        assert isinstance(text, text_type)
        assert isinstance(start_position, int)
        assert isinstance(style, text_type)
        assert isinstance(selected_style, text_type)

        from prompt_toolkit.formatted_text import to_formatted_text
        self.text = text
        self.start_position = start_position
        self._display_meta = display_meta

        if display is None:
            display = text

        self.display = to_formatted_text(display)

        self.style = style
        self.selected_style = selected_style

        assert self.start_position <= 0
def _get_menu_item_fragments(
        completion, is_current_completion, width, space_after=False):
    """
    Get the style/text tuples for a menu item, styled and trimmed to the given
    width.
    """
    if is_current_completion:
        style_str = 'class:completion-menu.completion.current %s %s' % (
            completion.style, completion.selected_style)
    else:
        style_str = 'class:completion-menu.completion ' + completion.style

    text, tw = _trim_formatted_text(
        completion.display,
        (width - 2 if space_after else width - 1))

    padding = ' ' * (width - 1 - tw)

    return to_formatted_text(
        [('', ' ')] + text + [('', padding)],
        style=style_str)
def print_formatted_text(
        output, formatted_text, style, style_transformation=None,
        color_depth=None):
    """
    Print a list of (style_str, text) tuples in the given style to the output.
    """
    assert isinstance(output, Output)
    assert isinstance(style, BaseStyle)
    assert style_transformation is None or isinstance(style_transformation, StyleTransformation)
    assert color_depth is None or color_depth in ColorDepth._ALL

    fragments = to_formatted_text(formatted_text)
    style_transformation = style_transformation or DummyStyleTransformation()
    color_depth = color_depth or ColorDepth.default()

    # Reset first.
    output.reset_attributes()
    output.enable_autowrap()

    # Print all (style_str, text) tuples.
    attrs_for_style_string = _StyleStringToAttrsCache(
        style.get_attrs_for_style_str,
        style_transformation)

    for style_str, text in fragments:
        attrs = attrs_for_style_string[style_str]

        if attrs:
            output.set_attributes(attrs, color_depth)
        else:
            output.reset_attributes()

        # Assume that the output is raw, and insert a carriage return before
        # every newline. (Also important when the front-end is a telnet client.)
        assert '\r' not in text
        output.write(text.replace('\n', '\r\n'))

    # Reset again.
    output.reset_attributes()
    output.flush()
 def display_meta(self):
     " Return meta-text. (This is lazy when using a callable). "
     from prompt_toolkit.formatted_text import to_formatted_text
     return to_formatted_text(self._display_meta)
 def to_text(val: Any) -> StyleAndTextTuples:
     # Normal lists which are not instances of `FormattedText` are
     # considered plain text.
     if isinstance(val, list) and not isinstance(val, FormattedText):
         return to_formatted_text('{0}'.format(val))
     return to_formatted_text(val, auto_convert=True)