def _regen_header(self): """ Fills self.header with lines of CSS extracted from IPython and Pygments. """ #Clear existing header. header = [] #Construct path to IPy CSS from IPython.html import DEFAULT_STATIC_FILES_PATH sheet_filename = os.path.join(DEFAULT_STATIC_FILES_PATH, 'style', 'style.min.css') #Load style CSS file. with io.open(sheet_filename, encoding='utf-8') as file: file_text = file.read() header.append(file_text) #Add pygments CSS formatter = HtmlFormatter() pygments_css = formatter.get_style_defs(self.highlight_class) header.append(pygments_css) #Set header self.header = header
def highlight_python_source(source): if not pygments_plugin: return "<pre><code>{}</code></pre".format(source) formatter = HtmlFormatter() return '<style type="text/css">{}</style>{}'.format( formatter.get_style_defs(".highlight"), highlight(source, PythonLexer(), formatter) )
def pipp_code(context, src, code, lexer, docss): ctx = context.processor.extensionParams[(NAMESPACE, 'context')] src = Conversions.StringValue(src) if src: abs_src = ctx.abs_in_path(src) ctx.add_depends(abs_src[len(ctx.in_root):]) fname = os.path.basename(src) code = open(abs_src).read() else: fname = 'inline-code' code = Conversions.StringValue(code) lexer = Conversions.StringValue(lexer) if lexer: lexer = get_lexer_by_name(lexer) elif src: lexer = get_lexer_for_filename(fname) else: raise Exception('The lexer must be explicitly specified for inline code blocks') formatter = HtmlFormatter(cssclass="source") result = highlight(code, lexer, formatter) if Conversions.StringValue(docss) == '1': result = '<link rel="stylesheet" href="%s.css"/>' % fname + result css = open(ctx.abs_out_path(ctx.abs_in_path(fname + '.css')), 'w') css.write(formatter.get_style_defs()) css.close() return result
def pretty_print(paste, style_choice, linenos = "inline", full = False): """Use Pygments library to highlight a TextField returns str1, str2 where str1 is the formatted text, and str2 is the css style block Syntax: code_str, style_str = pretty_print(code_str) Ex: Views: pretty_text_output, style_output = pretty_print(source_code) Template: <style> {{style_output|safe}} </style> {{pretty_text_output|safe}} """ if paste.language: lexer = get_lexer_by_name(paste.language, stripall=True) if not paste.language: lexer = guess_lexer(paste.code_paste, stripall=True) if not style_choice.highlight: style_choice.highlight = DEFAULT_STYLE formatter = HtmlFormatter(linenos = linenos, full = full, cssclass = "source", style = style_choice.highlight) result = highlight(paste.code_paste, lexer, formatter) css_style = formatter.get_style_defs() return result, css_style
def main(): parser = argparse.ArgumentParser() parser.add_argument('source', default='-', nargs='?', type=str) parser.add_argument('--style', default='colorful', type=str) parser.add_argument('--format', default='html', type=str) parser.add_argument('--css', action="store_true", help='Router service config') parser.add_argument('--preprocess', action="store_true", help='Preprocess a markdown file from stdin') args = parser.parse_args() if args.css: htmlformat = HtmlFormatter(style=args.style) sys.stdout.write(htmlformat.get_style_defs('.highlight')) sys.exit(0) if args.preprocess: source = sys.stdin.read() processed = preprocess_source(source, args.style, args.format) sys.stdout.write(processed) return if args.source == '-' or not args.source: source = sys.stdin.read() else: source = open(args.source).read() stdout = exec_block(source, style=args.style, formatter=args.format) sys.stdout.write(stdout)
def setError(self, err_type=None, err_value=None, err_traceback=None): """Translates the given error object into an HTML string and places it it the message panel :param error: an error object (typically an exception object) :type error: object""" msgbox = self._msgbox html_orig = '<html><head><style type="text/css">{style}</style>' "</head><body>" style, formatter = "", None if pygments is not None: formatter = HtmlFormatter() style = formatter.get_style_defs() html = html_orig.format(style=style) for de in err_value: e_html = """<pre>{reason}: {desc}</pre>{origin}<hr>""" origin, reason, desc = de.origin, de.reason, de.desc if reason.startswith("PyDs_") and pygments is not None: origin = highlight(origin, PythonTracebackLexer(), formatter) else: origin = "<pre>%s</pre>" % origin html += e_html.format(desc=desc, origin=origin, reason=reason) html += "</body></html>" msgbox.setText(err_value[0].desc) msgbox.setDetailedHtml(html) exc_info = "".join(traceback.format_exception(err_type, err_value, err_traceback)) html = html_orig.format(style=style) if pygments is None: html += "<pre>%s</pre>" % exc_info else: html += highlight(exc_info, PythonTracebackLexer(), formatter) html += "</body></html>" msgbox.setOriginHtml(html)
def index(request, *args, **kwargs): # the *args, **kwargs is because this view is used in urls.py # as a catch-all for the sake of pushstate context = {} html_formatter = HtmlFormatter(linenos=True) context['pygments_css'] = html_formatter.get_style_defs('.highlight') return render(request, 'analyzer/index.html', context)
def run_test(chapter_num=None, section_num=None, test_index=None, test_id=None): if test_id is None: try: chapter, sections, _ = chapters[chapter_num - 1] title, url, tests = sections[section_num - 1] test = tests[test_index - 1] previous_index = test_index - 1 next_index = test_index + 1 if test_index < len(tests) else None except IndexError: abort(404) else: test = dict(test_id=test_id) from pygments import highlight from pygments.lexers import HtmlLexer from pygments.formatters import HtmlFormatter filename = safe_join(suite_directory, test['test_id'] + '.htm') with open(filename, 'rb') as fd: source = fd.read().decode('utf8') formatter = HtmlFormatter(linenos='inline') source = highlight(source, HtmlLexer(), formatter) css = formatter.get_style_defs('.highlight') return render_template('run_test.html', **locals())
def setError(self, err_type=None, err_value=None, err_traceback=None): """Translates the given error object into an HTML string and places it in the message panel :param error: an error object (typically an exception object) :type error: object""" msgbox = self._msgbox error = "".join(traceback.format_exception_only(err_type, err_value)) msgbox.setText(error) msg = "<html><body><pre>%s</pre></body></html>" % error msgbox.setDetailedHtml(msg) html_orig = '<html><head><style type="text/css">{style}</style>' "</head><body>" exc_info = "".join(traceback.format_exception(err_type, err_value, err_traceback)) style = "" if pygments is not None: formatter = HtmlFormatter() style = formatter.get_style_defs() html = html_orig.format(style=style) if pygments is None: html += "<pre>%s</pre>" % exc_info else: formatter = HtmlFormatter() html += highlight(exc_info, PythonTracebackLexer(), formatter) html += "</body></html>" msgbox.setOriginHtml(html)
def highlight_blob(blob): try: lexer = guess_lexer_for_filename(blob.name, blob.data_stream.read()) except ClassNotFound: lexer = TextLexer() formater = HtmlFormatter(nobackground=True,linenos='table', cssclass="source") return "<style>%s</style>%s" % (formater.get_style_defs('.source'), highlight(blob.data_stream.read(), lexer, formater))
def style_info(request, response, function_info): """ Listet alle Stylesheet-Namen auf und zwigt die jeweiligen Styles an. """ style_list = list(get_all_styles()) selected_style = None if function_info!=None: selected_style = function_info[0] if not selected_style in style_list: self.page_msg.red("Name Error!") selected_style = None context = { "styles": style_list, "selected_style": selected_style, "menu_link": request.URLs.actionLink("menu"), } request.templates.write("pygments_css", context, debug=False) if selected_style == None: # Es wurde kein Style ausgewählt return # CSS zum Style anzeigen stylesheet = HtmlFormatter(style=selected_style) stylesheet = stylesheet.get_style_defs('.pygments_code') request.render.highlight( ".css", stylesheet, pygments_style=selected_style )
def test_linenos(self): optdict = dict(linenos=True) outfile = StringIO() fmt = HtmlFormatter(**optdict) fmt.format(tokensource, outfile) html = outfile.getvalue() self.assertTrue(re.search("<pre>\s+1\s+2\s+3", html))
def test_valid_output(self): # test all available wrappers fmt = HtmlFormatter(full=True, linenos=True, noclasses=True, outencoding='utf-8') handle, pathname = tempfile.mkstemp('.html') tfile = os.fdopen(handle, 'w+b') fmt.format(tokensource, tfile) tfile.close() catname = os.path.join(TESTDIR, 'dtds', 'HTML4.soc') try: try: import subprocess ret = subprocess.Popen(['nsgmls', '-s', '-c', catname, pathname], stdout=subprocess.PIPE).wait() except ImportError: # Python 2.3 - no subprocess module ret = os.popen('nsgmls -s -c "%s" "%s"' % (catname, pathname)).close() if ret == 32512: raise OSError # not found except OSError: # nsgmls not available pass else: self.failIf(ret, 'nsgmls run reported errors') os.unlink(pathname)
def test_valid_output(self): # test all available wrappers fmt = HtmlFormatter(full=True, linenos=True, noclasses=True, outencoding='utf-8') handle, pathname = tempfile.mkstemp('.html') tfile = os.fdopen(handle, 'w+b') fmt.format(tokensource, tfile) tfile.close() catname = os.path.join(TESTDIR, 'dtds', 'HTML4.soc') try: import subprocess po = subprocess.Popen(['nsgmls', '-s', '-c', catname, pathname], stdout=subprocess.PIPE) ret = po.wait() output = po.stdout.read() po.stdout.close() except OSError: # nsgmls not available pass else: if ret: print(output) self.assertFalse(ret, 'nsgmls run reported errors') os.unlink(pathname)
def test_filename(self): optdict = dict(filename="test.py") outfile = StringIO() fmt = HtmlFormatter(**optdict) fmt.format(tokensource, outfile) html = outfile.getvalue() self.assertTrue(re.search("<span class=\"filename\">test.py</span><pre>", html))
def test_linenos_with_startnum(self): optdict = dict(linenos=True, linenostart=5) outfile = StringIO() fmt = HtmlFormatter(**optdict) fmt.format(tokensource, outfile) html = outfile.getvalue() self.assertTrue(re.search("<pre>\s+5\s+6\s+7", html))
def test_lineanchors_with_startnum(self): optdict = dict(lineanchors="foo", linenostart=5) outfile = StringIO() fmt = HtmlFormatter(**optdict) fmt.format(tokensource, outfile) html = outfile.getvalue() self.assertTrue(re.search("<pre><span></span><a name=\"foo-5\">", html))
def _dump_bb_ex(self, basic_block, print_ir=False): lines = [] base_addr = basic_block.instrs[0].address formatter = HtmlFormatter() formatter.noclasses = True formatter.nowrap = True asm_mnemonic_max_width = 0 for dinstr in basic_block: if len(dinstr.asm_instr.mnemonic) > asm_mnemonic_max_width: asm_mnemonic_max_width = len(dinstr.asm_instr.mnemonic) for instr in basic_block.instrs: asm_instr = self._dump_instr(instr.asm_instr, asm_mnemonic_max_width + 1, fill_char=" ") asm_instr = highlight(asm_instr, NasmLexer(), formatter) asm_instr = asm_instr.replace("span", "font") asm_instr = asm_instr.replace('style="color: ', 'color="') lines += ["<tr><td align='left'> %08x [%02d] %s </td></tr>" % (instr.address, instr.asm_instr.size, asm_instr)] if print_ir: for ir_instr in instr.ir_instrs: lines += [" " + str(ir_instr) + "\\l"] return "".join(lines)
def get_pygments_css(request): formatter = HtmlFormatter(linenos=True, outencoding='utf-8') return HttpResponse( content=formatter.get_style_defs(arg=''), mimetype='text/css', content_type='text/css; charset=' + settings.DEFAULT_CHARSET, )
def _regen_header(self): """ Fills self.header with lines of CSS extracted from IPython and Pygments. """ from pygments.formatters import HtmlFormatter #Clear existing header. header = [] #Construct path to IPy CSS sheet_filename = os.path.join(path.get_ipython_package_dir(), 'html', 'static', 'style', 'style.min.css') #Load style CSS file. with io.open(sheet_filename, encoding='utf-8') as file: file_text = file.read() header.append(file_text) #Add pygments CSS formatter = HtmlFormatter() pygments_css = formatter.get_style_defs(self.highlight_class) header.append(pygments_css) #Set header self.header = header
def _html_format(self, content, content_types): try: from pygments import highlight from pygments.lexers import get_lexer_for_mimetype from pygments.formatters import HtmlFormatter lexer = None for ct in content_types: try: lexer = get_lexer_for_mimetype(ct) break except: pass if lexer is None: raise ValueError("No lexer found") formatter = HtmlFormatter() return html_body % dict( css=formatter.get_style_defs(), content=highlight(content, lexer, formatter).encode('utf8')) except Exception as e: log.warning( "Could not pygment the content because of the following " "error :\n%s" % e) return html_body % dict( css='', content=u('<pre>%s</pre>') % content.replace(b('>'), b('>')) .replace(b('<'), b('<')))
def pcat(filename, target='ipython'): code = read_file_or_url(filename) HTML_TEMPLATE = """<style> {} </style> {} """ from pygments.lexers import get_lexer_for_filename lexer = get_lexer_for_filename(filename, stripall=True) from pygments.formatters import HtmlFormatter, TerminalFormatter from pygments import highlight try: assert(target=='ipython') from IPython.display import HTML, display from pygments.formatters import HtmlFormatter formatter = HtmlFormatter(linenos=True, cssclass="source") html_code = highlight(code, lexer, formatter) css = formatter.get_style_defs() html = HTML_TEMPLATE.format(css, html_code) htmlres = HTML(html) return htmlres except Exception as e: print(e) pass formatter = TerminalFormatter() output = highlight(code,lexer,formatter) print(output)
def _generate_header(self, resources): """ Fills self.header with lines of CSS extracted from IPython and Pygments. """ from pygments.formatters import HtmlFormatter header = [] # Construct path to Jupyter CSS sheet_filename = os.path.join( os.path.dirname(nbconvert.resources.__file__), 'style.min.css', ) # Load style CSS file. with io.open(sheet_filename, encoding='utf-8') as f: header.append(f.read()) # Add pygments CSS formatter = HtmlFormatter(style=self.style) pygments_css = formatter.get_style_defs(self.highlight_class) header.append(pygments_css) # Load the user's custom CSS and IPython's default custom CSS. If they # differ, assume the user has made modifications to his/her custom CSS # and that we should inline it in the nbconvert output. config_dir = resources['config_dir'] custom_css_filename = os.path.join(config_dir, 'custom', 'custom.css') if os.path.isfile(custom_css_filename): if DEFAULT_STATIC_FILES_PATH and self._default_css_hash is None: self._default_css_hash = self._hash(os.path.join(DEFAULT_STATIC_FILES_PATH, 'custom', 'custom.css')) if self._hash(custom_css_filename) != self._default_css_hash: with io.open(custom_css_filename, encoding='utf-8') as f: header.append(f.read()) return header
class PygmentsHighlighter(object): """ highlight python code with a QSyntaxHighlighter, callable class (e.g. function with a state) to """ def __init__(self): """ constructor """ self._lexer = PythonLexer() self._formatter = HtmlFormatter() self._document = QtGui.QTextDocument() self._document.setDefaultStyleSheet(self._formatter.get_style_defs()) self._format_cache = dict() def __call__(self, code): """ makes this class callable, actually do the highlightning """ index = 0 for token, text in self._lexer.get_tokens(code): length = len(text) char_format = self._get_format(token) pygmentsHighlighter._setFormat(index, length, char_format) index += length def _get_format(self, token): """ get the QTextCharFormat for a token """ if token in self._format_cache: return self._format_cache[token] # get format from document code, html = next(self._formatter._format_lines([(token, u"dummy")])) self._document.setHtml(html) char_format = QtGui.QTextCursor(self._document).charFormat() # cache result self._format_cache[token] = char_format return char_format
def blog_mod_render_items(self, blog, items): if self.markdown_highlight_style: from pygments.style import Style from pygments.styles import get_style_by_name from pygments.formatters import HtmlFormatter # User-defined custom style takes precedence try: with tmp_sys_path(self.config.get('command_dir', "")): mod = import_module(self.markdown_highlight_style) except ImportError: mdstyle = None else: mdstyle = first_subclass(mod, Style) # Try for built-in style if no custom style if not mdstyle: mdstyle = get_style_by_name(self.markdown_highlight_style) # Generate CSS with selector for markdown codehilite extension css = HtmlFormatter(style=mdstyle).get_style_defs(arg=".codehilite") if not css.endswith(os.linesep): css = "{}{}".format(css, os.linesep) csspath = blog.metadata['highlight_stylesheet_url'] if csspath.startswith('/'): csspath = csspath[1:] items.append((encode(css, blog.metadata['charset']), csspath)) return items
def html_output(self,outfile_fn): def code(match): with open(match.srcfile(), 'rb') as src: for i in range(match.getStartLine()): src.readline() return [src.readline() for i in range(match.getLineCount())] try: import chardet lexer = CppLexer(encoding='chardet') except: lexer = CppLexer(encoding='utf-8') formatter = HtmlFormatter(encoding='utf-8') with open(outfile_fn, 'wb') as out: out.write('<html><head><style type="text/css">%s</style></head><body>'%formatter.get_style_defs('.highlight')) id = 0 copies = sorted(self.findcopies(),reverse=True,key=lambda x:x.matchedlines) out.write('<ul>%s</ul>'%'\n'.join(['<a href="#match_%i">Match %i</a>'%(i,i) for i in range(len(copies))])) for matches in copies: out.write('<h1 id="match_%i">MATCH %i</h1><ul>'%(id,id)) out.write(' '.join(['<li>%s:%i-%i</li>'%(m.srcfile(), m.getStartLine(), m.getStartLine() + m.getLineCount()) for m in matches])) out.write('</ul><div class="highlight">') highlight(''.join(code([s for s in matches][0])), lexer, formatter, outfile=out) out.write('<a href="#">Up</a></div>') id += 1 out.write('</body></html>')
def html_output(filenames, outfile, width, style): if not outfile: outfile = "output.html" lines_wrapped = 0 formatter = HtmlFormatter(linenos=False, cssclass="source", style=style) output = open(outfile, "w") output.write('<html><head><style type="text/css">') output.write(css_styles) output.write(formatter.get_style_defs()) output.write("\n</style></head><body>") W = width for filename in filenames: output.write("<h1>" + filename + "</h1>\n") lexer = get_lexer_for_filename(filename) F = open(filename, "r") code = "" for line in F: while len(line) > W: lines_wrapped += 1 code += line[:W] + "\n" line = line[W:] code += line[:W] result = highlight(code, lexer, formatter, output) F.close() output.write("</body></html>") if lines_wrapped > 0: print "(wrapped " + str(lines_wrapped) + " lines)" output.close()
def view_message(request, app_slug, message_id): message = get_object_or_404( remotelog.LogMessage, pk=message_id, application__slug=app_slug, ) exc_text = message.exc_text pygments_css = None if exc_text: try: from pygments import highlight from pygments.lexers import PythonTracebackLexer from pygments.formatters import HtmlFormatter formatter = HtmlFormatter() exc_text = highlight(exc_text, PythonTracebackLexer(), formatter) pygments_css = formatter.get_style_defs('.highlight') except ImportError: pass opts = remotelog.LogMessage._meta context = { 'message': message, 'exc_text': exc_text, 'pygments_css': pygments_css, # admin stuff 'has_change_permission': True, 'add': True, 'change': True, 'opts': opts, 'app_label': opts.app_label, } return render_to_response('remotelog/view_message.html', context)
def test_lineanchors(self): optdict = dict(lineanchors="foo") outfile = StringIO() fmt = HtmlFormatter(**optdict) fmt.format(tokensource, outfile) html = outfile.getvalue() self.assertTrue(re.search("<pre><a name=\"foo-1\">", html))
def syntax(dic, text): """ highlight code using pygments USAGE: [rk:syntax lang="LANG_NAME"]CODE[/rk:syntax] """ pygments_formatter = HtmlFormatter() langs = {} for i in dic: try: lexer = get_lexer_by_name(i['attributes']['lang']) except ValueError: lexer = get_lexer_by_name('text') if i['attributes']['lang'] == 'php' and i['code'].find('<?php') < 1: i['code'] = '<?php\n\r%s' % i['code'] parsed = highlight(i['code'], lexer, pygments_formatter) text = text.replace(i['tag'], '<div class="box" style="overflow:hidden;font-size:11px;">%s</div>' % parsed) langs['<style>%s</style>' % pygments_formatter.get_style_defs()] = True styles = '' for style in langs.keys(): styles = styles + style text = text + styles return text
import json from pygments import highlight from pygments.lexers import JsonLexer from pygments.formatters import HtmlFormatter from django.contrib import admin from django.utils.safestring import mark_safe from django.template.defaultfilters import truncatechars from drflog.models import Entry STYLE = 'friendly' HTML_FORMATTER = HtmlFormatter(style=STYLE) JSON_LEXER = JsonLexer() class InputFilter(admin.SimpleListFilter): template = 'admin/input_filter.html' def lookups(self, request, model_admin): # Dummy, required to show the filter. return ((), ) def choices(self, changelist): # Grab only the "all" option. all_choice = next(super().choices(changelist)) all_choice['query_parts'] = (( k, v) for k, v in changelist.get_filters_params().items() if k != self.parameter_name) yield all_choice class UserFilter(InputFilter):
settings = get_current_registry().settings expireChoice = {"never": None, "1day": datetime.timedelta(days=1), "1week": datetime.timedelta(days=7), "1month": datetime.timedelta(days=31) } # couchdb connection server = couchdbkit.Server(settings['couchdb.url']) db = server.get_or_create_db(settings['couchdb.db']) Paste.set_db(db) formatter = HtmlFormatter(linenos=True, full=True, cssclass="source") @view_config(route_name='home', renderer='templates/home.pt') def home(request): """ Home page. first page to be called. """ return {'lexers': lexers()} def _buildPassword(username, createdTime, password): """ Build sha1 of password. :param username: username field of paste,
def _generate_header(self, resources): """ Fills self.header with lines of CSS extracted from IPython and Pygments. """ from pygments.formatters import HtmlFormatter header = [] # Construct path to Jupyter CSS import nbconvert.resources sheet_filename = os.path.join( os.path.dirname(nbconvert.resources.__file__), 'style.min.css', ) # Load style CSS file. with io.open(sheet_filename, encoding='utf-8') as f: header.append(f.read()) # Add pygments CSS formatter = HtmlFormatter() pygments_css = formatter.get_style_defs(self.highlight_class) header.append(pygments_css) # These ANSI CSS definitions will be part of style.min.css with the # Notebook release 5.0 and shall be removed afterwards! # See https://github.com/jupyter/nbconvert/pull/259 header.append(""" /* Temporary definitions which will become obsolete with Notebook release 5.0 */ .ansi-black-fg { color: #3E424D; } .ansi-black-bg { background-color: #3E424D; } .ansi-black-intense-fg { color: #282C36; } .ansi-black-intense-bg { background-color: #282C36; } .ansi-red-fg { color: #E75C58; } .ansi-red-bg { background-color: #E75C58; } .ansi-red-intense-fg { color: #B22B31; } .ansi-red-intense-bg { background-color: #B22B31; } .ansi-green-fg { color: #00A250; } .ansi-green-bg { background-color: #00A250; } .ansi-green-intense-fg { color: #007427; } .ansi-green-intense-bg { background-color: #007427; } .ansi-yellow-fg { color: #DDB62B; } .ansi-yellow-bg { background-color: #DDB62B; } .ansi-yellow-intense-fg { color: #B27D12; } .ansi-yellow-intense-bg { background-color: #B27D12; } .ansi-blue-fg { color: #208FFB; } .ansi-blue-bg { background-color: #208FFB; } .ansi-blue-intense-fg { color: #0065CA; } .ansi-blue-intense-bg { background-color: #0065CA; } .ansi-magenta-fg { color: #D160C4; } .ansi-magenta-bg { background-color: #D160C4; } .ansi-magenta-intense-fg { color: #A03196; } .ansi-magenta-intense-bg { background-color: #A03196; } .ansi-cyan-fg { color: #60C6C8; } .ansi-cyan-bg { background-color: #60C6C8; } .ansi-cyan-intense-fg { color: #258F8F; } .ansi-cyan-intense-bg { background-color: #258F8F; } .ansi-white-fg { color: #C5C1B4; } .ansi-white-bg { background-color: #C5C1B4; } .ansi-white-intense-fg { color: #A1A6B2; } .ansi-white-intense-bg { background-color: #A1A6B2; } .ansi-bold { font-weight: bold; } """) # Load the user's custom CSS and IPython's default custom CSS. If they # differ, assume the user has made modifications to his/her custom CSS # and that we should inline it in the nbconvert output. try: from notebook import DEFAULT_STATIC_FILES_PATH except ImportError: DEFAULT_STATIC_FILES_PATH = None config_dir = resources['config_dir'] custom_css_filename = os.path.join(config_dir, 'custom', 'custom.css') if os.path.isfile(custom_css_filename): if DEFAULT_STATIC_FILES_PATH and self._default_css_hash is None: self._default_css_hash = self._hash(os.path.join(DEFAULT_STATIC_FILES_PATH, 'custom', 'custom.css')) if self._hash(custom_css_filename) != self._default_css_hash: with io.open(custom_css_filename, encoding='utf-8') as f: header.append(f.read()) return header
def pygments_css(style): formatter = HtmlFormatter(style=style) return formatter.get_style_defs('.highlight')
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)
app.config['SECRET_KEY'] = 'blin_is_not_a_pancake' app.config["TEMPLATES_AUTO_RELOAD"] = True app.config["MAIL_SERVER"] = "smtp.yandex.ru" app.config["MAIL_PORT"] = 465 app.config["MAIL_USE_SSL"] = True app.config["MAIL_USERNAME"] = '******' app.config["MAIL_PASSWORD"] = '******' app.config["MAIL_DEFAULT_SENDER"] = "*****@*****.**" serializer = URLSafeTimedSerializer(app.config['SECRET_KEY']) login_manager = LoginManager() login_manager.init_app(app) api = Api(app) socketio = SocketIO(app) mail = Mail(app) formatter = HtmlFormatter(style="monokai", full=True, cssclass="codehilite") css_string = formatter.get_style_defs() with open("static/css/code_highlight.css", "w") as f: f.write(css_string) @app.context_processor def inject_variables(): return dict(format_message=format_message) # ----------------------------------Классы------------------------------------ class RegisterForm(FlaskForm): password = PasswordField('Password', validators=[DataRequired()])
.. glossary:: /code <language> <snippet> Run this command to send the <snippet> of code, syntax highlighted using pygments’s <language> lexer. """ from poezio.plugin import BasePlugin from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter #pylint: disable=no-name-in-module FORMATTER = HtmlFormatter(nowrap=True, noclasses=True) class Plugin(BasePlugin): def init(self): self.api.add_command( 'code', self.command_code, usage='<language> <code>', short='Sends syntax-highlighted code', help='Sends syntax-highlighted code in the current tab') def command_code(self, args): language, code = args.split(None, 1) lexer = get_lexer_by_name(language) tab = self.api.current_tab()
:copyright: 2007 by Georg Brandl. :license: BSD, see LICENSE for more details. """ # Options # ~~~~~~~ # Set to True if you want inline CSS styles instead of classes INLINESTYLES = True # If no inline CSS styles are used the stylesheet must define the formatting. #INLINESTYLES = False from pygments.formatters import HtmlFormatter # The default formatter DEFAULT = HtmlFormatter(noclasses=INLINESTYLES) # Add name -> formatter pairs for every variant you want to use VARIANTS = { # 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True), } from docutils import nodes from docutils.parsers.rst import directives from pygments import highlight from pygments.lexers import get_lexer_by_name, TextLexer def pygments_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine):
import os import re try: import pygments from pygments.lexers import CppLexer from pygments.formatters import HtmlFormatter def highlight(src): return pygments.highlight(src, CppLexer(), HtmlFormatter()) CSS = HtmlFormatter().get_style_defs() code_CSS = "div.example { width: 50%; background-color: lightgrey; border: 1px solid; padding-left: 10px;}" except: print("Pygments is not installed, no syntax highlighting") def highlight(src): return src.replace("\n", "<br>").replace(" ", " ").replace( "\t", " ") CSS, code_CSS = "", "" from os.path import join, dirname, basename, abspath REGISTER_RE = re.compile(r'lua_register\([a-zA-Z0-9_]+, "([^"]+)", ([^\)]+)\)') END_OF_DOC_RE = re.compile(r'\*/\s*$') C_COMMENT_RE = re.compile(r'/\*[^*]*\*+(?:[^/*][^*]*\*+)*/', re.MULTILINE) BLANK_RE = re.compile(r'^\s*$') COMMENT_RE = re.compile(r'^\s*/?\*+/?', re.MULTILINE) PKG_EXPORT_RE = re.compile( r'^(?:extern )?((?:unsigned )?[a-zA-Z0-9_]+ [a-zA-Z0-9_\[\]\*]+(?:\([^)]+\))?);'
def block_code(self, text, lang): # pygments code highlighting if lang is None: return u'<pre><code>{}</pre></code>'.format(text) return p.highlight(text, get_lexer_by_name(lang), HtmlFormatter(cssclass='codehilite'))
def live_paste(request): commit_kwargs = {} if request.user.is_authenticated(): commit_kwargs = { 'anonymous': request.user.preference.default_anonymous } if request.method != 'POST': return render_to_response( 'live.html', { 'forms': PasteSet(), 'set_form': SetForm(), 'commit_meta_form': CommitMetaForm(initial=commit_kwargs), 'set_meta_form': SetMetaForm(), }, RequestContext(request)) paste_forms = PasteSet(request.POST) set_form = SetForm(request.POST) commit_meta_form = CommitMetaForm(request.POST, initial=commit_kwargs) set_meta_form = SetMetaForm(request.POST) if (not paste_forms.is_valid() or not set_form.is_valid() or not commit_meta_form.is_valid() or not set_meta_form.is_valid()): return render_to_response( 'live.html', { 'forms': paste_forms, 'set_form': set_form, 'commit_meta_form': commit_meta_form, 'set_meta_form': set_meta_form, }, RequestContext(request)) # Repositories are just a random sequence of letters and digits # We store the reference repository for editing the pastes. repo_dir = os.sep.join([ settings.REPO_DIR, "".join(random.sample(string.letters + string.digits, 15)) ]) anonymous = commit_meta_form.cleaned_data.get('anonymous') os.mkdir(repo_dir) owner = None if request.user.is_authenticated() and not anonymous: owner = request.user description = set_form.cleaned_data.get('description') private = set_meta_form.cleaned_data.get('private') allow_edits = set_meta_form.cleaned_data.get('anyone_can_edit') # Calculate expiration time of set if necessary exp_option = set_meta_form.cleaned_data.get('expires') exp_map = { 'day': timedelta(days=1), 'hour': timedelta(hours=1), 'month': timedelta(365 / 12), } exp_time = datetime.utcnow( ) + exp_map[exp_option] if exp_option in exp_map else None # Generate a random hash for private access (20-30 characters from letters & numbers) private_key = ''.join( random.choice(string.ascii_letters + string.digits) for x in range(random.randrange(20, 30))) # Create a new paste set so we can reference our paste. paste_set = Set.objects.create( views=0, repo=repo_dir, owner=owner, description=description, private=private, anyone_can_edit=allow_edits, private_key=private_key, expires=exp_time, ) # Yes, this is horrible. I know. But there is a bug with Python Git. # See: https://github.com/gitpython-developers/GitPython/issues/39 os.environ['USER'] = "******" if owner: os.environ['USER'] = owner.username # Initialize a commit, git repository, and pull the current index. commit = Commit.objects.create(views=0, parent_set=paste_set, commit='', owner=owner) git_repo = git.Repo.init(repo_dir) index = git_repo.index # We enumerate over the forms so we can have a way to reference # the line numbers in a unique way relevant to the pastes. priority_filename = os.sep.join([repo_dir, 'priority.txt']) priority_file = open(priority_filename, 'w') for form_index, form in enumerate(paste_forms): data = form.cleaned_data filename = data['filename'] language_lex, language = data['language'].split(';') paste = data['paste'] # If we don't specify a filename, then obviously it is lonely if not len(filename): filename = 'paste' # Construct a more logical filename for our commit filename_base, ext = os.path.splitext(filename) filename_slugify = slugify(filename[:len(ext)]) filename_absolute = os.sep.join([repo_dir, filename]) filename_absolute += ext filename_abs_base, ext = os.path.splitext(filename_absolute) # If no extension was specified in the file, then we can append # the extension from the lexer. if not len(ext): filename_absolute += language filename += language ext = language # Gists doesn't allow for the same filename, we do. # Just append a number to the filename and call it good. i = 1 while os.path.exists(filename_absolute): filename_absolute = '%s-%d%s' % (filename_abs_base, i, ext) filename = '%s-%d%s' % (filename_base, i, ext) i += 1 cleaned = [] paste = paste.encode('UTF-8') for line in paste.split('\n'): line = line.rstrip() cleaned.append(line) paste = '\n'.join(cleaned) # Open the file, write the paste, call it good. f = open(filename_absolute, "w") f.write(paste) f.close() priority_file.write('%s: %s\n' % (filename, data['priority'])) paste = smart_unicode(paste) # This is a bit nasty and a get_by_ext something exist in pygments. # However, globals() is just much more fun. lex = globals()[language_lex] paste_formatted = highlight( paste, lex(), HtmlFormatter(style='friendly', linenos='table', lineanchors='line-%s' % form_index, anchorlinenos=True)) # Add the file to the index and create the paste index.add([filename_absolute]) p = Paste.objects.create(filename=filename, absolute_path=filename_absolute, paste=paste, priority=data['priority'], paste_formatted=paste_formatted, language=data['language'], revision=commit) # Add a priority file priority_file.close() index.add([priority_filename]) # Create the commit from the index new_commit = index.commit('Initial paste.') commit.commit = new_commit commit.save() if not paste_set.private: return redirect('paste_view', pk=paste_set.pk) else: return redirect('paste_view', pk=paste_set.pk, private_key=paste_set.private_key) return render_to_response('live.html')
def highlight(src): return pygments.highlight(src, CppLexer(), HtmlFormatter())
def colorize(value, arg=None): try: return mark_safe( highlight(value, get_lexer(value, arg), HtmlFormatter())) except ClassNotFound: return mark_safe("<pre>%s</pre>" % escape(value))
def render_body(context): context.caller_stack._push_frame() try: h = context.get('h', UNDEFINED) c = context.get('c', UNDEFINED) request = context.get('request', UNDEFINED) __M_writer = context.writer() # SOURCE LINE 5 __M_writer(u'\n\t<a href=') # SOURCE LINE 6 __M_writer( escape( h.url_for(controller="contest", action="tasks", id=c.task.contest_id))) __M_writer(u' class="back">zp\u011bt na sout\u011b\u017e</a>\n\t<h2>') # SOURCE LINE 7 __M_writer(escape(c.task.name)) __M_writer(u'</h2>\n\t') # SOURCE LINE 8 __M_writer(c.task.description) __M_writer( u'\n\n\t<hr style="visibility:hidden;">\n\n\t<div id="example_in"><h3>P\u0159\xedklad vstupu:</h3><pre>' ) # SOURCE LINE 12 __M_writer(escape(c.task.example_in)) __M_writer( u'</pre></div>\n\t<div id="example_out"><h3>P\u0159\xedklad v\xfdstupu:</h3><pre>' ) # SOURCE LINE 13 __M_writer(escape(c.task.example_out)) __M_writer(u'</pre></div>\n') # SOURCE LINE 14 from devcontest.model import Contest from devcontest.model.meta import Session # SOURCE LINE 17 __M_writer(u'\n') # SOURCE LINE 18 if Session.query( Contest.is_running).filter_by(id=c.task.contest_id).first()[0]: # SOURCE LINE 19 __M_writer(u'\t<hr>\n') # SOURCE LINE 20 if not c.status or request.environ.get('REMOTE_USER').admin: # SOURCE LINE 21 __M_writer(u'\t ') __M_writer( escape( h.form_start(h.url_for(param="upload"), method="post", multipart=True))) __M_writer(u'\n\t ') # SOURCE LINE 22 __M_writer(escape(h.field("Zdroják", h.file(name="source")))) __M_writer(u'\n\t ') # SOURCE LINE 23 __M_writer(escape(h.field("", h.submit("submit", "Nahrát")))) __M_writer(u'\n\t ') # SOURCE LINE 24 __M_writer(escape(h.form_end())) __M_writer(u'\n') pass # SOURCE LINE 26 if c.status: # SOURCE LINE 27 __M_writer( u'\t\t<div class="success">\xdaloha vy\u0159e\u0161ena</div>\n' ) pass # SOURCE LINE 29 __M_writer(u'\n') # SOURCE LINE 30 if c.source: # SOURCE LINE 31 __M_writer(u'\t<h3>Posledn\xed verze</h3>\n\t') # SOURCE LINE 32 from pygments import highlight from pygments.lexers import guess_lexer from pygments.formatters import HtmlFormatter # SOURCE LINE 36 __M_writer(u'\n') # SOURCE LINE 37 if c.source.errors: # SOURCE LINE 38 __M_writer(u'\t<pre>') __M_writer(escape(c.source.errors)) __M_writer(u'</pre>\n') pass # SOURCE LINE 40 __M_writer(u'\n\t') # SOURCE LINE 41 __M_writer( highlight(c.source.source, guess_lexer(c.source.source), HtmlFormatter(linenos=True))) __M_writer(u'\n\n') pass pass return '' finally: context.caller_stack._pop_frame()
from pygments.formatters import HtmlFormatter print HtmlFormatter().get_style_defs('.highlight')
def source_code_to_html(func): """Present function source code as HTML""" code = inspect.getsource(func) return highlight(code, PythonLexer(), HtmlFormatter(style='algol', lineseparator='<br />'))
from markupsafe import Markup from tornado.escape import xhtml_escape, to_unicode, _URL_RE from pygments import highlight from pygments.formatters import HtmlFormatter from pygments.lexers import get_lexer_by_name, TextLexer from gather.account.models import Account from gather.node.models import Node from gather.topic.models import Topic, Reply from gather.extensions import cache from gather.utils import gen_action_token _CODE_RE = re.compile(r'```(\w+)(.+?)```', re.S) _MENTION_RE = re.compile(r'((?:^|\W)@\w+)') _FLOOR_RE = re.compile(r'((?:^|[^&])#\d+)') _EMAIL_RE = re.compile(r'([A-Za-z0-9-+.]+@[A-Za-z0-9-.]+)(\s|$)') formatter = HtmlFormatter() def get_site_status(): account, node, topic, reply = cache.get_many('status-account', 'status-node', 'status-topic', 'status-reply') if not account: account = Account.query.count() cache.set('status-account', account) if not node: node = Node.query.count() cache.set('status-node', node) if not topic: topic = Topic.query.count() cache.set('status-topic', topic)
def paste(request, id): paste = Paste.objects.get(pk=id) highlighted = highlight(paste.content, PythonLexer(), HtmlFormatter()) paste.content = highlighted ctx = {'paste': paste} return render(request, 'pastebin/paste-detail.jinja2', ctx)
def _colorLog(self, log: str) -> str: color_log = highlight( log, SASLogLexer(), HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>")) return color_log
def diff(request, src_profile, dest_profile): src_profile = get_object_or_404(FwProfile, slug=src_profile) dest_profile = get_object_or_404(FwProfile, slug=dest_profile) html_formatter = HtmlFormatter() style = html_formatter.get_style_defs() def add_rm_chg(src, dest): return dest - src, src - dest, src.intersection(dest) def _highlight(diff): return pygments.highlight(diff, DiffLexer(), html_formatter) packages_added, packages_removed, packages_same = add_rm_chg( set(src_profile.include_packages.split()), set(dest_profile.include_packages.split())) packages_old = list(packages_removed) + list(packages_same) packages_new = list(packages_added) + list(packages_same) packages_diff = _highlight("\n".join( unified_diff(packages_old, packages_new))) files_added, files_removed, files_changed = add_rm_chg( set(src_profile.include_files), set(dest_profile.include_files)) for filename in files_changed.copy(): if src_profile.include_files[filename] == dest_profile.include_files[ filename]: files_changed.remove(filename) def highlight_diff(filename): out = "\n".join( unified_diff( src_profile.include_files.get(filename, "").splitlines(), dest_profile.include_files.get(filename, "").splitlines(), filename, filename)) return _highlight(out) files_changed = [(filename, highlight_diff(filename)) for filename in files_changed] files_added = [(filename, highlight_diff(filename)) for filename in files_added] files_removed = [(filename, highlight_diff(filename)) for filename in files_removed] return render( request, "firmcreator/diff.html", { 'style': style, 'files_added': files_added, 'files_changed': files_changed, 'files_removed': files_removed, 'packages_diff': packages_diff, 'inverse_diff': reverse("fwprofile-diff", args=(dest_profile.slug, src_profile.slug)), })
def highlight_machine_code(mnemonics, snippet): lexer = PatchedGasLexer if mnemonics == 'intel': lexer = PatchedNasmLexer return highlight(snippet, lexer(), HtmlFormatter())
def view_file(repo, identifier, filename, username=None): """ Displays the content of a file or a tree for the specified repo. """ repo = pagure.lib.get_project(SESSION, repo, user=username) if not repo: flask.abort(404, 'Project not found') reponame = pagure.get_repo_path(repo) repo_obj = pygit2.Repository(reponame) if repo_obj.is_empty: flask.abort(404, 'Empty repo cannot have a file') if identifier in repo_obj.listall_branches(): branchname = identifier branch = repo_obj.lookup_branch(identifier) commit = branch.get_object() else: try: commit = repo_obj.get(identifier) branchname = identifier except ValueError: if 'master' not in repo_obj.listall_branches(): flask.abort(404, 'Branch no found') # If it's not a commit id then it's part of the filename commit = repo_obj[repo_obj.head.target] branchname = 'master' if commit and not isinstance(commit, pygit2.Blob): content = __get_file_in_tree( repo_obj, commit.tree, filename.split('/'), bail_on_tree=True) if not content: flask.abort(404, 'File not found') content = repo_obj[content.oid] else: content = commit if not content: flask.abort(404, 'File not found') if isinstance(content, pygit2.Blob): if content.is_binary or not pagure.lib.could_be_text(content.data): ext = filename[filename.rfind('.'):] if ext in ( '.gif', '.png', '.bmp', '.tif', '.tiff', '.jpg', '.jpeg', '.ppm', '.pnm', '.pbm', '.pgm', '.webp', '.ico'): try: Image.open(StringIO(content.data)) output_type = 'image' except IOError as err: LOG.debug( 'Failed to load image %s, error: %s', filename, err ) output_type = 'binary' else: output_type = 'binary' else: try: lexer = guess_lexer_for_filename( filename, content.data ) except (ClassNotFound, TypeError): lexer = TextLexer() content = highlight( content.data, lexer, HtmlFormatter( noclasses=True, style="tango",) ) output_type = 'file' else: content = sorted(content, key=lambda x: x.filemode) output_type = 'tree' return flask.render_template( 'file.html', select='tree', repo=repo, username=username, branchname=branchname, filename=filename, content=content, output_type=output_type, repo_admin=is_repo_admin(repo), )
def misc_pygments(request): return HtmlFormatter().get_style_defs('.highlight')
def pygments_filter(code): return highlight(code, PythonLexer(), HtmlFormatter())
def test_get_background_style_defs_uses_multiple_css_prefixes(): formatter = HtmlFormatter() lines = formatter.get_background_style_defs([".foo", ".bar"]) assert lines[0].startswith(".foo .hll, .bar .hll {") assert lines[1].startswith(".foo , .bar {")
def highlight_snippet(snippet): return highlight(snippet, PythonLexer(), HtmlFormatter())
def pythonprettyprint(val): s = pprint.pformat(val) lexer = lexers.get_lexer_by_name('python') formatter = HtmlFormatter() return mark_safe(highlight(s, lexer, formatter))
def check(optdict): outfile = StringIO() fmt = HtmlFormatter(**optdict) fmt.format(tokensource, outfile)
def highlight_code(ed): addon_conf = mw.col.conf['syntax_highlighting_conf'] # Do we want line numbers? linenos is either true or false according # to the user's preferences linenos = addon_conf['linenos'] centerfragments = addon_conf['centerfragments'] # Do we want to use css classes or have formatting directly in HTML? # Using css classes takes up less space and gives the user more # customization options, but is less self-contained as it requires # setting the styling on every note type where code is used noclasses = not addon_conf['cssclasses'] selected_text = ed.web.selectedText() if selected_text: # Sometimes, self.web.selectedText() contains the unicode character # '\u00A0' (non-breaking space). This character messes with the # formatter for highlighted code. To correct this, we replace all # '\u00A0' characters with regular space characters code = selected_text.replace('\u00A0', ' ') else: clipboard = QApplication.clipboard() # Get the code from the clipboard code = clipboard.text() langAlias = ed.codeHighlightLangAlias # Select the lexer for the correct language try: my_lexer = get_lexer_by_name(langAlias, stripall=True) except ClassNotFound as e: print(e) showError(ERR_LEXER, parent=ed.parentWindow) return False # Create html formatter object including flags for line nums and css classes try: my_formatter = HtmlFormatter(linenos=linenos, noclasses=noclasses, font_size=16, style=STYLE) except ClassNotFound as e: print(e) showError(ERR_STYLE, parent=ed.parentWindow) return False if linenos: if centerfragments: pretty_code = "".join([ "<center>", highlight(code, my_lexer, my_formatter), "</center><br>" ]) else: pretty_code = "".join( [highlight(code, my_lexer, my_formatter), "<br>"]) # TODO: understand why this is neccessary else: if centerfragments: pretty_code = "".join([ "<center>", highlight(code, my_lexer, my_formatter), "</center><br>" ]) else: pretty_code = "".join( [highlight(code, my_lexer, my_formatter), "<br>"]) pretty_code = process_html(pretty_code) # These two lines insert a piece of HTML in the current cursor position ed.web.eval("document.execCommand('inserthtml', false, %s);" % json.dumps(pretty_code))
def test_get_style_defs_contains_pre_style(): style_defs = HtmlFormatter().get_style_defs().splitlines() assert style_defs[0] == 'pre { line-height: 125%; margin: 0; }'