def block_code(self, code, lang=None):
"""Rendering block level code. ``pre > code``.
"""
lexer = None
if code.endswith('\n\n'):
code = code[:-1]
if HtmlFormatter and lang:
try:
lexer = get_lexer_by_name(lang, stripall=True)
except ClassNotFound:
code = lang + '\n' + code
if not lexer or not HtmlFormatter:
return '\n<pre><code>%s</code></pre>\n' % mistune.escape(code)
formatter = HtmlFormatter()
return highlight(code, lexer, formatter)
python类HtmlFormatter()的实例源码
def code(self):
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
title = dag_id
try:
with open(dag.fileloc, 'r') as f:
code = f.read()
html_code = highlight(
code, lexers.PythonLexer(), HtmlFormatter(linenos=True))
except IOError as e:
html_code = str(e)
return self.render(
'airflow/dag_code.html', html_code=html_code, dag=dag, title=title,
root=request.args.get('root'),
demo_mode=conf.getboolean('webserver', 'demo_mode'))
def _wiki_code(content):
"""
>>> u = _wiki_code('<code class="python">my_code()</code>')
>>> expected = '<div class="highlight"><pre><span class="n">my_code</span><span class="p">()</span>\\n</pre></div>\\n'
>>> expected in u
True
"""
css_class = "python"
if css_class:
content = content.replace('<code>', '<code class=\"%s\">' % css_class);
#syntax_css = u"<style>%s</style>" % HtmlFormatter().get_style_defs('.highlight')
#content = syntax_css + content
return re.sub(r'\<code\s+class\s*\=\s*\"([^\"]+)\"\>(.*?)\<\/code>',
_wiki_code_callback, content, flags=re.I | re.S)
def show_asm(self, item, primary):
cur = self.db_cursor()
if primary:
db = "main"
else:
db = "diff"
ea = str(int(item[1], 16))
sql = "select prototype, assembly, name from %s.functions where address = ?"
sql = sql % db
cur.execute(sql, (ea, ))
row = cur.fetchone()
if row is None:
Warning("Sorry, there is no assembly available for the selected function.")
else:
fmt = HtmlFormatter()
fmt.noclasses = True
fmt.linenos = True
asm = self.prettify_asm(row["assembly"])
final_asm = "; %s\n%s proc near\n%s\n%s endp\n"
final_asm = final_asm % (row["prototype"], row["name"], asm, row["name"])
src = highlight(final_asm, NasmLexer(), fmt)
title = "Assembly for %s" % row["name"]
cdiffer = CHtmlViewer()
cdiffer.Show(src, title)
cur.close()
def show_pseudo(self, item, primary):
cur = self.db_cursor()
if primary:
db = "main"
else:
db = "diff"
ea = str(int(item[1], 16))
sql = "select prototype, pseudocode, name from %s.functions where address = ?"
sql = sql % db
cur.execute(sql, (str(ea), ))
row = cur.fetchone()
if row is None or row["prototype"] is None or row["pseudocode"] is None:
Warning("Sorry, there is no pseudo-code available for the selected function.")
else:
fmt = HtmlFormatter()
fmt.noclasses = True
fmt.linenos = True
func = "%s\n%s" % (row["prototype"], row["pseudocode"])
src = highlight(func, CppLexer(), fmt)
title = "Pseudo-code for %s" % row["name"]
cdiffer = CHtmlViewer()
cdiffer.Show(src, title)
cur.close()
def get_experiment(path):
logdir = APP.config['logdir']
complete_path = os.path.join(logdir, path)
if os.path.isfile(complete_path):
file_content = get_file(complete_path)
if path.endswith(".log"):
result = ansiconv.to_html(html.escape(file_content))
elif path.endswith(".ini"):
lexer = IniLexer()
formatter = HtmlFormatter(linenos=True)
result = highlight(file_content, lexer, formatter)
else:
result = "Unknown file type: '{}'.".format(complete_path)
else:
result = "File '{}' does not exist.".format(complete_path)
return Response(result, mimetype='text/html', status=200)
def get_experiment(path):
logdir = APP.config['logdir']
complete_path = os.path.join(logdir, path)
if os.path.isfile(complete_path):
file_content = get_file(complete_path)
if path.endswith(".log"):
result = ansiconv.to_html(html.escape(file_content))
elif path.endswith(".ini"):
lexer = IniLexer()
formatter = HtmlFormatter(linenos=True)
result = highlight(file_content, lexer, formatter)
else:
result = "Unknown file type: '{}'.".format(complete_path)
else:
result = "File '{}' does not exist.".format(complete_path)
return Response(result, mimetype='text/html', status=200)
def get_experiment(path):
logdir = APP.config['logdir']
complete_path = os.path.join(logdir, path)
if os.path.isfile(complete_path):
file_content = get_file(complete_path)
if path.endswith(".log"):
result = ansiconv.to_html(html.escape(file_content))
elif path.endswith(".ini"):
lexer = IniLexer()
formatter = HtmlFormatter(linenos=True)
result = highlight(file_content, lexer, formatter)
else:
result = "Unknown file type: '{}'.".format(complete_path)
else:
result = "File '{}' does not exist.".format(complete_path)
return Response(result, mimetype='text/html', status=200)
def block_code(self, text, lang):
linenos = inlinestyles = 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 = HtmlFormatter(
noclasses=inlinestyles, linenos=linenos, cssclass='codehilite'
)
code = highlight(text, lexer, formatter)
if linenos:
return '<div class="highlight-wrapper">%s</div>\n' % code
return '<div class="doc doc-code">%s</div>%s' % (lang.upper(), code)
except:
return '<pre class="%s"><code>%s</code></pre>\n' % (
lang, mistune.escape(text)
)
def code(self):
dag_id = request.args.get('dag_id')
dag = dagbag.get_dag(dag_id)
title = dag_id
try:
m = importlib.import_module(dag.module_name)
code = inspect.getsource(m)
html_code = highlight(
code, lexers.PythonLexer(), HtmlFormatter(linenos=True))
except IOError as e:
html_code = str(e)
return self.render(
'airflow/dag_code.html', html_code=html_code, dag=dag, title=title,
root=request.args.get('root'),
demo_mode=conf.getboolean('webserver', 'demo_mode'))
def code_block(self, node, entering):
'''Output Pygments if required else use default html5 output'''
if self.use_pygments:
self.cr()
info_words = node.info.split() if node.info else []
if len(info_words) > 0 and len(info_words[0]) > 0:
try:
lexer = get_lexer_by_name(info_words[0])
except ValueError:
# no lexer found - use the text one instead of an exception
lexer = TextLexer()
else:
lexer = TextLexer()
formatter = HtmlFormatter(**self.pygments_options)
parsed = highlight(node.literal, lexer, formatter)
self.lit(parsed)
self.cr()
else:
super().code_block(node, entering)
def display_source_ipython(self):
"""
Convenience method to print the loaded source file
as syntax highlighted HTML within IPython.
"""
from pygments import highlight
from pygments.lexers import SLexer
from pygments.formatters import HtmlFormatter
import IPython.display as display
with open(self.source_file) as f:
code = f.read()
formatter = HtmlFormatter()
return display.HTML('<style type="text/css">{}</style>{}'.format(
formatter.get_style_defs('.highlight'),
highlight(code, SLexer(), formatter)))
def view_source(context, web_view, filename):
from base64 import b64encode
from java.io import BufferedReader, InputStreamReader
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_for_filename
stream = context.getAssets().open(join(ASSET_SOURCE_DIR, filename))
reader = BufferedReader(InputStreamReader(stream))
text = "\n".join(iter(reader.readLine, None))
formatter = HtmlFormatter()
body = highlight(text, get_lexer_for_filename(filename), formatter)
html = ("<html><head><style>{}\n{}</style></head><body>{}</body></html>"
.format(formatter.get_style_defs(), EXTRA_CSS, body)).encode()
web_view.loadData(b64encode(html).decode(), "text/html", "base64")
def data_prettified(instance):
"""Function to display pretty version of our data"""
# Convert the data to sorted, indented JSON
response = json.dumps(instance, sort_keys=True, indent=2)
# Truncate the data. Alter as needed
#response = response[:5000]
# Get the Pygments formatter
formatter = HtmlFormatter(style='colorful')
# Highlight the data
response = highlight(response, JsonLexer(), formatter)
# Get the stylesheet
style = "<style>" + formatter.get_style_defs() + "</style><br>"
# Safe the output
return mark_safe(style + response)
def toolTip(self, index):
if index.column() > 0:
return self.data(index)
obj = self.itemData()
if hasattr(obj, "exc_info") and obj.exc_info is not None:
html_orig = '<html><head><style type="text/css">{style}' \
'</style></head><body>'
formatter, style = None, ""
if pygments is not None:
formatter = HtmlFormatter()
style = formatter.get_style_defs()
txt = html_orig.format(style=style)
if formatter is None:
txt += "<pre>%s</pre>" % obj.exc_info
else:
txt += highlight(obj.exc_info, PythonTracebackLexer(),
formatter)
txt += "</body></html>"
else:
txt = "{0} {1}".format(getElementTypeToolTip(obj.type), obj.name)
return txt
def block_code(self, code, lang):
guess = 'python3'
if code.lstrip().startswith('<?php'):
guess = 'php'
elif code.lstrip().startswith(('<', '{%')):
guess = 'html+jinja'
elif code.lstrip().startswith(('function', 'var', '$')):
guess = 'javascript'
lexer = get_lexer_by_name(lang or guess, stripall=True)
return highlight(code, lexer, HtmlFormatter())
# ???????md?????????????????????????
def site_result_json(request: HttpRequest, site_id: int) -> HttpResponse:
site = get_object_or_404(Site.objects.annotate_most_recent_scan_result(), pk=site_id)
scan_result = site.last_scan__result if site.last_scan__result else {}
if 'raw' in request.GET:
return JsonResponse(scan_result)
code = json.dumps(scan_result, indent=2)
highlighted_code = mark_safe(highlight(code, JsonLexer(), HtmlFormatter()))
return render(request, 'frontend/site_result_json.html', {
'site': site,
'highlighted_code': highlighted_code
})
def _process(name, lexer):
from pygments import highlight
from pygments.formatters import HtmlFormatter
source = open("templates/front/snippets/%s.txt" % name).read()
processed = highlight(source, lexer, HtmlFormatter())
processed = processed.replace("PING_URL", "{{ ping_url }}")
processed = processed.replace("SITE_ROOT", "{{ SITE_ROOT }}")
processed = processed.replace("PING_ENDPOINT", "{{ PING_ENDPOINT }}")
with open("templates/front/snippets/%s.html" % name, "w") as out:
out.write(processed)
def blockcode(self, text, lang):
if not lang:
return '\n<pre><code>{}</code></pre>\n'.format(text.strip())
lexer = get_lexer_by_name(lang)
formatter = HtmlFormatter()
return highlight(text, lexer, formatter)
def set_style(self, style: str):
self.css.innerHTML = HtmlFormatter(style=style).get_style_defs()
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 = HtmlFormatter()
return highlight(code, lexer, formatter)
def _format_source(self, source):
formatter = HtmlFormatter(nowrap=True)
html = highlight(source, PythonLexer(), formatter)
return {
'html_lines': [Markup(l) for l in html.splitlines()],
'css': formatter.get_style_defs()
}
def write_styles(self):
"""Write the stylesheet."""
formatter = HtmlFormatter(nowrap=True)
tmpl = jinja2_env.get_template('styles.css')
rendered = tmpl.render(
pygments_css=formatter.get_style_defs()
)
stylesheet = os.path.join(self.outdir, 'styles.css')
with codecs.open(stylesheet, 'w', encoding='utf8') as f:
f.write(rendered)
def run(self):
"""Render templates"""
ifn = self.ifn
ofn = self.ofn
css = self.load_theme(self.theme)
fonts = self.load_fonts()
tmplenv = Environment(loader=FileSystemLoader(self.tmplpath))
slide_tmpl = tmplenv.get_template('index.tmpl')
if not os.path.splitext(ifn)[1] in self.mdexts:
raise IOError("invalid Markdown extension")
with codecs.open(ifn, 'r', encoding='utf-8') as filehandle:
content = markdown(filehandle.read(),
extensions=['markdown.extensions.fenced_code',
'markdown.extensions.tables',
'markdown.extensions.codehilite'])
hlcss = HtmlFormatter().get_style_defs('.codehilite')
content = content.split('<hr />')
title = '{0} ({1})'.format(os.path.splitext(ifn)[0],
datetime.now().strftime('%B %d, %Y'))
buf = slide_tmpl.render(title=title,
css=css,
hlcss=hlcss,
content=enumerate(content),
fonts=fonts)
with codecs.open(ofn, 'w', encoding='utf-8',
errors='xmlcharrefreplace') as filehandle:
filehandle.write(buf)
def pygments_highlight(text, lang, style):
lexer = get_lexer_by_name(lang, stripall=False)
formatter = HtmlFormatter(nowrap=True, style=style)
return pygments.highlight(text, lexer, formatter)
def pygments_css(style):
formatter = HtmlFormatter(style=style)
return formatter.get_style_defs('.highlight')
def get(self):
if (self.request.host.split(":")[0] == pasteconfig.BASE_DOMAIN or
self.request.host.split(".")[0] == "new"):
uname = self.get_cookie("username", "")
self.render("templates/main.html",
username=uname,
default_lang=pasteconfig.DEFAULT_LANG,
langs=OK_LANGS)
return
try:
user, desc, lang, paste = self._get_paste(["user",
"description",
"lang",
"paste"])
except KeyError:
self.clear()
self.set_status(404)
self.finish("<html><body>Not found</body></html>")
return
lexer = pygments.lexers.get_lexer_by_name(lang)
formatter = HtmlFormatter(linenos=True, cssclass="source")
paste = stripctlchars(highlight(paste, lexer, formatter))
css = formatter.get_style_defs(arg='')
self.render("templates/paste.html", css=css, user=user, desc=desc, paste=paste)
def blockcode(self, text, lang):
try:
lexer = get_lexer_by_name(lang, stripall=True)
except ClassNotFound:
lexer = None
if lexer:
formatter = HtmlFormatter(noclasses=True)
return highlight(text, lexer, formatter)
# default
return '\n<pre><code>{}</code></pre>\n'.format(
h.escape_html(text.strip()))
def pylight(code):
return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))
# builtin docstrings to ignore
def pygment_html_render(s, lexer=lexers.TextLexer):
return highlight(
s,
lexer(),
HtmlFormatter(linenos=True),
)