How to use the cmd2.ansi.ansi_safe_wcswidth function in cmd2

To help you get started, we’ve selected a few cmd2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github python-cmd2 / cmd2 / cmd2 / utils.py View on Github external
left_fill_width = 0
            right_fill_width = total_fill_width
        elif alignment == TextAlignment.CENTER:
            left_fill_width = total_fill_width // 2
            right_fill_width = total_fill_width - left_fill_width
        else:
            left_fill_width = total_fill_width
            right_fill_width = 0

        # Determine how many fill characters are needed to cover the width
        left_fill = (left_fill_width // fill_char_width) * fill_char
        right_fill = (right_fill_width // fill_char_width) * fill_char

        # In cases where the fill character display width didn't divide evenly into
        # the gaps being filled, pad the remainder with spaces.
        left_fill += ' ' * (left_fill_width - ansi.ansi_safe_wcswidth(left_fill))
        right_fill += ' ' * (right_fill_width - ansi.ansi_safe_wcswidth(right_fill))

        text_buf.write(left_fill + line + right_fill)

    return text_buf.getvalue()
github python-cmd2 / cmd2 / cmd2 / utils.py View on Github external
right_fill_width = total_fill_width
        elif alignment == TextAlignment.CENTER:
            left_fill_width = total_fill_width // 2
            right_fill_width = total_fill_width - left_fill_width
        else:
            left_fill_width = total_fill_width
            right_fill_width = 0

        # Determine how many fill characters are needed to cover the width
        left_fill = (left_fill_width // fill_char_width) * fill_char
        right_fill = (right_fill_width // fill_char_width) * fill_char

        # In cases where the fill character display width didn't divide evenly into
        # the gaps being filled, pad the remainder with spaces.
        left_fill += ' ' * (left_fill_width - ansi.ansi_safe_wcswidth(left_fill))
        right_fill += ' ' * (right_fill_width - ansi.ansi_safe_wcswidth(right_fill))

        text_buf.write(left_fill + line + right_fill)

    return text_buf.getvalue()
github python-cmd2 / cmd2 / cmd2 / utils.py View on Github external
lines = text.splitlines()
    else:
        lines = ['']

    if width is None:
        width = shutil.get_terminal_size().columns

    text_buf = io.StringIO()

    for index, line in enumerate(lines):
        if index > 0:
            text_buf.write('\n')

        # Use ansi_safe_wcswidth to support characters with display widths
        # greater than 1 as well as ANSI escape sequences
        line_width = ansi.ansi_safe_wcswidth(line)
        if line_width == -1:
            raise(ValueError("Text to align contains an unprintable character"))

        # Check if line is wider than the desired final width
        if width <= line_width:
            text_buf.write(line)
            continue

        # Calculate how wide each side of filling needs to be
        total_fill_width = width - line_width

        if alignment == TextAlignment.LEFT:
            left_fill_width = 0
            right_fill_width = total_fill_width
        elif alignment == TextAlignment.CENTER:
            left_fill_width = total_fill_width // 2
github python-cmd2 / cmd2 / tests / test_ansi.py View on Github external
def test_ansi_safe_wcswidth():
    base_str = HELLO_WORLD
    ansi_str = ansi.style(base_str, fg='green')
    assert ansi.ansi_safe_wcswidth(ansi_str) != len(ansi_str)
github python-cmd2 / cmd2 / tests / test_utils.py View on Github external
def test_align_text_term_width():
    import shutil
    from cmd2 import ansi
    text = 'foo'
    fill_char = ' '

    term_width = shutil.get_terminal_size().columns
    expected_fill = (term_width - ansi.ansi_safe_wcswidth(text)) * fill_char

    aligned = cu.align_text(text, fill_char=fill_char, alignment=cu.TextAlignment.LEFT)
    assert aligned == text + expected_fill
github python-cmd2 / cmd2 / cmd2 / argparse_completer.py View on Github external
def _format_completions(self, action, completions: List[Union[str, CompletionItem]]) -> List[str]:
        # Check if the results are CompletionItems and that there aren't too many to display
        if 1 < len(completions) <= self._cmd2_app.max_completion_items and \
                isinstance(completions[0], CompletionItem):

            # If the user has not already sorted the CompletionItems, then sort them before appending the descriptions
            if not self._cmd2_app.matches_sorted:
                completions.sort(key=self._cmd2_app.default_sort_key)
                self._cmd2_app.matches_sorted = True

            token_width = ansi.ansi_safe_wcswidth(action.dest)
            completions_with_desc = []

            for item in completions:
                item_width = ansi.ansi_safe_wcswidth(item)
                if item_width > token_width:
                    token_width = item_width

            term_size = shutil.get_terminal_size()
            fill_width = int(term_size.columns * .6) - (token_width + 2)
            for item in completions:
                entry = '{: <{token_width}}{: <{fill_width}}'.format(item, item.description,
                                                                     token_width=token_width + 2,
                                                                     fill_width=fill_width)
                completions_with_desc.append(entry)

            desc_header = getattr(action, ATTR_DESCRIPTIVE_COMPLETION_HEADER, None)
            if desc_header is None:
                desc_header = DEFAULT_DESCRIPTIVE_HEADER
            header = '\n{: <{token_width}}{}'.format(action.dest.upper(), desc_header, token_width=token_width + 2)
github python-cmd2 / cmd2 / cmd2 / argparse_completer.py View on Github external
def _format_completions(self, action, completions: List[Union[str, CompletionItem]]) -> List[str]:
        # Check if the results are CompletionItems and that there aren't too many to display
        if 1 < len(completions) <= self._cmd2_app.max_completion_items and \
                isinstance(completions[0], CompletionItem):

            # If the user has not already sorted the CompletionItems, then sort them before appending the descriptions
            if not self._cmd2_app.matches_sorted:
                completions.sort(key=self._cmd2_app.default_sort_key)
                self._cmd2_app.matches_sorted = True

            token_width = ansi.ansi_safe_wcswidth(action.dest)
            completions_with_desc = []

            for item in completions:
                item_width = ansi.ansi_safe_wcswidth(item)
                if item_width > token_width:
                    token_width = item_width

            term_size = shutil.get_terminal_size()
            fill_width = int(term_size.columns * .6) - (token_width + 2)
            for item in completions:
                entry = '{: <{token_width}}{: <{fill_width}}'.format(item, item.description,
                                                                     token_width=token_width + 2,
                                                                     fill_width=fill_width)
                completions_with_desc.append(entry)

            desc_header = getattr(action, ATTR_DESCRIPTIVE_COMPLETION_HEADER, None)
github python-cmd2 / cmd2 / cmd2 / utils.py View on Github external
ValueError if text or fill_char contains an unprintable character
    """
    import io
    import shutil

    from . import ansi

    # Handle tabs
    text = text.replace('\t', ' ' * tab_width)
    if fill_char == '\t':
        fill_char = ' '

    if len(fill_char) != 1:
        raise TypeError("Fill character must be exactly one character long")

    fill_char_width = ansi.ansi_safe_wcswidth(fill_char)
    if fill_char_width == -1:
        raise (ValueError("Fill character is an unprintable character"))

    if text:
        lines = text.splitlines()
    else:
        lines = ['']

    if width is None:
        width = shutil.get_terminal_size().columns

    text_buf = io.StringIO()

    for index, line in enumerate(lines):
        if index > 0:
            text_buf.write('\n')