我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pygments.formatters.HtmlFormatter()。
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)
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 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), )
def chart(self): if conf.getboolean('core', 'secure_mode'): abort(404) with create_session() as session: chart_id = request.args.get('chart_id') embed = request.args.get('embed') chart = session.query(models.Chart).filter_by(id=chart_id).first() NVd3ChartClass = chart_mapping.get(chart.chart_type) if not NVd3ChartClass: flash( "Not supported anymore as the license was incompatible, " "sorry", "danger") redirect('/admin/chart/') sql = "" if chart.show_sql: sql = Markup(highlight( chart.sql, lexers.SqlLexer(), # Lexer call HtmlFormatter(noclasses=True)) ) return self.render( 'airflow/nvd3.html', chart=chart, title="Airflow - Chart", sql=sql, label=chart.label, embed=embed)
def conf(self): raw = request.args.get('raw') == "true" title = "Airflow Configuration" subtitle = conf.AIRFLOW_CONFIG if conf.getboolean("webserver", "expose_config"): with open(conf.AIRFLOW_CONFIG, 'r') as f: config = f.read() table = [(section, key, value, source) for section, parameters in conf.as_dict(True, True).items() for key, (value, source) in parameters.items()] else: config = ( "# Your Airflow administrator chose not to expose the " "configuration, most likely for security reasons.") table = None if raw: return Response( response=config, status=200, mimetype="application/text") else: code_html = Markup(highlight( config, lexers.IniLexer(), # Lexer call HtmlFormatter(noclasses=True)) ) return self.render( 'airflow/config.html', pre_subtitle=settings.HEADER + " v" + airflow.__version__, code_html=code_html, title=title, subtitle=subtitle, table=table)
def __init__(self,parent=None,model='',filename='~/.qeval_history'): #'import fandango'): import fandango.web, fandango.functional print('%s()'%type(self).__name__) Qt.QWidget.__init__(self,parent) try: self.name = type(self).__name__ self._locals = {'self':self,'load':self.setModel,'printf':self.printf,'Qt':Qt} self._locals.update([(k,v) for k,v in fandango.functional.__dict__.items() if isCallable(v)]) self._locals['mdir'] = self.dir_module self._locals['help'] = self.help self._locals['doc'] = lambda x:x.__doc__ self._locals['run'] = fandango.objects.loadModule self._locals.update((k,getattr(fandango.web,k)) for k in ('table','bold','color')) self._modules = {} self._instances = {} self.history = [] self.filename = filename.replace('~',os.getenv('HOME')) if filename.startswith('~') else filename try:#Enabling Syntax Highlighting from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter lexer,frmt=PythonLexer(),HtmlFormatter() self.css=frmt.get_style_defs('.highlight') self.highlight = lambda t,l=lexer,f=frmt: highlight(t,l,f) #html='<head><style>%s</style><body>%s</body>'%(css,highlight(code,lexer,frmt)) except: traceback.print_exc() self.css = None self.highlight = lambda t: '<pre>%s</pre>'%t self.evalQ('import fandango') self.evalQ('import fandango.qt') self.evalQ('f=fandango') self.setup_ui() self.setEval() self.setModel(model or '') except: traceback.print_exc()
def block_code(self, text, lang): if not lang: return '\n<pre><code>%s</code></pre>\n' % text.strip() lexer = get_lexer_by_name(lang, stripall=True) formatter = HtmlFormatter() return highlight(text, lexer, formatter)
def __init__(self, **options): options['lineseparator'] = '\n<div class="newline"></div>' formatters.HtmlFormatter.__init__(self, **options)
def test_pygments(pyi_builder): pyi_builder.test_source( """ # This sample code is taken from http://pygments.org/docs/quickstart/. from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter code = 'print "Hello World"' print(highlight(code, PythonLexer(), HtmlFormatter())) """)
def pretty_json_as_html(data, sort_keys=True): response = json.dumps(data, sort_keys=sort_keys, 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 _format_sql(sql, data, format='html'): popts = {} if data.get('remove_comments'): popts['strip_comments'] = True if data.get('keyword_case', 'undefined') not in ('undefined', ''): popts['keyword_case'] = data.get('keyword_case') if data.get('identifier_case', 'undefined') not in ('undefined', ''): popts['identifier_case'] = data.get('identifier_case') if data.get('n_indents', None) is not None: val = data.get('n_indents') try: popts['indent_width'] = max(1, min(1000, int(val))) popts['reindent'] = True except (ValueError, TypeError): pass if (not 'indent_width' in popts and data.get('reindent', '').lower() in ('1', 'true', 't')): popts['indent_width'] = 2 popts['reindent'] = True if data.get('output_format', None) is not None: popts['output_format'] = data.get('output_format') logging.debug('Format: %s, POPTS: %r', format, popts) logging.debug(sql) sql = sqlparse.format(sql, **popts) if format in ('html', 'json'): if data.get('highlight', False): if popts['output_format'] == 'python': lexer = PythonLexer() elif popts['output_format'] == 'php': lexer = PhpLexer() else: lexer = SqlLexer() sql = highlight(sql, lexer, HtmlFormatter()) else: sql = ('<textarea class="resizable" ' 'style="height: 350px; margin-top: 1em;">%s</textarea>' % sql) return sql
def pygments2xpre(s, language="python"): "Return markup suitable for XPreformatted" try: from pygments import highlight from pygments.formatters import HtmlFormatter except ImportError: return s from pygments.lexers import get_lexer_by_name rconv = lambda x: x if isPy3: out = getStringIO() else: if isUnicode(s): s = asBytes(s) rconv = asUnicode out = getBytesIO() l = get_lexer_by_name(language) h = HtmlFormatter() highlight(s,l,h,out) styles = [(cls, style.split(';')[0].split(':')[1].strip()) for cls, (style, ttype, level) in h.class2style.items() if cls and style and style.startswith('color:')] return rconv(_2xpre(out.getvalue(),styles))
def _wiki_code_callback(matchobj): m = matchobj.groups() content = m[1] content = re.sub(r'^\s*', '', content, re.S) content = re.sub(r'\s*$', '', content, re.S) # code_class = m[0] formatter = HtmlFormatter() styles = formatter.get_style_defs('.highlight') code = highlight(content, PythonLexer(), formatter) return f'<style>{styles}</style>{code}'
def download_release(request, short_name, release_tag): dataset = get_object_or_404(Dataset, short_name=short_name) release = get_object_or_404(DatasetRelease, dataset=dataset, release_tag=release_tag) if release.type is not 'PU' and not dataset.user_is_maintainer(request.user): raise HttpResponseNotAllowed script = utils.generate_download_script(dataset) formatted_script = highlight(script, PythonLexer(), HtmlFormatter()) highlighting_styles = HtmlFormatter().get_style_defs('.highlight') return render(request, 'datasets/download.html', {'dataset': dataset, 'release': release, 'formatted_script': formatted_script, 'highlighting_styles': highlighting_styles})
def block_code(self, text, lang): if not lang: return '\n<pre><code>%s</code></pre>\n' % text.strip() lexer = get_lexer_by_name(lang, stripall=True) formatter = HtmlFormatter() return misaka.SmartyPants(highlight(text, lexer, formatter))
def send_codehilite_style(self, theme='default', dest=None): """Send Pygments stylesheet to dest directory""" if dest == None: dest = self.staticpath hl = HtmlFormatter(style=theme).get_style_defs('.codehilite') fname = path.join(dest, 'codehilite.css') with open(fname, 'w') as f: f.write(hl)
def get_prettyjson_html(api_key): boite = get_object_or_404(Boite, api_key=api_key) # Example from https://www.pydanny.com/pretty-formatting-json-django-admin.html response = json.dumps(boite.get_apps_dictionary(), sort_keys=True, indent=2) response = response[:5000] formatter = HtmlFormatter(style='friendly') response = highlight(response, JsonLexer(), formatter) style = "<style>" + formatter.get_style_defs() + "</style><br>" return mark_safe(style + response)
def chart(self): session = settings.Session() chart_id = request.args.get('chart_id') embed = request.args.get('embed') chart = session.query(models.Chart).filter_by(id=chart_id).first() session.expunge_all() session.commit() session.close() NVd3ChartClass = chart_mapping.get(chart.chart_type) if not NVd3ChartClass: flash( "Not supported anymore as the license was incompatible, " "sorry", "danger") redirect('/admin/chart/') sql = "" if chart.show_sql: sql = Markup(highlight( chart.sql, lexers.SqlLexer(), # Lexer call HtmlFormatter(noclasses=True)) ) return self.render( 'airflow/nvd3.html', chart=chart, title="Airflow - Chart", sql=sql, label=chart.label, embed=embed)
def sandbox(self): title = "Sandbox Suggested Configuration" cfg_loc = conf.AIRFLOW_CONFIG + '.sandbox' f = open(cfg_loc, 'r') config = f.read() f.close() code_html = Markup(highlight( config, lexers.IniLexer(), # Lexer call HtmlFormatter(noclasses=True)) ) return self.render( 'airflow/code.html', code_html=code_html, title=title, subtitle=cfg_loc)