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


Python pygments.lexers方法代码示例

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


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

示例1: _show_source_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [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: _get_source_highlight_function

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [as 别名]
def _get_source_highlight_function(self):
        try:
            import pygments
            import pygments.lexers
        except ImportError:
            return False

        try:
            pygments_formatter = self._get_pygments_formatter()
        except Exception as exc:
            self.message("pdb++: could not setup Pygments, disabling: {}".format(
                exc
            ))
            return False

        lexer = pygments.lexers.PythonLexer(stripnl=False)

        def syntax_highlight(src):
            return pygments.highlight(src, lexer, pygments_formatter)

        return syntax_highlight 
开发者ID:pdbpp,项目名称:pdbpp,代码行数:23,代码来源:pdbpp.py

示例3: test_highlight_renderer

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [as 别名]
def test_highlight_renderer(monkeypatch):
    monkeypatch.setattr(mistune, "escape", mock.MagicMock())
    monkeypatch.setattr(lexers, "get_lexer_by_name", mock.MagicMock())
    monkeypatch.setattr(html, "HtmlFormatter", mock.MagicMock())
    monkeypatch.setattr(pygments, "highlight", mock.MagicMock())

    lexers.get_lexer_by_name.return_value = True
    html.HtmlFormatter.return_value = {}

    r = renderer.HighlightRenderer()
    r.block_code("code")

    mistune.escape.assert_called_with("code")

    r.block_code("code", "python")
    lexers.get_lexer_by_name.assert_called_with("python", stripall=True)
    pygments.highlight.assert_called_with("code", True, {}) 
开发者ID:chris104957,项目名称:maildown,代码行数:19,代码来源:test_renderer.py

示例4: printargs

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [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

示例5: add_argparser

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [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

示例6: _render_execution_errors

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [as 别名]
def _render_execution_errors(self, formatter):
        """ Renders stack traces of those executions which failed
        """
        tb_lexer = pygments.lexers.get_lexer_by_name("py3tb", stripall=True)

        executions = []

        for orig_execution in self.eoexecutor.execution_stats:
            execution = copy.deepcopy(orig_execution)

            if self.eoexecutor.STATS_ERROR in execution:
                execution[self.eoexecutor.STATS_ERROR] = pygments.highlight(execution[self.eoexecutor.STATS_ERROR],
                                                                            tb_lexer, formatter)

            executions.append(execution)

        return executions 
开发者ID:sentinel-hub,项目名称:eo-learn,代码行数:19,代码来源:eoexecutor_visualization.py

示例7: get_diff

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [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

示例8: _colorize

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [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

示例9: get_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [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

示例10: _add_syntax_highlighting

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [as 别名]
def _add_syntax_highlighting(self, insource, language):
        lexer = pygments.lexers.get_lexer_by_name(language, stripall=True)
        if language in ('latex', 'tex'):
            fmtr = OdtPygmentsLaTeXFormatter(lambda name, parameters=():
                self.rststyle(name, parameters),
                escape_function=escape_cdata)
        else:
            fmtr = OdtPygmentsProgFormatter(lambda name, parameters=():
                self.rststyle(name, parameters),
                escape_function=escape_cdata)
        outsource = pygments.highlight(insource, lexer, fmtr)
        return outsource 
开发者ID:skarlekar,项目名称:faces,代码行数:14,代码来源:__init__.py

示例11: Code

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [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

示例12: parse

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [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

示例13: highlight_code

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [as 别名]
def highlight_code(code, language, cssclass='codehilite'):
        try:
            lexer = pygments.lexers.get_lexer_by_name(language)
        except pygments.util.ClassNotFound:
            return _make_pre_code(code)

        # return mark_safe(pygments.highlight(code, lexer, HtmlCodeFormatter(cssclass=cssclass, linenos='table')))
        return mark_safe(pygments.highlight(code, lexer, HtmlCodeFormatter(cssclass=cssclass))) 
开发者ID:DMOJ,项目名称:online-judge,代码行数:10,代码来源:highlight_code.py

示例14: fill_read_cache

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [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: get_pygments

# 需要导入模块: import pygments [as 别名]
# 或者: from pygments import lexers [as 别名]
def get_pygments(self):
        if self.__pygments is not None:
            return self.__pygments
        # try pygments for pretty printing if available
        try:
            import pygments
            import pygments.lexers
            import pygments.formatters
        except ImportError:
            pygments = None
        self.__pygments = pygments
        return self.__pygments 
开发者ID:naparuba,项目名称:opsbro,代码行数:14,代码来源:library.py


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