本文整理汇总了Python中pygments.formatters.html.HtmlFormatter类的典型用法代码示例。如果您正苦于以下问题:Python HtmlFormatter类的具体用法?Python HtmlFormatter怎么用?Python HtmlFormatter使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HtmlFormatter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _highlight_lines
def _highlight_lines(self, tokensource):
"""
Highlighted the lines specified in the `hl_lines` option by
post-processing the token stream coming from `_format_lines`.
"""
if not isinstance(self.hl_lines, dict):
HtmlFormatter._highlight_lines(tokensource)
else:
hl_lines = {}
for css, lines in self.hl_lines.items():
hl_lines.update(dict([(line, css) for line in lines]))
hls = hl_lines.keys()
for i, (t, value) in enumerate(tokensource):
if t != 1:
yield t, value
if i + 1 in hls: # i + 1 because Python indexes start at 0
css = hl_lines[i + 1]
if css:
yield 1, '<span class="%s">%s</span>' % (css, value)
elif self.noclasses:
style = ''
if self.style.highlight_color is not None:
style = (' style="background-color: %s"' %
(self.style.highlight_color,))
yield 1, '<span%s>%s</span>' % (style, value)
else:
yield 1, '<span class="hll">%s</span>' % value
else:
yield 1, value
示例2: process_request
def process_request(self, req):
style = req.args['style']
try:
style_cls = get_style_by_name(style)
except ValueError as e:
raise HTTPNotFound(e)
parts = style_cls.__module__.split('.')
filename = resource_filename('.'.join(parts[:-1]), parts[-1] + '.py')
mtime = datetime.fromtimestamp(os.path.getmtime(filename), localtz)
last_modified = http_date(mtime)
if last_modified == req.get_header('If-Modified-Since'):
req.send_response(304)
req.end_headers()
return
formatter = HtmlFormatter(style=style_cls)
content = u'\n\n'.join([
formatter.get_style_defs('div.code pre'),
formatter.get_style_defs('table.code td')
]).encode('utf-8')
req.send_response(200)
req.send_header('Content-Type', 'text/css; charset=utf-8')
req.send_header('Last-Modified', last_modified)
req.send_header('Content-Length', len(content))
req.write(content)
示例3: prev_view_code
def prev_view_code(self, code, laugange):
htmlFormatter = HtmlFormatter()
lexer = CppLexer()
if laugange == "Cpp":
lexer = CppLexer()
elif laugange == "CSharp":
lexer = CSharpLexer()
codeDiv = highlight(code, lexer, htmlFormatter)
codeCss = htmlFormatter.get_style_defs(".highlight")
#
html = """
<html>
<head>
<style type="text/css">
%s
</style>
</head>
<body>
%s
</body>
</html>
""" % (codeCss, codeDiv)
self.webView.setHtml(html)
self.setStyleSheet(codeCss)
# 输出文件测试验证
# ff = open('test.html', 'w')
# ff.write(html)
# ff.close()
pass
示例4: render_code
def render_code(self):
formatter = HtmlFormatter(style='default', nowrap=True, classprefix='code%s-' % self.pk)
html = highlight(self.code, get_lexer_by_name(self.syntax), formatter)
css = formatter.get_style_defs()
# Included in a DIV, so the next item will be displayed below.
return _('<div class="code"><style type="text/css">%(css)s</style>\n<pre>%(html)s</pre></div>\n') % {'css':css, 'html':html}
示例5: _bbcodeAsHtml
def _bbcodeAsHtml(self):
style = get_style_by_name('igor')
formatter = HtmlFormatter(style=style)
lexer = get_lexer_by_name("bbcode", stripall=True)
css = formatter.get_style_defs()
txt = highlight(self._bbcode, lexer, HtmlFormatter())
return "<style>%s</style>\n%s" % (css, txt)
示例6: highlight_paste
def highlight_paste(paste, hl_lines):
'''Use pygments to syntax highlight a paste, returns by the way the CSS'''
lexer = get_lexer_by_name(paste.hl_alias)
formatter = HtmlFormatter(linenos=True, cssclass='source', hl_lines=hl_lines)
return (
highlight(paste.content, lexer, formatter),
formatter.get_style_defs('.source')
)
示例7: style_defs
def style_defs(cls):
"""
Return the CSS style definitions required
by the formatted snippet.
"""
formatter = HtmlFormatter()
formatter.style.highlight_color = cls.VIOLATION_COLOR
return formatter.get_style_defs()
示例8: __init__
def __init__(self, **options):
HtmlFormatter.__init__(self, **options)
self.hl_lines = {None: self.hl_lines}
if isinstance(options.get('css_lines'), dict):
for k, lines in options['css_lines'].items():
self.hl_lines[k] = set()
for lineno in lines:
try:
self.hl_lines[k].add(int(lineno))
except ValueError:
pass
示例9: get
def get(self, paste_id):
try:
aid = b64.num_decode(paste_id)
paste = Paste.get_by_id(aid)
content, lang = paste.content, paste.type
formatter = HtmlFormatter()
self.response.out.write(template.render("paste.html", {'css': formatter.get_style_defs('.highlight'),
'paste': highlight(content, get_lexer_by_name(lang), formatter)}))
except Exception:
self.response.set_status(404)
self.response.out.write(template.render("404.html", {}))
示例10: getOutput
def getOutput(self):
"""
Returns the output
:rtype: str
"""
if not self.formatted:
lex = JavaLexer()
formatter = HtmlFormatter(full=True)
formatter.noclasses = True
self._output = highlight(self._output, lex, formatter)
self.formatted = True
return self._output
示例11: render_code
def render_code(instance, style_name='default'):
# Some interesting options in the HtmlFormatter:
# - nowrap -> no wrap inside <pre>
# - classprefix -> prefix for the classnames
# - noclasses -> all inline styles.
#
# To get_style_defs(), you can pass a selector prefix.
#
style = styles.get_style_by_name(style_name)
formatter = HtmlFormatter(linenos=instance.linenumbers, style=style, nowrap=True, classprefix='code%s-' % instance.pk)
html = highlight(instance.code, get_lexer_by_name(instance.language), formatter)
css = formatter.get_style_defs()
# Included in a DIV, so the next item will be displayed below.
return '<div class="code"><style type="text/css">' + css + '</style>\n<pre>' + html + '</pre></div>\n'
示例12: __init__
def __init__(self, parent, lexer=None):
super(PygmentsHighlighter, self).__init__(parent)
self._document = QtGui.QTextDocument()
self._formatter = HtmlFormatter(nowrap=True)
self._lexer = lexer if lexer else PythonLexer()
self.set_style('default')
示例13: __init__
def __init__(self, document, lexer=None):
super(PygmentsSyntaxHighlighter, self).__init__(document)
self._document = QtGui.QTextDocument()
self._formatter = HtmlFormatter(nowrap=True)
self._lexer = lexer if lexer else PythonLexer()
self.__previousFilename = ""
self.style = "default"
示例14: __init__
def __init__(self, parent, lexer=None):
super(QPygmentsHighlighter, self).__init__(parent)
self._document = QtGui.QTextDocument()
self._formatter = HtmlFormatter(nowrap=True)
self._lexer = lexer if lexer else PythonLexer()
self.style = styles.getStyle("Default").pygmentsStyle
self.enabled = True
示例15: process_request
def process_request(self, req):
# settings panel
if not 'style' in req.args:
req._no_pygments_stylesheet = True
styles = list(get_all_styles())
styles.sort(lambda a, b: cmp(a.lower(), b.lower()))
if req.method == 'POST':
style = req.args.get('new_style')
if style and style in styles:
req.session['pygments_style'] = style
output = self._highlight('html', self.EXAMPLE, False)
req.hdf['output'] = Markup(output)
req.hdf['current'] = req.session.get('pygments_style',
self.default_style)
req.hdf['styles'] = styles
req.hdf['pygments_path'] = self.env.href.pygments()
return 'pygments_settings.cs', None
# provide stylesheet
else:
style = req.args['style']
parts = style.__module__.split('.')
filename = resource_filename('.'.join(parts[:-1]), parts[-1] + '.py')
mtime = datetime.utcfromtimestamp(os.path.getmtime(filename))
last_modified = http_date(time.mktime(mtime.timetuple()))
if last_modified == req.get_header('If-Modified-Since'):
req.send_response(304)
req.end_headers()
return
formatter = HtmlFormatter(style=style)
content = u'\n\n'.join([
formatter.get_style_defs('div.code pre'),
formatter.get_style_defs('table.code td')
]).encode('utf-8')
req.send_response(200)
req.send_header('Content-Type', 'text/css; charset=utf-8')
req.send_header('Last-Modified', last_modified)
req.send_header('Content-Length', len(content))
req.write(content)