예제 #1
0
    def test_get_style_defs(self):
        fmt = HtmlFormatter()
        sd = fmt.get_style_defs()
        self.assert_(sd.startswith('.'))

        fmt = HtmlFormatter(cssclass='foo')
        sd = fmt.get_style_defs()
        self.assert_(sd.startswith('.foo'))
        sd = fmt.get_style_defs('.bar')
        self.assert_(sd.startswith('.bar'))
        sd = fmt.get_style_defs(['.bar', '.baz'])
        fl = sd.splitlines()[0]
        self.assert_('.bar' in fl and '.baz' in fl)
예제 #2
0
    def post(self):
        #get language 
        lang = self.request.get('lang')
        #get code
        code = self.request.get('code')

        #format code
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = HtmlFormatter()
        formatter.get_style_defs('.syntax')
        
        response = {"html": highlight(code, lexer, formatter)}
        
        #render json response
        self.response.out.write(json.dumps(response))
예제 #3
0
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
예제 #4
0
파일: revisions.py 프로젝트: NORDUnet/peer
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,
        )
예제 #5
0
    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)
예제 #6
0
파일: web.py 프로젝트: isleei/WeasyPrint
    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())
예제 #7
0
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
예제 #8
0
    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
예제 #9
0
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)
    )
예제 #10
0
class InspectorMagics(Magics):
    
    def __init__(self, **kwargs):
        super(InspectorMagics, self).__init__(**kwargs)
        self.formatter = HtmlFormatter()
        self.lexer = PythonLexer()
        self.style_name = "default"
    
    @line_magic
    def showsrc(self, line):
        line = line.strip()
        filename, identifier = line.rsplit(None, 1)
        modname, ext = os.path.splitext(filename)
        mod = __import__(modname)
        reload(mod)
        linecache.checkcache()
        obj = getattr(mod, identifier)
        lines, lineno = inspect.getsourcelines(obj)
        self.formatter.linenos = True
        self.formatter.linenostart = lineno
        html = "<span class='inspector-header'>"
        html += "<span class='inspector-filename'>%s: </span>" % filename
        html += "<span class='inspector-lineno'>%i-%i</span>" % (lineno, lineno + len(lines))
        html += "</span>"
        html += highlight(''.join(lines), self.lexer, self.formatter)
        display(HTML(html))
    
    @line_magic
    def showsrcstyle(self, line):
        """publish the CSS for highlighting used in %showsrc
        
        Takes a """
        
        name = line.strip()
        if not name:
            name = "default"
        self.style_name = name
        self.formatter = HtmlFormatter(style=name)
        display(HTML("""<style type='text/css'>
        span.inspector-header {
            font-family: monospace;
            border-bottom: 1px solid #555;
        }
        table.highlighttable, .highlighttable td, .highlighttable tr {
            border: 0px;
        }
        .highlighttable td.linenos {
            border-right: 1px solid #555;
        }
        
        span.inspector-filename {
            text-decoration: italic;
        }
        span.inspector-lineno {
            font-weight: bold;
        }
        %s
        </style>
        """ % self.formatter.get_style_defs()
        ))
예제 #11
0
    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
        sheet_filename = os.path.join(path.get_ipython_package_dir(), "html", "static", "style", "style.min.css")

        # Load style CSS file.
        try:
            with io.open(sheet_filename, encoding="utf-8") as file:
                file_text = file.read()
                header.append(file_text)
        except IOError:

            # New version of IPython with style.min.css, pass
            pass

        # Add pygments CSS
        formatter = HtmlFormatter()
        pygments_css = formatter.get_style_defs(self.highlight_class)
        header.append(pygments_css)

        # Set header
        self.header = header
예제 #12
0
파일: gitlog.py 프로젝트: masarliev/gitlog
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))
예제 #13
0
파일: debug.py 프로젝트: rivrproject/rivr
    def process_exception(self, request, e):
        if isinstance(e, Http404):
            return self.process_404(request)

        import traceback
        tb = '\n'.join(traceback.format_exception(*sys.exc_info()))

        if HAS_PYGMENTS:
            formatter = HtmlFormatter(style='borland')
            html_tb = highlight(tb, PythonTracebackLexer(), formatter)
        else:
            html_tb = '<pre><code>%s</pre></code>' % (tb)

        context = {
            'title': str(e),
            'traceback': html_tb,
            'request': repr(request).replace('>', '&gt;').replace('<', '&lt;'),
            'version': VERSION,
            'python_version': '{}.{}.{}-{}-{}'.format(*sys.version_info),
            'css': ERROR_CSS,
        }

        if HAS_PYGMENTS:
            context['css'] += formatter.get_style_defs('.highlight')

        return Response(ERROR_TEMPLATE.format(**context), status=500)
예제 #14
0
    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)
예제 #15
0
    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
예제 #16
0
파일: views.py 프로젝트: peterbe/webalyzer
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)
예제 #17
0
    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('&gt;'))
                           .replace(b('<'), b('&lt;')))
예제 #18
0
파일: views.py 프로젝트: gtt116/novalog
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)
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
예제 #20
0
파일: models.py 프로젝트: xando/funnybag
 def render(self):
     lexer = get_lexer_by_name(self.language)
     formatter = HtmlFormatter(linenos=True)
     code = mark_safe(highlight(self.code, lexer, formatter))
     template = loader.get_template('core/blocks/code.html')
     return template.render(Context({'code': code,
                                     'styles' : formatter.get_style_defs('.highlight')}))
예제 #21
0
    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
예제 #22
0
 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>')
예제 #23
0
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 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
    )
예제 #25
0
파일: display.py 프로젝트: EconForge/dolo
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)
예제 #26
0
파일: pyshell.py 프로젝트: sdiehl/tipy
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)
예제 #27
0
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
예제 #28
0
파일: main.py 프로젝트: MrChoclate/PPaste
def highlight_paste(paste):
    '''Use pygments to syntax highlight a paste, returns by the way the CSS'''
    lexer = get_lexer_by_name(paste.hl_alias)
    formatter = HtmlFormatter(linenos=True, cssclass='source')
    return (
        highlight(paste.content, lexer, formatter),
        formatter.get_style_defs('.source')
    )
예제 #29
0
파일: syntax.py 프로젝트: BastinRobin/a.out
 def render(self, context):
     if not is_qouted(self.style):
         self.style = template.Variable(self.style).resolve(context)
     else: self.style = self.style[1:-1]
     if self.linenos:
         formatter = HtmlFormatter(style = get_style_by_name(self.style), linenos = self.linenos)
     else: formatter = HtmlFormatter(style = get_style_by_name(self.style))
     return mark_safe(formatter.get_style_defs('.highlight'))
예제 #30
0
 def style_defs(cls):
     """
     Return the CSS style definitions required
     by the formatted snippet.
     """
     formatter = HtmlFormatter()
     formatter.style.highlight_color = cls.VIOLATION_COLOR
     return formatter.get_style_defs()
예제 #31
0
def schema_upgrade(context, request):
    dbsync = IndexDatabaseSyncAdapter(context.collection, request)
    if not dbsync.need_update:
        return morpfw.redirect(request.link(context))
    code = dbsync.migration_code
    formatter = HtmlFormatter()
    highlighted = highlight(code, PythonLexer(), formatter)
    return {
        "hide_title": True,
        "need_update": dbsync.need_update,
        "code": code,
        "highlighted_code": highlighted,
        "highlight_styles": formatter.get_style_defs(".highlight"),
    }
예제 #32
0
    def taskerror(taskid):
        if not has_permission('read'):
            abort(403, 'Nothing to see there.')

        job = getjob(engine, taskid)
        if job is None:
            abort(404, 'job does not exists')

        formatter = HtmlFormatter()
        traceback = highlight(job.traceback, PythonTracebackLexer(), formatter)
        return render_template('taskerror.html',
                               tid=taskid,
                               css=formatter.get_style_defs(),
                               traceback=traceback)
예제 #33
0
파일: admin.py 프로젝트: stevekm/beagle
 def _pretty_python_exception(obj):
     json_obj = getattr(obj, field_name)
     if not json_obj:
         return "-"
     message = json_obj["details"]
     if message[0:5] == "Error" and message[7:]:
         error = ast.literal_eval(message[7:])
         error = " ".join(error)
         formatter = HtmlFormatter(style='colorful')
         response = highlight(error, PythonLexer(), formatter)
         style = "<style>" + formatter.get_style_defs() + ".highlight{width: 500px; overflow: scroll; border: 1px solid gray;}</style>"
         return mark_safe(style + response)
     else:
         return message
예제 #34
0
def pygments_style_defs(style='default'):
    """:return: the CSS definitions for the `CodeHilite`_ Markdown plugin.

    :param style: The Pygments `style`_ to use.

    Only available if `Pygments`_ is.

    .. _CodeHilite:
       http://www.freewisdom.org/projects/python-markdown/CodeHilite
    .. _Pygments: http://pygments.org/
    .. _style: http://pygments.org/docs/styles/
    """
    formatter = PygmentsHtmlFormatter(style=style)
    return formatter.get_style_defs('.codehilite')
예제 #35
0
def diff_view(request, domain, id):
    result = get_object_or_404(Result, id=id, domain=domain)
    context = {}

    html_formatter = HtmlFormatter(linenos=True,
                                   lineanchors='L',
                                   linespans='L',
                                   anchorlinenos=True)
    context['code'] = highlight(diff_table(result.before, result.after),
                                DiffLexer(), html_formatter)
    context['domain'] = domain
    context['result'] = result
    context['pygments_css'] = html_formatter.get_style_defs('.highlight')
    return render(request, 'analyzer/diff_view.html', context)
예제 #36
0
def main():
    formatter = HtmlFormatter(full=False, style='monokai')

    html = []
    with open('out.html', 'w') as f:
        html.append('<link rel="stylesheet" type="text/css" href="style.css">')
        html.append(MARKDOWN)
        html.append(highlight(CODE, ScalaLexer(), formatter))
        html.append(highlight(RESULT, PythonConsoleLexer(), formatter))
        html.append(MARKDOWN1)
        f.write("\n\n".join(html))

    with open('style.css', 'w') as f:
        f.write(formatter.get_style_defs('body'))
예제 #37
0
def get_highlighted_file(cache_prefix, name, content_hash, content):
    """ Highlights a file for display in a repository's browsing UI.
    """
    key = f"{cache_prefix}:highlight:{content_hash}"
    html = redis.get(key)
    if html:
        return Markup(html.decode())

    lexer = _get_lexer(name, content)
    formatter = HtmlFormatter()
    style = formatter.get_style_defs('.highlight')
    html = f"<style>{style}</style>" + highlight(content, lexer, formatter)
    redis.setex(key, timedelta(days=7), html)
    return Markup(html)
예제 #38
0
파일: views.py 프로젝트: L4wk3R/DWSE
def data_prettified(data):
    """Function to display pretty version of our data"""
    # Convert the data to sorted, indented JSON
    response = json.dumps(data, 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)
예제 #39
0
    def _pygmentsDemo(self):

        from pygments import highlight
        from pygments.lexers import PythonLexer
        from pygments.formatters import HtmlFormatter

        code = 'def foo(x="bar"): return True'

        lexer = PythonLexer()
        formatter = HtmlFormatter()
        codeHtml = highlight(code, lexer, formatter)

        doc = self.textEdit.document()
        doc.defaultStyleSheet = formatter.get_style_defs()
        doc.setHtml(codeHtml)
예제 #40
0
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)
예제 #41
0
파일: models.py 프로젝트: Kuzyashin/10flats
 def pretty_answers(self):
     if not self.answers:
         return ''
     try:
         points = json.dumps(
             json.loads(self.answers), sort_keys=True,
             indent=2, ensure_ascii=False
         )
     except Exception as e:
         logger.error('Parsing content error %s' % e)
         return ''
     formatter = HtmlFormatter(style='colorful')
     output = highlight(points, JsonLexer(), formatter)
     style = "<style>" + formatter.get_style_defs() + "</style><br>"
     return mark_safe(style + output)
def index():
    readme_file = open("README.md", "r")
    md_template_string = markdown.markdown(
        readme_file.read(), extensions=["fenced_code", "codehilite"])

    # Generate css for syntax highlighting
    formatter = HtmlFormatter(style="friendly",
                              full=True,
                              cssclass="codehilite")
    css_string = formatter.get_style_defs()
    md_css_string = "<style>" + css_string + "</style>"

    md_template = md_css_string + md_template_string
    print(md_template)
    return md_template
예제 #43
0
    def display_source_ipython(self):
        """Display source code as syntax highlighted HTML within IPython."""
        import IPython.display as display
        from pygments import highlight
        from pygments.formatters import HtmlFormatter
        from pygments.lexers import JuliaLexer

        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, JuliaLexer(), formatter),
        ))
예제 #44
0
def print_code(code):
    template = """<style>
    {}
    </style>
    {}
    """

    lexer = Python3Lexer()
    formatter = HtmlFormatter(cssclass='pygments')

    html_code = highlight(code, lexer, formatter)
    css = formatter.get_style_defs('.pygments')

    html = template.format(css, html_code)
    return display(HTML(html))
예제 #45
0
    def _generate_header(self, resources):
        """
        Fills self.header with lines of CSS extracted from IPython
        and Pygments.
        """
        header = []

        # Add pygments CSS

        from pygments.formatters import HtmlFormatter
        formatter = HtmlFormatter(style=self.style)
        pygments_css = formatter.get_style_defs(self.highlight_class)
        header.append(pygments_css)

        return header
예제 #46
0
    def generate_content(cls, attachment):
        mime_type = attachment.file.content_type

        lexer = cls.CUSTOM_LEXERS.get(mime_type)
        if lexer is None:
            lexer = get_lexer_for_mimetype(mime_type)

        with attachment.file.open() as f:
            html_formatter = HtmlFormatter(style='tango', linenos='inline', prestyles='mono')
            html_code = highlight(f.read(), lexer, html_formatter)

        css_code = html_formatter.get_style_defs('.highlight')

        return render_template('previewer_code:pygments_preview.html', attachment=attachment,
                               html_code=html_code, css_code=css_code)
예제 #47
0
def highlight_content(context, content, mimetype):
    """render content as highlighted HTML"""

    hformat = HtmlFormatter()
    css = hformat.get_style_defs('.highlight')
    if mimetype == 'json':
        body = highlight(json.dumps(content, indent=4), JsonLexer(), hformat)
    elif mimetype == 'xml':
        body = highlight(prettify_xml(content), XmlLexer(), hformat)

    env = Environment(loader=FileSystemLoader(context.ppath))

    template_file = 'resources/templates/api_highlight.html'
    template = env.get_template(template_file)
    return template.render(css=css, body=body)
예제 #48
0
    def url(self, instance):
        ss = SailStreamServer.objects.all()
        if len(ss) == 0:
            return format_html('<span style="color:{};">{}</span>', 'orange',
                               "Please config SailStreamServer in conf")
        elif len(ss) > 1:
            return format_html('<span style="color:{};">{}</span>', 'orange',
                               "SailStreamServer in conf is more than one")

        payload = {
            "cameraName": instance.name,
            "accessKey": instance.camera_manager.access_key,
            "t": int(time.time()),
        }
        token = jwt.encode(payload,
                           instance.camera_manager.secret_key,
                           algorithm="HS256")

        urls = {
            "ChannelKey":
            "http://{}:{}/control/get?cameraName={}&accessKey={}&token={}".
            format(ss[0].host, ss[0].api_port, instance.name,
                   instance.camera_manager.access_key, token),
            "RTMP":
            "rtmp://{}:{}/live/{}?accessKey={}&token={}".format(
                ss[0].host, ss[0].rtmp_port, instance.name,
                instance.camera_manager.access_key, token),
            "FLV":
            "http://{}:{}/live/{}.flv?accessKey={}&token={}".format(
                ss[0].host, ss[0].flv_port, instance.name,
                instance.camera_manager.access_key, token),
            "HLS":
            "http://{}:{}/live/{}.m3u8?accessKey={}&token={}".format(
                ss[0].host, ss[0].hls_port, instance.name,
                instance.camera_manager.access_key, token),
        }

        response = json.dumps(urls, indent=4)
        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)
예제 #49
0
def show_block(height=None, hash=None, more_details=False):
    lmq, oxend = lmq_connection()
    info = FutureJSON(lmq, oxend, 'rpc.get_info', 1)
    hfinfo = FutureJSON(lmq, oxend, 'rpc.hard_fork_info', 10)
    if height is not None:
        val = height
    elif hash is not None:
        val = hash

    block = None if val is None else block_with_txs_req(lmq, oxend, val).get()
    if block is None:
        return flask.render_template("not_found.html",
                info=info.get(),
                hfinfo=hfinfo.get(),
                type='block',
                height=height,
                id=hash
                )

    next_block = None
    block_height = block['block_header']['height']
    txs = get_block_txs_future(lmq, oxend, block)

    if info.get()['height'] > 1 + block_height:
        next_block = block_header_req(lmq, oxend, '{}'.format(block_height + 1))

    if more_details:
        formatter = HtmlFormatter(cssclass="syntax-highlight", style="native")
        more_details = {
                'details_css': formatter.get_style_defs('.syntax-highlight'),
                'details_html': highlight(json.dumps(block, indent="\t", sort_keys=True), JsonLexer(), formatter),
                }
    else:
        more_details = {}

    transactions = [] if txs is None else parse_txs(txs.get()).copy()
    miner_tx = transactions.pop() if transactions else []

    return flask.render_template("block.html",
            info=info.get(),
            hfinfo=hfinfo.get(),
            block_header=block['block_header'],
            block=block,
            miner_tx=miner_tx,
            transactions=transactions,
            next_block=next_block.get() if next_block else None,
            **more_details,
            )
예제 #50
0
    def highlight_html(self, parameter_s=''):
        """
        Display the contents of a source code file with syntax highlighting.

        You must be in an environment that can display HTML output.
        Requires the pygments library.

        Usage:
            %highlight [options] <file name>

        Options:

            -n: Show line numbers.

            -s <style name>: An available Pygments style, default is 'default'.

            -l <lexer name>: Manually specify the language of the code using
                any lexer name from http://pygments.org/docs/lexers/.
                By default the source language is guessed from the file name.

        """
        opts_def = Struct(l='', s='default')
        opts, arg_str = self.parse_options(parameter_s, 'l:s:n')
        opts.merge(opts_def)

        if opts.l:
            lexer = get_lexer_by_name(opts.l)
        else:
            lexer = get_lexer_for_filename(arg_str)

        if 'n' in opts:
            linenos = 'table'
        else:
            linenos = False

        formatter = HtmlFormatter(style=opts.s,
                                  cssclass='pygments' + str(uuid.uuid4()),
                                  linenos=linenos)

        with open(arg_str) as f:
            code = f.read()

        html_code = highlight(code, lexer, formatter)
        css = formatter.get_style_defs()

        html = HTML_TEMPLATE.format(css, html_code)

        display(HTML(html))
예제 #51
0
 def toOriginHtml(self, err_type=None, err_value=None, err_traceback=None):
     exc_info = "".join(
         traceback.format_exception(err_type, err_value, err_traceback))
     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)
     if pygments is None:
         html += "<pre>%s</pre>" % exc_info
     else:
         html += highlight(exc_info, PythonTracebackLexer(), formatter)
     html += "</body></html>"
     return html
예제 #52
0
 def install_script(self, instance: MinecraftServerConfig) -> str:
     "Get the install script HTML formatted for display"
     html_formatter = HtmlFormatter(cssclass="install-script")
     return mark_safe(
         "".join([
             highlight(
                 instance.get_install_script(),
                 BashLexer(),
                 html_formatter
             ),
             "<style type=\"text/css\">",
             ".install-script { padding: 5px 10px; border-radius: 4px; }",
             html_formatter.get_style_defs(),
             "</style>",
         ])
     )
예제 #53
0
def diff(request, name, revN, revM, path='/'):
    resp, r, rc = check_acl(request, name, path)
    if resp is not None:
        return resp

    content = svn.DIFF(r, revN, revM)

    if content is not None and len(content) > 0:
        hf = HtmlFormatter(encoding='utf8')
        rc.content_style = hf.get_style_defs('.highlight')
        rc.content = highlight(safe_esc(force_unicode(content)), DiffLexer(), hf)

    rc.revN = revN
    rc.revM = revM
    return send_response(request, 
                         'repos/view_diff.html')
예제 #54
0
    def __colorize(self, params_dict, content):
        """
        Раскраска исходников. Возвращает получившийся HTML и добавляет нужные стили в заголовок страницы
        """
        from pygments import highlight
        from pygments.formatters import HtmlFormatter

        lexermaker = LexerMaker()
        lexer = lexermaker.getLexer(params_dict)

        linenum = LINE_NUM_PARAM_NAME in params_dict
        parentbg = PARENT_BACKGROUND_PARAM_NAME in params_dict

        style = self.__getStyle(params_dict)
        cssclass = self.__getCssClass(style, parentbg)

        formatter = HtmlFormatter(linenos=linenum,
                                  cssclass=cssclass,
                                  style=style)

        if cssclass not in self.__appendCssClasses:
            sourceStyle = formatter.get_style_defs()

            # Нужно для улучшения внешнего вида исходников
            sourceStyle += CUSTOM_STYLES.format(name=cssclass)

            if parentbg:
                sourceStyle += u"\n.{name} {{color: inherit; background-color: inherit }}".format(
                    name=cssclass)

            styleTemplate = u"<STYLE>{0}</STYLE>"
            self.parser.appendToHead(styleTemplate.format(sourceStyle))
            self.parser.appendToHead(
                styleTemplate.format("".join(
                    ["div.", cssclass, HIGHLIGHT_STYLE])))

            self.__appendCssClasses.append(cssclass)

        content = highlight(content, lexer, formatter)

        result = u"".join(
            [u'<div class="source-block">',
             content.strip(), u'</div>'])
        result = result.replace("\n</td>", "</td>")

        return result
예제 #55
0
def post(post):
    #parse the md file
    filepath = Path(f'{POST_DIR}/{post}')
    md_file = open(filepath, "r")
    md = markdown.Markdown(extensions=["fenced_code", "codehilite", "meta"])
    html = md.convert(md_file.read())
    #apply formatting
    formatter = HtmlFormatter(style="emacs",full=True,cssclass="codehilite")
    css_string = formatter.get_style_defs()
    md_css_string = "<style>" + css_string + "</style>"
    #prepend meta information to the html output
    post_title = "<h2>" + str(md.Meta['title'][0]) + "</h2>"
    post_date = "<b>" + str(md.Meta['published-on'][0]) + "</b>"
    html = post_title + post_date + html
    #combine html and css
    markdown_post = md_css_string + html
    return markdown_post
예제 #56
0
def highlight_file(filename):
    lexer = get_lexer_for_filename(filename)

    linenos = "inline"

    formatter = HtmlFormatter(style="default",
                              cssclass="pygments",
                              linenos=linenos)

    with open(filename) as f:
        code = f.read()

    html_code = highlight(code, lexer, formatter)
    css = formatter.get_style_defs()
    css += EXTRA_CSS

    return HTML(HTML_TEMPLATE.format(css, html_code))
예제 #57
0
def json(debugger, expression):
    # get JSON string
    value = get_value(debugger, expression)
    json_string = value.GetObjectDescription()

    # prettify JSON
    pretty_json_string = json_lib.dumps(json_lib.loads(json_string),
                                        sort_keys=True,
                                        indent=4)

    # render HTML with highlighted JSON
    formatter = HtmlFormatter(linenos=True)
    html = """
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">

        <style>
            {style}
        </style>
    </head>

    <body>
        {body}
    </body>
</html>
    """.format(
        **{
            'style': formatter.get_style_defs('.highlight'),
            'body': highlight(pretty_json_string, JavascriptLexer(),
                              formatter),
        })

    # save HTML to a temporary file
    with NamedTemporaryFile(delete=False) as f:
        f.write(html)

        # add ".html" extension
        original_path = f.name
        path = original_path + '.html'
        system('mv "%s" "%s"' % (original_path, path))

    # show HTML in Quick Look and delete file at the end
    system('qlmanage -p "%s" > /dev/null && rm "%s" &' % (path, path))
예제 #58
0
def image_export(input_path: str, output_path: str, style: str, zoom: float = 2.0):
    """
    Export code (Python script or Jupyter Notebook) as a image.

        Parameters
    ----------
    input_path: str
                    Path of the file that contains cells to be exported.
    output_path: str
                    Output path of the exported images. If two images are exported, then paths for them will
                    be '0_output_path' and '1_output_path'
    style: bool
                    Style of the exported image. For the list of supported styles use 'available_styles()'
                    function.
    zoom: float
                    Zoom factor for the output image.
    Returns
    ------
    None
    """
    input_path = Path(input_path)
    output_path = Path(output_path)
    if not input_path.exists():
        raise FileNotFoundError(input_path)
    #  Check style is valid
    if style not in available_styles():
        raise StyleNotFoundError(style)
    if output_path.suffix not in _supported_image_formats:
        raise UnsupportedFileExtensionError(output_path, _supported_image_formats)
    blocks = _parse_blocks(input_path)
    lexer = PythonLexer()
    formatter = HtmlFormatter(style=style)

    #  Options for imgkit
    options = {
        'quiet': '',  #  Do not show any output
        'zoom': zoom,  #  Zoom level
    }

    for i, block in enumerate(blocks):
        highlighted_block = highlight(block, lexer, formatter)
        #  We are closing StringIO after reading it, therefore we need to recreate it.
        css_buffer = io.StringIO(formatter.get_style_defs('.highlight'))
        output_path_formatted = f"{output_path}" if len(blocks) == 1 else f"{i}_{output_path}"
        imgkit.from_string(highlighted_block, output_path_formatted, css=css_buffer, options=options)
예제 #59
0
def retrieve(request):
    if request.method == "POST":
        json_file_name = request.POST.get('json_file_name', None)
        json_data = json.load(open(json_file_name))

        json_data = json.dumps(json_data, sort_keys=True, indent=4)
        formatter = HtmlFormatter(style='colorful')
        response = highlight(json_data, JsonLexer(), formatter)
        style = "<style>" + formatter.get_style_defs() + "</style><br>"

        template = loader.get_template('frontend/retrieve.html')
        context = {
            "json_file_name": json_file_name,
            "json_data": mark_safe(style + response),
            "json_data_unformatted": json.loads(json_data)
        }

        return HttpResponse(template.render(context, request))
예제 #60
0
def view_source(context, web_view, filename):
    from base64 import b64encode
    from os.path import join
    from pygments import highlight
    from pygments.formatters import HtmlFormatter
    from pygments.lexers import get_lexer_for_filename

    from java.io import BufferedReader, InputStreamReader

    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")