python类HtmlFormatter()的实例源码

slidoc.py 文件源码 项目:slidoc 作者: mitotic 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def block_code(self, code, lang=None):
        """Rendering block level code. ``pre > code``.
        """
        lexer = None
        if code.endswith('\n\n'):
            code = code[:-1]
        if HtmlFormatter and lang:
            try:
                lexer = get_lexer_by_name(lang, stripall=True)
            except ClassNotFound:
                code = lang + '\n' + code

        if not lexer or not HtmlFormatter:
            return '\n<pre><code>%s</code></pre>\n' % mistune.escape(code)

        formatter = HtmlFormatter()
        return highlight(code, lexer, formatter)
views.py 文件源码 项目:incubator-airflow-old 作者: apache 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def code(self):
        dag_id = request.args.get('dag_id')
        dag = dagbag.get_dag(dag_id)
        title = dag_id
        try:
            with open(dag.fileloc, 'r') as f:
                code = f.read()
            html_code = highlight(
                code, lexers.PythonLexer(), HtmlFormatter(linenos=True))
        except IOError as e:
            html_code = str(e)

        return self.render(
            'airflow/dag_code.html', html_code=html_code, dag=dag, title=title,
            root=request.args.get('root'),
            demo_mode=conf.getboolean('webserver', 'demo_mode'))
wiki.py 文件源码 项目:pygameweb 作者: pygame 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _wiki_code(content):
    """
    >>> u = _wiki_code('<code class="python">my_code()</code>')
    >>> expected = '<div class="highlight"><pre><span class="n">my_code</span><span class="p">()</span>\\n</pre></div>\\n'
    >>> expected in u
    True

    """
    css_class = "python"
    if css_class:
        content = content.replace('<code>', '<code class=\"%s\">' % css_class);

    #syntax_css = u"<style>%s</style>" % HtmlFormatter().get_style_defs('.highlight')
    #content = syntax_css + content

    return re.sub(r'\<code\s+class\s*\=\s*\"([^\"]+)\"\>(.*?)\<\/code>',
                  _wiki_code_callback, content, flags=re.I | re.S)
diaphora_ida.py 文件源码 项目:maltindex 作者: joxeankoret 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def show_asm(self, item, primary):
    cur = self.db_cursor()
    if primary:
      db = "main"
    else:
      db = "diff"
    ea = str(int(item[1], 16))
    sql = "select prototype, assembly, name from %s.functions where address = ?"
    sql = sql % db
    cur.execute(sql, (ea, ))
    row = cur.fetchone()
    if row is None:
      Warning("Sorry, there is no assembly available for the selected function.")
    else:
      fmt = HtmlFormatter()
      fmt.noclasses = True
      fmt.linenos = True
      asm = self.prettify_asm(row["assembly"])
      final_asm = "; %s\n%s proc near\n%s\n%s endp\n"
      final_asm = final_asm % (row["prototype"], row["name"], asm, row["name"])
      src = highlight(final_asm, NasmLexer(), fmt)
      title = "Assembly for %s" % row["name"]
      cdiffer = CHtmlViewer()
      cdiffer.Show(src, title)
    cur.close()
diaphora_ida.py 文件源码 项目:maltindex 作者: joxeankoret 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def show_pseudo(self, item, primary):
    cur = self.db_cursor()
    if primary:
      db = "main"
    else:
      db = "diff"
    ea = str(int(item[1], 16))
    sql = "select prototype, pseudocode, name from %s.functions where address = ?"
    sql = sql % db
    cur.execute(sql, (str(ea), ))
    row = cur.fetchone()
    if row is None or row["prototype"] is None or row["pseudocode"] is None:
      Warning("Sorry, there is no pseudo-code available for the selected function.")
    else:
      fmt = HtmlFormatter()
      fmt.noclasses = True
      fmt.linenos = True
      func = "%s\n%s" % (row["prototype"], row["pseudocode"])
      src = highlight(func, CppLexer(), fmt)
      title = "Pseudo-code for %s" % row["name"]
      cdiffer = CHtmlViewer()
      cdiffer.Show(src, title)
    cur.close()
logbook.py 文件源码 项目:neuralmonkey 作者: ufal 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_experiment(path):
    logdir = APP.config['logdir']
    complete_path = os.path.join(logdir, path)
    if os.path.isfile(complete_path):
        file_content = get_file(complete_path)
        if path.endswith(".log"):
            result = ansiconv.to_html(html.escape(file_content))
        elif path.endswith(".ini"):
            lexer = IniLexer()
            formatter = HtmlFormatter(linenos=True)
            result = highlight(file_content, lexer, formatter)
        else:
            result = "Unknown file type: '{}'.".format(complete_path)
    else:
        result = "File '{}' does not exist.".format(complete_path)
    return Response(result, mimetype='text/html', status=200)
logbook.py 文件源码 项目:neuralmonkey 作者: ufal 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get_experiment(path):
    logdir = APP.config['logdir']
    complete_path = os.path.join(logdir, path)
    if os.path.isfile(complete_path):
        file_content = get_file(complete_path)
        if path.endswith(".log"):
            result = ansiconv.to_html(html.escape(file_content))
        elif path.endswith(".ini"):
            lexer = IniLexer()
            formatter = HtmlFormatter(linenos=True)
            result = highlight(file_content, lexer, formatter)
        else:
            result = "Unknown file type: '{}'.".format(complete_path)
    else:
        result = "File '{}' does not exist.".format(complete_path)
    return Response(result, mimetype='text/html', status=200)
logbook.py 文件源码 项目:neuralmonkey 作者: ufal 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_experiment(path):
    logdir = APP.config['logdir']
    complete_path = os.path.join(logdir, path)
    if os.path.isfile(complete_path):
        file_content = get_file(complete_path)
        if path.endswith(".log"):
            result = ansiconv.to_html(html.escape(file_content))
        elif path.endswith(".ini"):
            lexer = IniLexer()
            formatter = HtmlFormatter(linenos=True)
            result = highlight(file_content, lexer, formatter)
        else:
            result = "Unknown file type: '{}'.".format(complete_path)
    else:
        result = "File '{}' does not exist.".format(complete_path)
    return Response(result, mimetype='text/html', status=200)
myrenderer.py 文件源码 项目:yafblog 作者: jifegg 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def block_code(self, text, lang):
        linenos = inlinestyles = False
        if not lang:
            text = text.strip()
            return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)

        try:
            lexer = get_lexer_by_name(lang, stripall=True)
            formatter = HtmlFormatter(
                noclasses=inlinestyles, linenos=linenos, cssclass='codehilite'
            )
            code = highlight(text, lexer, formatter)
            if linenos:
                return '<div class="highlight-wrapper">%s</div>\n' % code
            return '<div class="doc doc-code">%s</div>%s' % (lang.upper(), code)
        except:
            return '<pre class="%s"><code>%s</code></pre>\n' % (
                lang, mistune.escape(text)
            )
views.py 文件源码 项目:airflow 作者: apache-airflow 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def code(self):
        dag_id = request.args.get('dag_id')
        dag = dagbag.get_dag(dag_id)
        title = dag_id
        try:
            m = importlib.import_module(dag.module_name)
            code = inspect.getsource(m)
            html_code = highlight(
                code, lexers.PythonLexer(), HtmlFormatter(linenos=True))
        except IOError as e:
            html_code = str(e)

        return self.render(
            'airflow/dag_code.html', html_code=html_code, dag=dag, title=title,
            root=request.args.get('root'),
            demo_mode=conf.getboolean('webserver', 'demo_mode'))
reader.py 文件源码 项目:pelican-frontmark 作者: noirbizarre 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def code_block(self, node, entering):
        '''Output Pygments if required else use default html5 output'''
        if self.use_pygments:
            self.cr()
            info_words = node.info.split() if node.info else []

            if len(info_words) > 0 and len(info_words[0]) > 0:
                try:
                    lexer = get_lexer_by_name(info_words[0])
                except ValueError:
                    # no lexer found - use the text one instead of an exception
                    lexer = TextLexer()
            else:
                lexer = TextLexer()

            formatter = HtmlFormatter(**self.pygments_options)
            parsed = highlight(node.literal, lexer, formatter)
            self.lit(parsed)
            self.cr()
        else:
            super().code_block(node, entering)
external.py 文件源码 项目:pyabc 作者: neuralyzer 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def display_source_ipython(self):
        """
        Convenience method to print the loaded source file
        as syntax highlighted HTML within IPython.
        """
        from pygments import highlight
        from pygments.lexers import SLexer

        from pygments.formatters import HtmlFormatter
        import IPython.display as display

        with open(self.source_file) as f:
            code = f.read()

        formatter = HtmlFormatter()
        return display.HTML('<style type="text/css">{}</style>{}'.format(
            formatter.get_style_defs('.highlight'),
            highlight(code, SLexer(), formatter)))
utils.py 文件源码 项目:chaquopy 作者: chaquo 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def view_source(context, web_view, filename):
    from base64 import b64encode
    from java.io import BufferedReader, InputStreamReader
    from pygments import highlight
    from pygments.formatters import HtmlFormatter
    from pygments.lexers import get_lexer_for_filename

    stream = context.getAssets().open(join(ASSET_SOURCE_DIR, filename))
    reader = BufferedReader(InputStreamReader(stream))
    text = "\n".join(iter(reader.readLine, None))

    formatter = HtmlFormatter()
    body = highlight(text, get_lexer_for_filename(filename), formatter)
    html = ("<html><head><style>{}\n{}</style></head><body>{}</body></html>"
            .format(formatter.get_style_defs(), EXTRA_CSS, body)).encode()
    web_view.loadData(b64encode(html).decode(), "text/html", "base64")
operators.py 文件源码 项目:django-elasticsearch-app 作者: bsab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def data_prettified(instance):
    """Function to display pretty version of our data"""

    # Convert the data to sorted, indented JSON
    response = json.dumps(instance, sort_keys=True, indent=2)

    # Truncate the data. Alter as needed
    #response = response[:5000]

    # Get the Pygments formatter
    formatter = HtmlFormatter(style='colorful')

    # Highlight the data
    response = highlight(response, JsonLexer(), formatter)

    # Get the stylesheet
    style = "<style>" + formatter.get_style_defs() + "</style><br>"

    # Safe the output
    return mark_safe(style + response)
model.py 文件源码 项目:sardana 作者: sardana-org 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def toolTip(self, index):
        if index.column() > 0:
            return self.data(index)
        obj = self.itemData()
        if hasattr(obj, "exc_info") and obj.exc_info is not None:
            html_orig = '<html><head><style type="text/css">{style}' \
                        '</style></head><body>'
            formatter, style = None, ""
            if pygments is not None:
                formatter = HtmlFormatter()
                style = formatter.get_style_defs()
            txt = html_orig.format(style=style)
            if formatter is None:
                txt += "<pre>%s</pre>" % obj.exc_info
            else:
                txt += highlight(obj.exc_info, PythonTracebackLexer(),
                                 formatter)
            txt += "</body></html>"
        else:
            txt = "{0} {1}".format(getElementTypeToolTip(obj.type), obj.name)
        return txt
filters.py 文件源码 项目:mblog 作者: moling3650 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def block_code(self, code, lang):
        guess = 'python3'
        if code.lstrip().startswith('<?php'):
            guess = 'php'
        elif code.lstrip().startswith(('<', '{%')):
            guess = 'html+jinja'
        elif code.lstrip().startswith(('function', 'var', '$')):
            guess = 'javascript'

        lexer = get_lexer_by_name(lang or guess, stripall=True)
        return highlight(code, lexer, HtmlFormatter())

# ???????md?????????????????????????
views.py 文件源码 项目:PrivacyScore 作者: PrivacyScore 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def site_result_json(request: HttpRequest, site_id: int) -> HttpResponse:
    site = get_object_or_404(Site.objects.annotate_most_recent_scan_result(), pk=site_id)
    scan_result = site.last_scan__result if site.last_scan__result else {}
    if 'raw' in request.GET:
        return JsonResponse(scan_result)
    code = json.dumps(scan_result, indent=2)
    highlighted_code = mark_safe(highlight(code, JsonLexer(), HtmlFormatter()))
    return render(request, 'frontend/site_result_json.html', {
        'site': site,
        'highlighted_code': highlighted_code
    })
pygmentize.py 文件源码 项目:healthchecks_asgards 作者: andela 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _process(name, lexer):
    from pygments import highlight
    from pygments.formatters import HtmlFormatter
    source = open("templates/front/snippets/%s.txt" % name).read()
    processed = highlight(source, lexer, HtmlFormatter())
    processed = processed.replace("PING_URL", "{{ ping_url }}")
    processed = processed.replace("SITE_ROOT", "{{ SITE_ROOT }}")
    processed = processed.replace("PING_ENDPOINT", "{{ PING_ENDPOINT }}")
    with open("templates/front/snippets/%s.html" % name, "w") as out:
        out.write(processed)
markdown_simple.py 文件源码 项目:wdom 作者: miyakogi 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def blockcode(self, text, lang):
        if not lang:
            return '\n<pre><code>{}</code></pre>\n'.format(text.strip())
        lexer = get_lexer_by_name(lang)
        formatter = HtmlFormatter()
        return highlight(text, lexer, formatter)
markdown_simple.py 文件源码 项目:wdom 作者: miyakogi 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def set_style(self, style: str):
        self.css.innerHTML = HtmlFormatter(style=style).get_style_defs()
markup.py 文件源码 项目:pyt 作者: python-security 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def block_code(self, code, lang):
        if not lang:
            return '\n<pre><code>%s</code></pre>\n' % \
                mistune.escape(code)
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = HtmlFormatter()
        return highlight(code, lexer, formatter)
plugin.py 文件源码 项目:flake8-html 作者: lordmauve 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _format_source(self, source):
        formatter = HtmlFormatter(nowrap=True)
        html = highlight(source, PythonLexer(), formatter)
        return {
            'html_lines': [Markup(l) for l in html.splitlines()],
            'css': formatter.get_style_defs()
        }
plugin.py 文件源码 项目:flake8-html 作者: lordmauve 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def write_styles(self):
        """Write the stylesheet."""
        formatter = HtmlFormatter(nowrap=True)
        tmpl = jinja2_env.get_template('styles.css')

        rendered = tmpl.render(
            pygments_css=formatter.get_style_defs()
        )

        stylesheet = os.path.join(self.outdir, 'styles.css')
        with codecs.open(stylesheet, 'w', encoding='utf8') as f:
            f.write(rendered)
gen.py 文件源码 项目:gmhp 作者: anqurvanillapy 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def run(self):
        """Render templates"""
        ifn = self.ifn
        ofn = self.ofn
        css = self.load_theme(self.theme)
        fonts = self.load_fonts()
        tmplenv = Environment(loader=FileSystemLoader(self.tmplpath))
        slide_tmpl = tmplenv.get_template('index.tmpl')

        if not os.path.splitext(ifn)[1] in self.mdexts:
            raise IOError("invalid Markdown extension")

        with codecs.open(ifn, 'r', encoding='utf-8') as filehandle:
            content = markdown(filehandle.read(),
                               extensions=['markdown.extensions.fenced_code',
                                           'markdown.extensions.tables',
                                           'markdown.extensions.codehilite'])
        hlcss = HtmlFormatter().get_style_defs('.codehilite')
        content = content.split('<hr />')
        title = '{0} ({1})'.format(os.path.splitext(ifn)[0],
                                   datetime.now().strftime('%B %d, %Y'))
        buf = slide_tmpl.render(title=title,
                                css=css,
                                hlcss=hlcss,
                                content=enumerate(content),
                                fonts=fonts)
        with codecs.open(ofn, 'w', encoding='utf-8',
                         errors='xmlcharrefreplace') as filehandle:
            filehandle.write(buf)
compat.py 文件源码 项目:sdining 作者: Lurance 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
compat.py 文件源码 项目:sdining 作者: Lurance 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def pygments_css(style):
        formatter = HtmlFormatter(style=style)
        return formatter.get_style_defs('.highlight')
server.py 文件源码 项目:paste.se 作者: wanders 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get(self):
        if (self.request.host.split(":")[0] == pasteconfig.BASE_DOMAIN or
            self.request.host.split(".")[0] == "new"):
            uname = self.get_cookie("username", "")
            self.render("templates/main.html",
                        username=uname,
                        default_lang=pasteconfig.DEFAULT_LANG,
                        langs=OK_LANGS)
            return

        try:
            user, desc, lang, paste = self._get_paste(["user",
                                                       "description",
                                                       "lang",
                                                       "paste"])
        except KeyError:
            self.clear()
            self.set_status(404)
            self.finish("<html><body>Not found</body></html>")
            return

        lexer = pygments.lexers.get_lexer_by_name(lang)
        formatter = HtmlFormatter(linenos=True, cssclass="source")
        paste = stripctlchars(highlight(paste, lexer, formatter))
        css = formatter.get_style_defs(arg='')

        self.render("templates/paste.html", css=css, user=user, desc=desc, paste=paste)
markdown.py 文件源码 项目:hacksoft.io 作者: HackSoftware 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def blockcode(self, text, lang):
        try:
            lexer = get_lexer_by_name(lang, stripall=True)
        except ClassNotFound:
            lexer = None

        if lexer:
            formatter = HtmlFormatter(noclasses=True)
            return highlight(text, lexer, formatter)
        # default
        return '\n<pre><code>{}</code></pre>\n'.format(
                            h.escape_html(text.strip()))
oinspect.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def pylight(code):
    return highlight(code, PythonLexer(), HtmlFormatter(noclasses=True))

# builtin docstrings to ignore
views.py 文件源码 项目:incubator-airflow-old 作者: apache 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def pygment_html_render(s, lexer=lexers.TextLexer):
    return highlight(
        s,
        lexer(),
        HtmlFormatter(linenos=True),
    )


问题


面经


文章

微信
公众号

扫码关注公众号