def block_code(text, lang, inlinestyles=False, linenos=False):
if not lang:
text = text.strip()
return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)
try:
lexer = get_lexer_by_name(lang, stripall=True)
formatter = html.HtmlFormatter(
noclasses=inlinestyles, linenos=linenos
)
code = highlight(text, lexer, formatter)
if linenos:
return '<div class="highlight-wrapper">%s</div>\n' % code
return code
except BaseException:
return '<pre class="%s"><code>%s</code></pre>\n' % (
lang, mistune.escape(text)
)
python类HtmlFormatter()的实例源码
def _format_code(html_code):
# syntax highlighting:
code_highlighted = highlight(html_code, HtmlLexer(), HtmlFormatter(style='monokai', noclasses=True))
# add formatting for diff-markers:
common_diff_style = ' margin-right: 3px; padding-right: 7px; padding-left: 7px;'
code_formatted = code_highlighted \
.replace('[-', '<span style="background: #71332c;' + common_diff_style + '">') \
.replace('-]', '</span>') \
.replace('{+', '<span style="background: #2e4d28;' + common_diff_style + '">') \
.replace('+}', '</span>')
# wrap in general layout:
code_wrapped = '<div style="color: #efefef; margin: 3px; margin-left: 17px;line-height: 150%%;">%s</div>'\
%(code_formatted)
return code_wrapped
def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = self.linenos and 'table' or False
options = self.title and {'title': self.title} or {}
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)
# limit the number of instances retained
snippets = Snippet.objects.all()
if len(snippets) > 100:
snippets[0].delete()
def block_code(text, lang, inlinestyles=False, linenos=False):
if not lang:
text = text.strip()
return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)
try:
lexer = get_lexer_by_name(lang, stripall=True)
formatter = html.HtmlFormatter(
noclasses=inlinestyles, linenos=linenos
)
code = highlight(text, lexer, formatter)
if linenos:
return '<div class="highlight">%s</div>\n' % code
return code
except:
return '<pre class="%s"><code>%s</code></pre>\n' % (
lang, mistune.escape(text)
)
def get_context(self, morpheus_api):
method = self.request.match_info['method']
message_id = self.request.match_info['id']
url = self.app.router['user-messages'].url_for(method=method).with_query({'message_id': message_id})
r = await morpheus_api.get(url)
data = await r.json()
data = json.dumps(data, indent=2)
data = re.sub('14\d{8,11}', self.replace_data, data)
preview_path = morpheus_api.modify_url(self.app.router['user-preview'].url_for(method=method, id=message_id))
deets_path = morpheus_api.modify_url(self.app.router['user-message-get'].url_for(method=method, id=message_id))
return dict(
sub_heading=f'Message {message_id}',
preview_url=self.full_url(preview_path),
details_url=self.full_url(deets_path),
json_display=highlight(data, JsonLexer(), HtmlFormatter()),
form_action=self.app.router['admin-list'].url_for(),
)
def run(self):
while True:
# wait for next element
element = self.queue.get()
if element is None or element.tag is Comment:
self.return_signal.emit("")
continue
element = XML(tostring(element))
# process the element
deannotate(element, cleanup_namespaces=True)
code = tostring(element, encoding="Unicode", pretty_print=True, xml_declaration=False)
self.return_signal.emit(highlight(code, XmlLexer(), HtmlFormatter(
noclasses=True, style="autumn", linenos="table"
)))
def blockcode(self, text, lang):
if not lang:
return '\n<pre><code>{}</code></pre>\n'.format(houdini.escape_html(text.strip()))
lexer = get_lexer_by_name(lang)
formatter = HtmlFormatter()
return highlight(text, lexer, formatter)
def __init__(self, config, site):
""" Initialize a new parser for a given type of parsing
Args:
confi (obj_dict): the parser config. It is explicitly defined to allows different conf
site (dictobj): sitefab instantiated object
Return:
None
note: one parser is instanciated by thread. potentially batching more than one post per thread might help with performance.
"""
# verify that the config exist
self.config = config
self.site = site
# NOTE: Might seems weird to do this but templates is what allows to have different rendering for each plugins.
# So we keep it explict in the code as this got messed up countless time :(
self.templates = self.config.templates
# NOTE: This part must be done at parsing time to let plugins time to be loaded/executed.
# Replacing standard template with the one injected by plugins
for elt, template in self.config.injected_html_templates.items():
self.templates[elt] = template
# templates are not compiled yet, they will be when parsing will be called the first time
self.jinja2 = None
# markdown parser
self.renderer = HTMLRenderer()
self.md_parser = mistune.Markdown(renderer=self.renderer)
#code higlighterr
if self.config.code_display_line_num:
linenos = 'table'
else:
linenos = False
self.code_formatter = html.HtmlFormatter(style=self.config.code_highlighting_theme, nobackground=False, linenos=linenos)
def blockcode(self, text, lang):
if not lang:
return '\n<pre><code>{}</code></pre>\n'.format(text.strip())
lexer = get_lexer_by_name(lang, stripall=True)
formatter = HtmlFormatter()
return highlight(code=text, lexer=lexer, formatter=formatter)
def block_code(self, code, lang):
lang = CODE_LANG
if not lang:
return '\n<pre><code>%s</code></pre>\n' % \
mistune.escape(code)
lexer = get_lexer_by_name(lang, stripall=True)
formatter = html.HtmlFormatter()
return highlight(code, lexer, formatter)
# renderer = HighlightRenderer()
# markdown = mistune.Markdown(renderer=renderer)
# print(markdown('```python\nassert 1 == 1\n```'))
def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = self.linenos and 'table' or False
options = self.title and {'title': self.title} or {}
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)
def block_code(self, code, lang):
guess = 'python3'
if code.lstrip().startswith('<?php'):
guess = 'php'
elif code.lstrip().startswith('<'):
guess = 'html'
elif code.lstrip().startswith(('function', 'var', '$')):
guess = 'javascript'
lexer = get_lexer_by_name(lang or guess, stripall=True)
formatter = html.HtmlFormatter()
return highlight(code, lexer, formatter)
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')
)
def block_code(self, code, lang):
if not lang:
return '\n<pre><code>%s</code></pre>\n' % \
mistune.escape(code)
lexer = get_lexer_by_name(lang, stripall=True)
formatter = html.HtmlFormatter()
return highlight(code, lexer, formatter)
def admin_v4only_data(self, measurement):
response = yaml.dump(measurement.v4only_data)
# Get the Pygments formatter
formatter = HtmlFormatter(style='colorful')
# Highlight the data
response = highlight(response, YamlLexer(), formatter)
# Get the stylesheet
style = "<style>" + formatter.get_style_defs() + "</style><br>"
# Safe the output
return mark_safe(style + response)
def admin_v6only_data(self, measurement):
response = yaml.dump(measurement.v6only_data)
# Get the Pygments formatter
formatter = HtmlFormatter(style='colorful')
# Highlight the data
response = highlight(response, YamlLexer(), formatter)
# Get the stylesheet
style = "<style>" + formatter.get_style_defs() + "</style><br>"
# Safe the output
return mark_safe(style + response)
def admin_nat64_data(self, measurement):
response = yaml.dump(measurement.nat64_data)
# Get the Pygments formatter
formatter = HtmlFormatter(style='colorful')
# Highlight the data
response = highlight(response, YamlLexer(), formatter)
# Get the stylesheet
style = "<style>" + formatter.get_style_defs() + "</style><br>"
# Safe the output
return mark_safe(style + response)
def save(self, *args, **kwargs):
"""
Use the `pygments` library to create a highlighted HTML
representation of the code snippet.
"""
lexer = get_lexer_by_name(self.language)
linenos = self.linenos and 'table' or False
options = self.title and {'title': self.title} or {}
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)
def save(self, *args, **kwargs):
# Use the `pygments` library to create a highlighted HTML representation of the code snippet.
lexer = get_lexer_by_name(self.language)
linenos = self.linenos and 'table' or False
options = self.title and {'title': self.title} or {}
formatter = HtmlFormatter(style=self.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)
super(Snippet, self).save(*args, **kwargs)
def python_file_to_json(req, file_name: str):
try:
with open(file_name, "r") as file:
data = file.read()
except IOError as e:
data = "Error: {}".format(e.strerror)
if req.accept_mimetypes.accept_html:
html = highlight(data, Python3Lexer(), HtmlFormatter(full=True, linenos='table'))
return Response(html, content_type="text/html")
json_res = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
return Response(json_res, content_type="application/json")
def to_formatted_json(data):
if request.accept_mimetypes.accept_html:
html = highlight(data, JsonLexer(), HtmlFormatter(full=True, linenos='table'))
return Response(html, content_type="text/html")
return Response(data, content_type="application/json")
def transform_code_to_html(code, lang):
return highlight(code, get_lexer_by_name(dict(LANG_REGULAR_NAME).get(lang, lang)), HtmlFormatter())
def get(self, request, submission_id):
submission = OldSubmission.objects.get(pk=submission_id)
return HttpResponse(json.dumps({'code': highlight(submission.code, get_lexer_by_name(submission.lang), HtmlFormatter())}))
def view(slug):
paste = Paste.get_or_404(slug)
if paste.password:
form = PasswordForm()
if form.validate_on_submit():
if not paste.verify_password(form.password.data):
flash('????? ???? ????.', 'error')
return render_template('password.html', form=form)
else:
form.flash_errors()
return render_template('password.html', form=form)
viewed = session.setdefault('viewed', [])
if paste.slug not in viewed:
viewed.append(paste.slug)
session.permanent = True
session.modified = True
paste.view_count += 1
db.session.add(paste)
db.session.commit()
lexer = get_lexer_by_name(paste.lexer)
formatter = HtmlFormatter(
linenos=True,
linespans='line',
lineanchors='line',
anchorlinenos=True,
)
return render_template(
'view.html',
styles=formatter.get_style_defs(),
highlighted_source=highlight(paste.source, lexer, formatter),
lexer=lexer,
paste=paste,
)