def patch_fenced_rule(self):
"""
Patch Python Markdown with our own fenced block extension.
if the Python Markdown's 'fenced_code' extension was already configured,
we will replace it.
"""
config = self.getConfigs()
fenced = SuperFencesBlockPreprocessor(self.markdown)
indented_code = SuperFencesCodeBlockProcessor(self)
fenced.config = config
indented_code.config = config
indented_code.markdown = self.markdown
hiliter = SuperFencesHiliteTreeprocessor(self.markdown)
hiliter.config = self.getConfigs()
self.markdown.treeprocessors["hilite"] = hiliter
self.markdown.superfences[0]["formatter"] = fenced.highlight
self.markdown.parser.blockprocessors['code'] = indented_code
self.markdown.preprocessors.add('fenced_code_block', fenced, ">normalize_whitespace")
python类highlight()的实例源码
def _color_with_pygments(self, codeblock, lexer, **formatter_opts):
import pygments
import pygments.formatters
class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
def _wrap_code(self, inner):
"""A function for use in a Pygments Formatter which
wraps in <code> tags.
"""
yield 0, "<code>"
for tup in inner:
yield tup
yield 0, "</code>"
def wrap(self, source, outfile):
"""Return the source with a code, pre, and div."""
return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
formatter_opts.setdefault("cssclass", "codehilite")
formatter = HtmlCodeFormatter(**formatter_opts)
return pygments.highlight(codeblock, lexer, formatter)
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 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 show_response(self, response):
"""Print an HTTP Response."""
if response.headers.get('Content-Type', None) == 'application/json':
try:
body = json.dumps(response.json(), indent=2)
except json.JSONDecodeError:
body = response.text
else:
body = response.text
http_txt = self.HTTP_TPL.substitute(
http_version=str(float(response.raw.version) / 10),
status_code=response.status_code,
reason=response.reason,
headers=self.key_value_pairs(response.headers),
body=body,
)
return highlight(http_txt, self.http_lexer, self.formatter)
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 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 _color_with_pygments(self, codeblock, lexer, **formatter_opts):
import pygments
import pygments.formatters
class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
def _wrap_code(self, inner):
"""A function for use in a Pygments Formatter which
wraps in <code> tags.
"""
yield 0, "<code>"
for tup in inner:
yield tup
yield 0, "</code>"
def wrap(self, source, outfile):
"""Return the source with a code, pre, and div."""
return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
formatter_opts.setdefault("cssclass", "codehilite")
formatter = HtmlCodeFormatter(**formatter_opts)
return pygments.highlight(codeblock, lexer, formatter)
def __call__(self, value: Any, *, indent: int=0, indent_first: bool=False, highlight: bool=False):
self._stream = io.StringIO()
self._format(value, indent_current=indent, indent_first=indent_first)
s = self._stream.getvalue()
if highlight and pyg_lexer:
# apparently highlight adds a trailing new line we don't want
s = pygments.highlight(s, lexer=pyg_lexer, formatter=pyg_formatter).rstrip('\n')
return s
def pprint(s, file=None):
highlight = isatty(file) if force_highlight is None else force_highlight
print(pformat(s, highlight=highlight), file=file, flush=True)
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 syntax_highlight(filename='', language=None):
mako_lexer = MakoLexer()
if compat.py3k:
python_lexer = Python3Lexer()
else:
python_lexer = PythonLexer()
if filename.startswith('memory:') or language == 'mako':
return lambda string: highlight(string, mako_lexer,
pygments_html_formatter)
return lambda string: highlight(string, python_lexer,
pygments_html_formatter)
def _create_html_file(self, sourcefile, htmlfile, errors):
name = self.generator.get_name()
root = ElementTree.fromstring(CPPCHECK_HTML_FILE)
title = root.find('head/title')
title.text = 'cppcheck - report - %s' % name
body = root.find('body')
for div in body.findall('div'):
if div.get('id') == 'page':
page = div
break
for div in page.findall('div'):
if div.get('id') == 'header':
h1 = div.find('h1')
h1.text = 'cppcheck report - %s' % name
if div.get('id') == 'content':
content = div
srcnode = self.generator.bld.root.find_node(sourcefile)
hl_lines = [e['line'] for e in errors if e.has_key('line')]
formatter = CppcheckHtmlFormatter(linenos=True, style='colorful', hl_lines=hl_lines, lineanchors='line')
formatter.errors = [e for e in errors if e.has_key('line')]
css_style_defs = formatter.get_style_defs('.highlight')
lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
s = pygments.highlight(srcnode.read(), lexer, formatter)
table = ElementTree.fromstring(s)
content.append(table)
s = ElementTree.tostring(root, method='html')
s = CCPCHECK_HTML_TYPE + s
node = self.generator.path.get_bld().find_or_declare(htmlfile)
node.write(s)
return css_style_defs
def _create_html_file(self, sourcefile, htmlfile, errors):
name = self.generator.get_name()
root = ElementTree.fromstring(CPPCHECK_HTML_FILE)
title = root.find('head/title')
title.text = 'cppcheck - report - %s' % name
body = root.find('body')
for div in body.findall('div'):
if div.get('id') == 'page':
page = div
break
for div in page.findall('div'):
if div.get('id') == 'header':
h1 = div.find('h1')
h1.text = 'cppcheck report - %s' % name
if div.get('id') == 'content':
content = div
srcnode = self.generator.bld.root.find_node(sourcefile)
hl_lines = [e['line'] for e in errors if e.has_key('line')]
formatter = CppcheckHtmlFormatter(linenos=True, style='colorful', hl_lines=hl_lines, lineanchors='line')
formatter.errors = [e for e in errors if e.has_key('line')]
css_style_defs = formatter.get_style_defs('.highlight')
lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
s = pygments.highlight(srcnode.read(), lexer, formatter)
table = ElementTree.fromstring(s)
content.append(table)
s = ElementTree.tostring(root, method='html')
s = CCPCHECK_HTML_TYPE + s
node = self.generator.path.get_bld().find_or_declare(htmlfile)
node.write(s)
return css_style_defs
def _create_html_file(self, sourcefile, htmlfile, errors):
name = self.generator.get_name()
root = ElementTree.fromstring(CPPCHECK_HTML_FILE)
title = root.find('head/title')
title.text = 'cppcheck - report - %s' % name
body = root.find('body')
for div in body.findall('div'):
if div.get('id') == 'page':
page = div
break
for div in page.findall('div'):
if div.get('id') == 'header':
h1 = div.find('h1')
h1.text = 'cppcheck report - %s' % name
if div.get('id') == 'content':
content = div
srcnode = self.generator.bld.root.find_node(sourcefile)
hl_lines = [e['line'] for e in errors if e.has_key('line')]
formatter = CppcheckHtmlFormatter(linenos=True, style='colorful', hl_lines=hl_lines, lineanchors='line')
formatter.errors = [e for e in errors if e.has_key('line')]
css_style_defs = formatter.get_style_defs('.highlight')
lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
s = pygments.highlight(srcnode.read(), lexer, formatter)
table = ElementTree.fromstring(s)
content.append(table)
s = ElementTree.tostring(root, method='html')
s = CCPCHECK_HTML_TYPE + s
node = self.generator.path.get_bld().find_or_declare(htmlfile)
node.write(s)
return css_style_defs