Python源码示例:pygments.style.Style()

示例1
def json_out(data, pretty=False, mono=False, piped_out=False):

    if not mono and not piped_out:
        # set colors
        class JcStyle(Style):
            styles = set_env_colors()

        if pretty:
            print(highlight(json.dumps(data, indent=2), JsonLexer(), Terminal256Formatter(style=JcStyle))[0:-1])
        else:
            print(highlight(json.dumps(data), JsonLexer(), Terminal256Formatter(style=JcStyle))[0:-1])
    else:
        if pretty:
            print(json.dumps(data, indent=2))
        else:
            print(json.dumps(data)) 
示例2
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native").styles

    for token in cli_style:
        if token.startswith("Token."):
            token_type, style_value = parse_pygments_style(token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error("Unhandled style / class name: %s", token)

    class OutputStyle(PygmentsStyle):
        default_style = ""
        styles = style

    return OutputStyle 
示例3
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native").styles

    for token in cli_style:
        if token.startswith("Token."):
            token_type, style_value = parse_pygments_style(token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error("Unhandled style / class name: %s", token)

    class OutputStyle(PygmentsStyle):
        default_style = ""
        styles = style

    return OutputStyle 
示例4
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name('native').styles

    for token in cli_style:
        if token.startswith('Token.'):
            token_type, style_value = parse_pygments_style(
                token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error('Unhandled style / class name: %s', token)
        
        class OutputStyle(PygmentsStyle):
            default_style = ""
            styles = style
        
        return OutputStyle 
示例5
def test_get_style_defs_contains_style_specific_line_numbers_styles():
    class TestStyle(Style):
        line_number_color = '#ff0000'
        line_number_background_color = '#0000ff'
        line_number_special_color = '#00ff00'
        line_number_special_background_color = '#ffffff'

    style_defs = HtmlFormatter(style=TestStyle).get_style_defs().splitlines()

    assert style_defs[1] == (
        'td.linenos pre '
        '{ color: #ff0000; background-color: #0000ff; padding: 0 5px 0 5px; }'
    )
    assert style_defs[2] == (
        'span.linenos '
        '{ color: #ff0000; background-color: #0000ff; padding: 0 5px 0 5px; }'
    )
    assert style_defs[3] == (
        'td.linenos pre.special '
        '{ color: #00ff00; background-color: #ffffff; padding: 0 5px 0 5px; }'
    )
    assert style_defs[4] == (
        'span.linenos.special '
        '{ color: #00ff00; background-color: #ffffff; padding: 0 5px 0 5px; }'
    ) 
示例6
def style_from_pygments_cls(pygments_style_cls: Type["PygmentsStyle"]) -> Style:
    """
    Shortcut to create a :class:`.Style` instance from a Pygments style class
    and a style dictionary.

    Example::

        from prompt_toolkit.styles.from_pygments import style_from_pygments_cls
        from pygments.styles import get_style_by_name
        style = style_from_pygments_cls(get_style_by_name('monokai'))

    :param pygments_style_cls: Pygments style class to start from.
    """
    # Import inline.
    from pygments.style import Style as PygmentsStyle

    assert issubclass(pygments_style_cls, PygmentsStyle)

    return style_from_pygments_dict(pygments_style_cls.styles) 
示例7
def set_default_style(style):
    """Sets default global style to be used by ``prettyprinter.cpprint``.

    :param style: the style to set, either subclass of
                  ``pygments.styles.Style`` or one of ``'dark'``, ``'light'``
    """
    global default_style
    if style == 'dark':
        style = default_dark_style
    elif style == 'light':
        style = default_light_style

    if not issubclass(style, Style):
        raise TypeError(
            "style must be a subclass of pygments.styles.Style or "
            "one of 'dark', 'light'. Got {}".format(repr(style))
        )
    default_style = style 
示例8
def test_override_missing_value_with_style():
    """Test that *override_missing_value()* styles output."""

    class NullStyle(Style):
        styles = {
            Token.Output.Null: '#0f0'
        }

    headers = ['h1', 'h2']
    data = [[None, '2'], ['abc', None]]

    expected_headers = ['h1', 'h2']
    expected_data = [
        ['\x1b[38;5;10m<null>\x1b[39m', '2'],
        ['abc', '\x1b[38;5;10m<null>\x1b[39m']
    ]
    results = override_missing_value(data, headers, 
                                     style=NullStyle, missing_value="<null>")

    assert (expected_data, expected_headers) == (list(results[0]), results[1]) 
示例9
def test_style_output():
    """Test that *style_output()* styles output."""

    class CliStyle(Style):
        default_style = ""
        styles = {
            Token.Output.Header: 'bold ansibrightred',
            Token.Output.OddRow: 'bg:#eee #111',
            Token.Output.EvenRow: '#0f0'
        }
    headers = ['h1', 'h2']
    data = [['观音', '2'], ['Ποσειδῶν', 'b']]

    expected_headers = ['\x1b[91;01mh1\x1b[39;00m', '\x1b[91;01mh2\x1b[39;00m']
    expected_data = [['\x1b[38;5;233;48;5;7m观音\x1b[39;49m',
                      '\x1b[38;5;233;48;5;7m2\x1b[39;49m'],
                     ['\x1b[38;5;10mΠοσειδῶν\x1b[39m', '\x1b[38;5;10mb\x1b[39m']]
    results = style_output(data, headers, style=CliStyle)

    assert (expected_data, expected_headers) == (list(results[0]), results[1]) 
示例10
def test_style_output_custom_tokens():
    """Test that *style_output()* styles output with custom token names."""

    class CliStyle(Style):
        default_style = ""
        styles = {
            Token.Results.Headers: 'bold ansibrightred',
            Token.Results.OddRows: 'bg:#eee #111',
            Token.Results.EvenRows: '#0f0'
        }
    headers = ['h1', 'h2']
    data = [['1', '2'], ['a', 'b']]

    expected_headers = ['\x1b[91;01mh1\x1b[39;00m', '\x1b[91;01mh2\x1b[39;00m']
    expected_data = [['\x1b[38;5;233;48;5;7m1\x1b[39;49m',
                      '\x1b[38;5;233;48;5;7m2\x1b[39;49m'],
                     ['\x1b[38;5;10ma\x1b[39m', '\x1b[38;5;10mb\x1b[39m']]

    output = style_output(
        data, headers, style=CliStyle,
        header_token='Token.Results.Headers',
        odd_row_token='Token.Results.OddRows',
        even_row_token='Token.Results.EvenRows')

    assert (expected_data, expected_headers) == (list(output[0]), output[1]) 
示例11
def style_factory_output(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name).styles
    except ClassNotFound:
        style = pygments.styles.get_style_by_name('native').styles

    for token in cli_style:
        if token.startswith('Token.'):
            token_type, style_value = parse_pygments_style(
                token, style, cli_style)
            style.update({token_type: style_value})
        elif token in PROMPT_STYLE_TO_TOKEN:
            token_type = PROMPT_STYLE_TO_TOKEN[token]
            style.update({token_type: cli_style[token]})
        else:
            # TODO: cli helpers will have to switch to ptk.Style
            logger.error('Unhandled style / class name: %s', token)

    class OutputStyle(PygmentsStyle):   # pylint: disable=too-few-public-methods
        default_style = ""
        styles = style

    return OutputStyle 
示例12
def __init__(
        self,
        code: str,
        lexer_name: str,
        *,
        theme: Union[str, Type[PygmentsStyle]] = DEFAULT_THEME,
        dedent: bool = False,
        line_numbers: bool = False,
        start_line: int = 1,
        line_range: Tuple[int, int] = None,
        highlight_lines: Set[int] = None,
        code_width: Optional[int] = None,
        tab_size: int = 4,
        word_wrap: bool = False
    ) -> None:
        self.code = code
        self.lexer_name = lexer_name
        self.dedent = dedent
        self.line_numbers = line_numbers
        self.start_line = start_line
        self.line_range = line_range
        self.highlight_lines = highlight_lines or set()
        self.code_width = code_width
        self.tab_size = tab_size
        self.word_wrap = word_wrap

        self._style_cache: Dict[Any, Style] = {}

        if not isinstance(theme, str) and issubclass(theme, PygmentsStyle):
            self._pygments_style_class = theme
        else:
            try:
                self._pygments_style_class = get_style_by_name(theme)
            except ClassNotFound:
                self._pygments_style_class = get_style_by_name("default")
        self._background_color = self._pygments_style_class.background_color 
示例13
def style_from_dict(d):
        styles = default_style_extensions.copy()
        styles.update(DefaultStyle.styles)
        styles.update(d)
        PromptStyle = type('PromptStyle', (Style,), {'styles': styles})
        return PromptStyle 
示例14
def test_style_factory():
    """Test that a Pygments Style class is created."""
    header = "bold underline #ansired"
    cli_style = {"Token.Output.Header": header}
    style = style_factory("default", cli_style)

    assert isinstance(style(), Style)
    assert Token.Output.Header in style.styles
    assert header == style.styles[Token.Output.Header] 
示例15
def test_style_factory_unknown_name():
    """Test that an unrecognized name will not throw an error."""
    style = style_factory("foobar", {})

    assert isinstance(style(), Style) 
示例16
def override_missing_value(data, headers, style=None,
                           missing_value_token="Token.Output.Null",
                           missing_value='', **_):
    """Override missing values in the *data* with *missing_value*.

    A missing value is any value that is :data:`None`.

    :param iterable data: An :term:`iterable` (e.g. list) of rows.
    :param iterable headers: The column headers.
    :param style: Style for missing_value.
    :param missing_value_token: The Pygments token used for missing data.
    :param missing_value: The default value to use for missing data.
    :return: The processed data and headers.
    :rtype: tuple

    """
    def fields():
        for row in data:
            processed = []
            for field in row:
                if field is None and style and HAS_PYGMENTS:
                    styled = utils.style_field(missing_value_token, missing_value, style)
                    processed.append(styled)
                elif field is None:
                    processed.append(missing_value)
                else:
                    processed.append(field)
            yield processed

    return (fields(), headers) 
示例17
def test_style_output_table():
    """Test that *style_output_table()* styles the output table."""

    class CliStyle(Style):
        default_style = ""
        styles = {
            Token.Output.TableSeparator: 'ansibrightred',
        }
    headers = ['h1', 'h2']
    data = [['观音', '2'], ['Ποσειδῶν', 'b']]
    style_output_table = terminaltables_adapter.style_output_table('ascii')

    style_output_table(data, headers, style=CliStyle)
    output = terminaltables_adapter.adapter(iter(data), headers, table_format='ascii')

    assert "\n".join(output) == dedent('''\
        \x1b[91m+\x1b[39m''' + (
          ('\x1b[91m-\x1b[39m' * 10) +
          '\x1b[91m+\x1b[39m' +
          ('\x1b[91m-\x1b[39m' * 4)) +
        '''\x1b[91m+\x1b[39m
        \x1b[91m|\x1b[39m h1       \x1b[91m|\x1b[39m''' +
        ''' h2 \x1b[91m|\x1b[39m
        ''' + '\x1b[91m+\x1b[39m' + (
          ('\x1b[91m-\x1b[39m' * 10) +
          '\x1b[91m+\x1b[39m' +
          ('\x1b[91m-\x1b[39m' * 4)) +
        '''\x1b[91m+\x1b[39m
        \x1b[91m|\x1b[39m 观音     \x1b[91m|\x1b[39m''' +
        ''' 2  \x1b[91m|\x1b[39m
        \x1b[91m|\x1b[39m Ποσειδῶν \x1b[91m|\x1b[39m''' +
        ''' b  \x1b[91m|\x1b[39m
        ''' + '\x1b[91m+\x1b[39m' + (
          ('\x1b[91m-\x1b[39m' * 10) +
          '\x1b[91m+\x1b[39m' +
          ('\x1b[91m-\x1b[39m' * 4)) +
        '\x1b[91m+\x1b[39m') 
示例18
def test_style_output_table():
    """Test that *style_output_table()* styles the output table."""

    class CliStyle(Style):
        default_style = ""
        styles = {
            Token.Output.TableSeparator: 'ansibrightred',
        }
    headers = ['h1', 'h2']
    data = [['观音', '2'], ['Ποσειδῶν', 'b']]
    style_output_table = tabulate_adapter.style_output_table('psql')

    style_output_table(data, headers, style=CliStyle)
    output = tabulate_adapter.adapter(iter(data), headers, table_format='psql')

    assert "\n".join(output) == dedent('''\
        \x1b[91m+\x1b[39m''' + (
          ('\x1b[91m-\x1b[39m' * 10) +
          '\x1b[91m+\x1b[39m' +
          ('\x1b[91m-\x1b[39m' * 6)) +
        '''\x1b[91m+\x1b[39m
        \x1b[91m|\x1b[39m h1       \x1b[91m|\x1b[39m''' +
        ''' h2   \x1b[91m|\x1b[39m
        ''' + '\x1b[91m|\x1b[39m' + (
          ('\x1b[91m-\x1b[39m' * 10) +
          '\x1b[91m+\x1b[39m' +
          ('\x1b[91m-\x1b[39m' * 6)) +
        '''\x1b[91m|\x1b[39m
        \x1b[91m|\x1b[39m 观音     \x1b[91m|\x1b[39m''' +
        ''' 2    \x1b[91m|\x1b[39m
        \x1b[91m|\x1b[39m Ποσειδῶν \x1b[91m|\x1b[39m''' +
        ''' b    \x1b[91m|\x1b[39m
        ''' + '\x1b[91m+\x1b[39m' + (
          ('\x1b[91m-\x1b[39m' * 10) +
          '\x1b[91m+\x1b[39m' +
          ('\x1b[91m-\x1b[39m' * 6)) +
        '\x1b[91m+\x1b[39m') 
示例19
def style_from_pygments(style_cls=pygments_DefaultStyle,
                        style_dict=None,
                        include_defaults=True):
    """
    Shortcut to create a :class:`.Style` instance from a Pygments style class
    and a style dictionary.

    Example::

        from prompt_toolkit.styles.from_pygments import style_from_pygments
        from pygments.styles import get_style_by_name
        style = style_from_pygments(get_style_by_name('monokai'))

    :param style_cls: Pygments style class to start from.
    :param style_dict: Dictionary for this style. `{Token: style}`.
    :param include_defaults: (`bool`) Include prompt_toolkit extensions.
    """
    assert style_dict is None or isinstance(style_dict, dict)
    assert style_cls is None or issubclass(style_cls, pygments_Style)

    styles_dict = {}

    if style_cls is not None:
        styles_dict.update(style_cls.styles)

    if style_dict is not None:
        styles_dict.update(style_dict)

    return style_from_dict(styles_dict, include_defaults=include_defaults) 
示例20
def __new__(cls, pygments_style_cls):
        assert issubclass(pygments_style_cls, pygments_Style)
        return style_from_dict(pygments_style_cls.styles) 
示例21
def from_path(
        cls,
        path: str,
        encoding: str = "utf-8",
        theme: Union[str, Type[PygmentsStyle]] = DEFAULT_THEME,
        dedent: bool = True,
        line_numbers: bool = False,
        line_range: Tuple[int, int] = None,
        start_line: int = 1,
        highlight_lines: Set[int] = None,
        code_width: Optional[int] = None,
        tab_size: int = 4,
        word_wrap: bool = False,
    ) -> "Syntax":
        """Construct a Syntax object from a file.
        
        Args:
            path (str): Path to file to highlight.
            encoding (str): Encoding of file.
            lexer_name (str): Lexer to use (see https://pygments.org/docs/lexers/)
            theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "emacs".
            dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True.
            line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
            start_line (int, optional): Starting number for line numbers. Defaults to 1.
            line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render.
            highlight_lines (Set[int]): A set of line numbers to highlight.
            code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
            tab_size (int, optional): Size of tabs. Defaults to 4.
            word_wrap (bool, optional): Enable word wrapping of code.

        Returns:
            [Syntax]: A Syntax object that may be printed to the console
        """
        with open(path, "rt", encoding=encoding) as code_file:
            code = code_file.read()
        try:
            lexer = guess_lexer_for_filename(path, code)
            lexer_name = lexer.name
        except ClassNotFound:
            lexer_name = "default"
        return cls(
            code,
            lexer_name,
            theme=theme,
            dedent=dedent,
            line_numbers=line_numbers,
            line_range=line_range,
            start_line=start_line,
            highlight_lines=highlight_lines,
            code_width=code_width,
            word_wrap=word_wrap,
        ) 
示例22
def style_output(data, headers, style=None,
                 header_token='Token.Output.Header',
                 odd_row_token='Token.Output.OddRow',
                 even_row_token='Token.Output.EvenRow', **_):
    """Style the *data* and *headers* (e.g. bold, italic, and colors)

    .. NOTE::
        This requires the `Pygments <http://pygments.org/>`_ library to
        be installed. You can install it with CLI Helpers as an extra::
            $ pip install cli_helpers[styles]

    Example usage::

        from cli_helpers.tabular_output.preprocessors import style_output
        from pygments.style import Style
        from pygments.token import Token

        class YourStyle(Style):
            default_style = ""
            styles = {
                Token.Output.Header: 'bold ansibrightred',
                Token.Output.OddRow: 'bg:#eee #111',
                Token.Output.EvenRow: '#0f0'
            }

        headers = ('First Name', 'Last Name')
        data = [['Fred', 'Roberts'], ['George', 'Smith']]

        data, headers = style_output(data, headers, style=YourStyle)

    :param iterable data: An :term:`iterable` (e.g. list) of rows.
    :param iterable headers: The column headers.
    :param str/pygments.style.Style style: A Pygments style. You can `create
        your own styles <https://pygments.org/docs/styles#creating-own-styles>`_.
    :param str header_token: The token type to be used for the headers.
    :param str odd_row_token: The token type to be used for odd rows.
    :param str even_row_token: The token type to be used for even rows.
    :return: The styled data and headers.
    :rtype: tuple

    """
    if style and HAS_PYGMENTS:
        headers = [utils.style_field(header_token, header, style) for header in headers]
        data = ([utils.style_field(odd_row_token if i % 2 else even_row_token, f, style)
                 for f in r] for i, r in enumerate(data, 1))

    return iter(data), headers 
示例23
def style_output_table(format_name=""):
    def style_output(data, headers, style=None,
                     table_separator_token='Token.Output.TableSeparator', **_):
        """Style the *table* (e.g. bold, italic, and colors)

        .. NOTE::
            This requires the `Pygments <http://pygments.org/>`_ library to
            be installed. You can install it with CLI Helpers as an extra::
                $ pip install cli_helpers[styles]

        Example usage::

            from cli_helpers.tabular_output import terminaltables_adapter
            from pygments.style import Style
            from pygments.token import Token

            class YourStyle(Style):
                default_style = ""
                styles = {
                    Token.Output.TableSeparator: '#ansigray'
                }

            headers = ('First Name', 'Last Name')
            data = [['Fred', 'Roberts'], ['George', 'Smith']]
            style_output_table = terminaltables_adapter.style_output_table('psql')
            style_output_table(data, headers, style=CliStyle)

            output = terminaltables_adapter.adapter(data, headers, style=YourStyle)

        :param iterable data: An :term:`iterable` (e.g. list) of rows.
        :param iterable headers: The column headers.
        :param str/pygments.style.Style style: A Pygments style. You can `create
            your own styles <https://pygments.org/docs/styles#creating-own-styles>`_.
        :param str table_separator_token: The token type to be used for the table separator.
        :return: data and headers.
        :rtype: tuple

        """
        if style and HAS_PYGMENTS and format_name in supported_formats:
            formatter = Terminal256Formatter(style=style)

            def style_field(token, field):
                """Get the styled text for a *field* using *token* type."""
                s = StringIO()
                formatter.format(((token, field),), s)
                return s.getvalue()

            clss = table_format_handler[format_name]
            for char in [char for char in terminaltables.base_table.BaseTable.__dict__ if char.startswith("CHAR_")]:
                setattr(clss, char, style_field(
                    table_separator_token, getattr(clss, char)))

        return iter(data), headers
    return style_output