當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。