本文整理汇总了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)
示例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
示例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, {})
示例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()
示例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')
示例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
示例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)
示例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()
示例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')
示例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
示例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
示例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())
示例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)))
示例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)
示例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