当前位置: 首页>>代码示例>>Python>>正文


Python pygments.formatters方法代码示例

本文整理汇总了Python中pygments.formatters方法的典型用法代码示例。如果您正苦于以下问题:Python pygments.formatters方法的具体用法?Python pygments.formatters怎么用?Python pygments.formatters使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pygments的用法示例。


在下文中一共展示了pygments.formatters方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _show_source_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def _show_source_pygments(self) -> None:

        def show_source_cb(source: str) -> None:
            """Show source as soon as it's ready."""
            # WORKAROUND for https://github.com/PyCQA/pylint/issues/491
            # pylint: disable=no-member
            lexer = pygments.lexers.HtmlLexer()
            formatter = pygments.formatters.HtmlFormatter(
                full=True, linenos='table')
            # pylint: enable=no-member
            highlighted = pygments.highlight(source, lexer, formatter)

            tb = objreg.get('tabbed-browser', scope='window',
                            window=self._tab.win_id)
            new_tab = tb.tabopen(background=False, related=True)
            new_tab.set_html(highlighted, self._tab.url())
            new_tab.data.viewing_source = True

        self._tab.dump_async(show_source_cb) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:21,代码来源:browsertab.py

示例2: _color_with_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def _color_with_pygments(self, codeblock, lexer, **formatter_opts):
        import pygments
        import pygments.formatters

        class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
            def _wrap_code(self, inner):
                """A function for use in a Pygments Formatter which
                wraps in <code> tags.
                """
                yield 0, "<code>"
                for tup in inner:
                    yield tup
                yield 0, "</code>"

            def wrap(self, source, outfile):
                """Return the source with a code, pre, and div."""
                return self._wrap_div(self._wrap_pre(self._wrap_code(source)))

        formatter_opts.setdefault("cssclass", "codehilite")
        formatter = HtmlCodeFormatter(**formatter_opts)
        return pygments.highlight(codeblock, lexer, formatter) 
开发者ID:b1ueb1ues,项目名称:dl,代码行数:23,代码来源:markdown2.py

示例3: _color_with_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def _color_with_pygments(self, codeblock, lexer, **formatter_opts):
        import pygments
        import pygments.formatters

        class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):

            def _wrap_code(self, inner):
                """A function for use in a Pygments Formatter which
                wraps in <code> tags.
                """
                yield 0, "<code>"
                for tup in inner:
                    yield tup
                yield 0, "</code>"

            def wrap(self, source, outfile):
                """Return the source with a code, pre, and div."""
                return self._wrap_div(self._wrap_pre(self._wrap_code(source)))

        formatter_opts.setdefault("cssclass", "codehilite")
        formatter = HtmlCodeFormatter(**formatter_opts)
        return pygments.highlight(codeblock, lexer, formatter) 
开发者ID:tzshlyt,项目名称:python-webapp-blog,代码行数:24,代码来源:markdown2.py

示例4: _color_with_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def _color_with_pygments(self, codeblock, lexer, **formatter_opts):
        import pygments
        import pygments.formatters

        class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
            def _wrap_code(self, inner):
                """A function for use in a Pygments Formatter which
                wraps in <code> tags.
                """
                yield 0, "<code>"
                for tup in inner:
                    yield tup 
                yield 0, "</code>"

            def wrap(self, source, outfile):
                """Return the source with a code, pre, and div."""
                return self._wrap_div(self._wrap_pre(self._wrap_code(source)))

        formatter = HtmlCodeFormatter(cssclass="codehilite", **formatter_opts)
        return pygments.highlight(codeblock, lexer, formatter) 
开发者ID:omererdem,项目名称:honeything,代码行数:22,代码来源:markdown.py

示例5: generate_css

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def generate_css(base_folder, target_folder):
    log.info("Generating CSS.")
    file_mapping = {}
    target_folder = target_folder
    try:
        target_folder.mkdir(parents=True)
    except FileExistsError:
        pass

    pygments_css = base_folder / '_pygments.scss'
    with open(str(pygments_css), 'w') as fp:
        fp.write(pygments.formatters.HtmlFormatter().get_style_defs(
            '.highlight'))

    for file_ in base_folder.glob('*.scss'):
        if not file_.name.startswith('_'):
            target_path = target_folder / (file_.stem + '.{}.css')
            target_path = compile_sass(file_, target_path)
            file_mapping[file_.name] = target_path.name
    return file_mapping 
开发者ID:ulope,项目名称:pyformat.info,代码行数:22,代码来源:main.py

示例6: printargs

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def printargs():
    """Prints out all command-line parameters."""
    switch = {BGColor.LIGHT: 'xcode',
              BGColor.DARK: 'vim',
              BGColor.UNKNOWN: 'default'}
    style = switch[terminal_bg()]
    pprint = print
    try:
        import pygments
        from pygments.lexers import Python3Lexer
        from pygments.formatters import Terminal256Formatter
        pprint = partial(pygments.highlight, lexer=Python3Lexer(),
                         formatter=Terminal256Formatter(style=style),
                         outfile=sys.stdout)
    except ImportError:
        pass
    print('Parameters:')
    for key in sorted(ARGS):
        v = repr(getattr(ARGS, key))
        print('% 16s: ' % key, end='')
        pprint(v)
    print() 
开发者ID:crowsonkb,项目名称:style_transfer,代码行数:24,代码来源:style_transfer.py

示例7: add_argparser

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def add_argparser(argparser, *args, **kwargs):
        # Python 2 argparse does not support aliases
        if sys.version_info.major < 3 or \
            (sys.version_info.major == 3 and
                sys.version_info.minor < 2):
            parser = argparser.add_parser(DeenPluginSyntaxHighlighter.cmd_name,
                                          help=DeenPluginSyntaxHighlighter.cmd_help)
        else:
            parser = argparser.add_parser(DeenPluginSyntaxHighlighter.cmd_name,
                                          help=DeenPluginSyntaxHighlighter.cmd_help,
                                          aliases=DeenPluginSyntaxHighlighter.aliases)
        parser.add_argument('plugindata', action='store', help='input data', nargs='?')
        parser.add_argument('--list', action='store_true', dest='list',
                            default=False, help='list available lexers')
        parser.add_argument('--list-formatters', action='store_true', dest='listformatters',
                            default=False, help='list available formatters')
        parser.add_argument('-f', '--file', dest='plugininfile', default=None,
                            help='file name or - for STDIN', metavar='filename')
        parser.add_argument('--formatter', help='formatter to use',
                            type=str.lower, default=None, metavar='formatter')
        parser.add_argument('-l', '--lexer', help='hash algorithm for signature', default=None,
                            type=str.lower, metavar='lexer')
        parser.add_argument('-n', '--numbers', action='store_true', dest='numbers',
                            default=False, help='print line numbers') 
开发者ID:takeshixx,项目名称:deen,代码行数:26,代码来源:plugin_highlight.py

示例8: _color_with_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def _color_with_pygments(self, codeblock, lexer, **formatter_opts):
        import pygments
        import pygments.formatters

        class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
            def _wrap_code(self, inner):
                """A function for use in a Pygments Formatter which
                wraps in <code> tags.
                """
                yield 0, "<code>"
                for tup in inner:
                    yield tup
                yield 0, "</code>"

            def wrap(self, source, outfile):
                """Return the source with a code, pre, and div."""
                return self._wrap_div(self._wrap_pre(self._wrap_code(source)))

        formatter = HtmlCodeFormatter(cssclass="codehilite", **formatter_opts)
        return pygments.highlight(codeblock, lexer, formatter) 
开发者ID:uwdata,项目名称:termite-visualizations,代码行数:22,代码来源:markdown2.py

示例9: get_diff

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def get_diff() -> str:
    """Get a HTML diff for the old config files."""
    old_conf_lines = []  # type: typing.MutableSequence[str]
    old_key_lines = []  # type: typing.MutableSequence[str]

    for filename, dest in [('qutebrowser.conf', old_conf_lines),
                           ('keys.conf', old_key_lines)]:
        path = os.path.join(standarddir.config(), filename)

        with open(path, 'r', encoding='utf-8') as f:
            for line in f:
                if not line.strip() or line.startswith('#'):
                    continue
                dest.append(line.rstrip())

    conf_delta = difflib.unified_diff(OLD_CONF.lstrip().splitlines(),
                                      old_conf_lines)
    key_delta = difflib.unified_diff(OLD_KEYS_CONF.lstrip().splitlines(),
                                     old_key_lines)

    conf_diff = '\n'.join(conf_delta)
    key_diff = '\n'.join(key_delta)

    # pylint: disable=no-member
    # WORKAROUND for https://bitbucket.org/logilab/pylint/issue/491/
    lexer = pygments.lexers.DiffLexer()
    formatter = pygments.formatters.HtmlFormatter(
        full=True, linenos='table',
        title='Diffing pre-1.0 default config with pre-1.0 modified config')
    # pylint: enable=no-member
    return pygments.highlight(conf_diff + key_diff, lexer, formatter) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:33,代码来源:configdiff.py

示例10: _colorize

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def _colorize(content: str) -> str:
        try:
            import pygments
            import pygments.lexers
            import pygments.formatters
        except ImportError:
            return content
        content = pygments.highlight(
            code=content,
            lexer=pygments.lexers.MarkdownLexer(),
            formatter=pygments.formatters.TerminalFormatter(),
        )
        return content.strip() 
开发者ID:dephell,项目名称:dephell,代码行数:15,代码来源:deps_tree.py

示例11: get_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def get_pygments():
    try:
        import pygments
        from pygments.lexers import PythonLexer
        from pygments.formatters import Terminal256Formatter
    except ImportError:  # pragma: no cover
        return None, None, None
    else:
        return pygments, PythonLexer(), Terminal256Formatter(style='vim') 
开发者ID:samuelcolvin,项目名称:python-devtools,代码行数:11,代码来源:prettier.py

示例12: Code

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def Code(language):

    class ColoredCode(str):
        """Piece of source code. (extends str)
        Takes a string representing a portion of source code.

        When printed or when self.__str__() is called the code will be
        formated using pygments if possible. self._code_value() is used
        to retrieve the code to be formated, its default implementation
        is to use self.__call__().
        """

        if USE_PYGMENTS:
            lexer = pygments.lexers.get_lexer_by_name(language)
            if ui.output.colors() >= 256:
                formatter = pygments.formatters.Terminal256Formatter
            else:
                formatter = pygments.formatters.TerminalFormatter
            formatter = formatter(style='vim', bg='dark')

        def _raw_value(self):
            return super().__str__()

        def __call__(self):
            return self._raw_value()

        def _code_value(self):
            return self.__call__()

        def __str__(self):
            string = self._code_value()
            if not USE_PYGMENTS:
                return string
            return pygments.highlight(string,
                                      self.lexer,
                                      self.formatter).strip()

    return ColoredCode 
开发者ID:nil0x42,项目名称:phpsploit,代码行数:40,代码来源:Code.py

示例13: parse

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def parse(data, key):
    fp = BytesIO(data)
    build_dictionary(fp, key)
    records = Record.parse(fp)
    out = StringIO()
    print_records(records, fp=out)
    out.seek(0)

    if pygments is not None:
        print(pygments.highlight(out.read(),
                                 pygments.lexers.get_lexer_by_name('XML'),
                                 pygments.formatters.get_formatter_by_name('terminal')))
    else:
        print(out.read()) 
开发者ID:ernw,项目名称:net.tcp-proxy,代码行数:16,代码来源:protocol2xml.py

示例14: fill_read_cache

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def fill_read_cache(self, filename: str, line: int) -> None:
        try:
            lexer = pygments.lexers.get_lexer_for_filename(
                str(filename)
            )  # type: RegexLexer
            formatter_opts = dict(linenos="inline", linespans="line", hl_lines=[line])
            html_formatter = pygments.formatters.get_formatter_by_name(
                "html", **formatter_opts
            )
            css = html_formatter.get_style_defs(".highlight")
            with open(str(filename)) as f:
                lines = f.readlines()
            if len(lines) < 1000:
                content = "".join(lines)
                tokens = lexer.get_tokens(content)
                source = pygments.format(tokens, html_formatter)
                self.file_cache[filename][line] = (css, source)
                self.file_read_cache[filename] = (lexer, content, False)
            else:
                minl = max(0, line - 30)
                maxl = min(len(lines), line + 30)
                formatter_opts = dict(
                    linenos="inline", linespans="line", hl_lines=[line]
                )
                html_formatter = pygments.formatters.get_formatter_by_name(
                    "html", **formatter_opts
                )
                css = html_formatter.get_style_defs(".highlight")
                source = pygments.format(
                    lexer.get_tokens("".join(lines[minl:maxl])), html_formatter
                )
                self.file_cache[filename][line] = (css, source)
                self.file_read_cache[filename] = (lexer, lines, True)
        except Exception as e:
            l.exception(e)
            self.file_cache[filename][line] = (None, None)
            self.file_read_cache[filename] = (None, None, False) 
开发者ID:hase-project,项目名称:hase,代码行数:39,代码来源:__init__.py

示例15: fill_file_cache

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import formatters [as 别名]
def fill_file_cache(self, filename: str, line: int) -> None:
        lexer, content, is_largefile = self.file_read_cache[filename]
        if lexer and content:
            try:
                if not is_largefile:
                    formatter_opts = dict(
                        linenos="inline", linespans="line", hl_lines=[line]
                    )
                    html_formatter = pygments.formatters.get_formatter_by_name(
                        "html", **formatter_opts
                    )
                    css = html_formatter.get_style_defs(".highlight")
                    source = pygments.format(lexer.get_tokens(content), html_formatter)
                    self.file_cache[filename][line] = (css, source)
                else:
                    minl = max(0, line - 30)
                    maxl = min(len(content), line + 30)
                    formatter_opts = dict(
                        linenos="inline", linespans="line", hl_lines=[line - minl]
                    )
                    html_formatter = pygments.formatters.get_formatter_by_name(
                        "html", **formatter_opts
                    )
                    css = html_formatter.get_style_defs(".highlight")
                    source = pygments.format(
                        lexer.get_tokens("".join(content[minl:maxl])), html_formatter
                    )
                    self.file_cache[filename][line] = (css, source)
            except Exception as e:
                l.exception(e)
                self.file_cache[filename][line] = (None, None)
        else:
            self.file_cache[filename][line] = (None, None) 
开发者ID:hase-project,项目名称:hase,代码行数:35,代码来源:__init__.py


注:本文中的pygments.formatters方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。