Python pygments.formatters.html 模块,HtmlFormatter() 实例源码

我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用pygments.formatters.html.HtmlFormatter()

项目:quokka_ng    作者:rochacbruno    | 项目源码 | 文件源码
def block_code(text, lang, inlinestyles=False, linenos=False):
    if not lang:
        text = text.strip()
        return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)

    try:
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = html.HtmlFormatter(
            noclasses=inlinestyles, linenos=linenos
        )
        code = highlight(text, lexer, formatter)
        if linenos:
            return '<div class="highlight-wrapper">%s</div>\n' % code
        return code
    except BaseException:
        return '<pre class="%s"><code>%s</code></pre>\n' % (
            lang, mistune.escape(text)
        )
项目:DualisWatcher    作者:LucaVazz    | 项目源码 | 文件源码
def _format_code(html_code):
    # syntax highlighting:
    code_highlighted = highlight(html_code, HtmlLexer(), HtmlFormatter(style='monokai', noclasses=True))
    # add formatting for diff-markers:
    common_diff_style = ' margin-right: 3px; padding-right: 7px; padding-left: 7px;'
    code_formatted = code_highlighted \
        .replace('[-', '<span style="background: #71332c;' + common_diff_style + '">') \
        .replace('-]', '</span>') \
        .replace('{+', '<span style="background: #2e4d28;' + common_diff_style + '">') \
        .replace('+}', '</span>')

    # wrap in general layout:
    code_wrapped = '<div style="color: #efefef; margin: 3px; margin-left: 17px;line-height: 150%%;">%s</div>'\
                   %(code_formatted)

    return code_wrapped
项目:drf-swagger-missing    作者:tovmeod    | 项目源码 | 文件源码
def save(self, *args, **kwargs):
        """
        Use the `pygments` library to create a highlighted HTML
        representation of the code snippet.
        """
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and 'table' or False
        options = self.title and {'title': self.title} or {}
        formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                  full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super(Snippet, self).save(*args, **kwargs)

        # limit the number of instances retained
        snippets = Snippet.objects.all()
        if len(snippets) > 100:
            snippets[0].delete()
项目:DjangoBlog    作者:liangliangyy    | 项目源码 | 文件源码
def block_code(text, lang, inlinestyles=False, linenos=False):
    if not lang:
        text = text.strip()
        return u'<pre><code>%s</code></pre>\n' % mistune.escape(text)

    try:
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = html.HtmlFormatter(
            noclasses=inlinestyles, linenos=linenos
        )
        code = highlight(text, lexer, formatter)
        if linenos:
            return '<div class="highlight">%s</div>\n' % code
        return code
    except:
        return '<pre class="%s"><code>%s</code></pre>\n' % (
            lang, mistune.escape(text)
        )
项目:morpheus    作者:tutorcruncher    | 项目源码 | 文件源码
def get_context(self, morpheus_api):
        method = self.request.match_info['method']
        message_id = self.request.match_info['id']
        url = self.app.router['user-messages'].url_for(method=method).with_query({'message_id': message_id})

        r = await morpheus_api.get(url)
        data = await r.json()
        data = json.dumps(data, indent=2)
        data = re.sub('14\d{8,11}', self.replace_data, data)

        preview_path = morpheus_api.modify_url(self.app.router['user-preview'].url_for(method=method, id=message_id))
        deets_path = morpheus_api.modify_url(self.app.router['user-message-get'].url_for(method=method, id=message_id))
        return dict(
            sub_heading=f'Message {message_id}',
            preview_url=self.full_url(preview_path),
            details_url=self.full_url(deets_path),
            json_display=highlight(data, JsonLexer(), HtmlFormatter()),
            form_action=self.app.router['admin-list'].url_for(),
        )
项目:fomod-designer    作者:GandaG    | 项目源码 | 文件源码
def run(self):
        while True:
            # wait for next element
            element = self.queue.get()

            if element is None or element.tag is Comment:
                self.return_signal.emit("")
                continue

            element = XML(tostring(element))

            # process the element
            deannotate(element, cleanup_namespaces=True)
            code = tostring(element, encoding="Unicode", pretty_print=True, xml_declaration=False)
            self.return_signal.emit(highlight(code, XmlLexer(), HtmlFormatter(
                noclasses=True, style="autumn", linenos="table"
            )))
项目:blog-a    作者:richardchien    | 项目源码 | 文件源码
def blockcode(self, text, lang):
        if not lang:
            return '\n<pre><code>{}</code></pre>\n'.format(houdini.escape_html(text.strip()))

        lexer = get_lexer_by_name(lang)
        formatter = HtmlFormatter()
        return highlight(text, lexer, formatter)
项目:SiteFab    作者:ebursztein    | 项目源码 | 文件源码
def __init__(self, config, site):
        """ Initialize a new parser for a given type of parsing

        Args:
            confi (obj_dict): the parser config. It is explicitly defined to allows  different conf
            site (dictobj): sitefab instantiated object        
        Return:
            None

        note: one parser is instanciated by thread. potentially batching more than one post per thread might help with performance.

        """

        # verify that the config exist
        self.config = config
        self.site = site

        # NOTE: Might seems weird to do this but templates is what allows to have different rendering for each plugins.
        # So we keep it explict in the code as this got messed up countless time :(
        self.templates = self.config.templates 

        # NOTE: This part must be done at parsing time to let plugins time to be loaded/executed.
        # Replacing standard template with the one injected by plugins
        for elt, template in self.config.injected_html_templates.items():
            self.templates[elt] = template

        # templates are not compiled yet, they will be when parsing will be called the first time 
        self.jinja2 = None 

        # markdown parser
        self.renderer = HTMLRenderer()
        self.md_parser = mistune.Markdown(renderer=self.renderer)

        #code higlighterr
        if self.config.code_display_line_num:
            linenos = 'table'
        else:
            linenos = False

        self.code_formatter = html.HtmlFormatter(style=self.config.code_highlighting_theme, nobackground=False, linenos=linenos)
项目:akamatsu    作者:rmed    | 项目源码 | 文件源码
def blockcode(self, text, lang):
        if not lang:
            return '\n<pre><code>{}</code></pre>\n'.format(text.strip())

        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = HtmlFormatter()

        return highlight(code=text, lexer=lexer, formatter=formatter)
项目:CustomContextMenu    作者:bigsinger    | 项目源码 | 文件源码
def block_code(self, code, lang):
        lang = 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 = html.HtmlFormatter()
        return highlight(code, lexer, formatter)

# renderer = HighlightRenderer()
# markdown = mistune.Markdown(renderer=renderer)
# print(markdown('```python\nassert 1 == 1\n```'))
项目:Code_python    作者:RoJoHub    | 项目源码 | 文件源码
def save(self, *args, **kwargs):
        """
        Use the `pygments` library to create a highlighted HTML
        representation of the code snippet.
        """
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and 'table' or False
        options = self.title and {'title': self.title} or {}
        formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                  full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super(Snippet, self).save(*args, **kwargs)
项目:FBlog-python3-webapp    作者:fuyangzhen    | 项目源码 | 文件源码
def block_code(self, code, lang):
        guess = 'python3'
        if code.lstrip().startswith('<?php'):
            guess = 'php'
        elif code.lstrip().startswith('<'):
            guess = 'html'
        elif code.lstrip().startswith(('function', 'var', '$')):
            guess = 'javascript'

        lexer = get_lexer_by_name(lang or guess, stripall=True)
        formatter = html.HtmlFormatter()
        return highlight(code, lexer, formatter)
项目:PPaste    作者:Thooms    | 项目源码 | 文件源码
def highlight_paste(paste, hl_lines):
    '''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', hl_lines=hl_lines)
    return (
        highlight(paste.content, lexer, formatter),
        formatter.get_style_defs('.source')
    )
项目:dystic    作者:oxalorg    | 项目源码 | 文件源码
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 = html.HtmlFormatter()
        return highlight(code, lexer, formatter)
项目:nat64check    作者:sjm-steffann    | 项目源码 | 文件源码
def admin_v4only_data(self, measurement):
        response = yaml.dump(measurement.v4only_data)

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

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

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

        # Safe the output
        return mark_safe(style + response)
项目:nat64check    作者:sjm-steffann    | 项目源码 | 文件源码
def admin_v6only_data(self, measurement):
        response = yaml.dump(measurement.v6only_data)

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

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

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

        # Safe the output
        return mark_safe(style + response)
项目:nat64check    作者:sjm-steffann    | 项目源码 | 文件源码
def admin_nat64_data(self, measurement):
        response = yaml.dump(measurement.nat64_data)

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

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

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

        # Safe the output
        return mark_safe(style + response)
项目:IntelligentWord    作者:DannyLee1991    | 项目源码 | 文件源码
def save(self, *args, **kwargs):
        """
        Use the `pygments` library to create a highlighted HTML
        representation of the code snippet.
        """
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and 'table' or False
        options = self.title and {'title': self.title} or {}
        formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                  full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super(Snippet, self).save(*args, **kwargs)
项目:Pastebin    作者:sarthakagarwal18    | 项目源码 | 文件源码
def save(self, *args, **kwargs):
        # Use the `pygments` library to create a highlighted HTML representation of the code snippet.
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and 'table' or False
        options = self.title and {'title': self.title} or {}
        formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                  full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super(Snippet, self).save(*args, **kwargs)
项目:docker-enforcer    作者:piontec    | 项目源码 | 文件源码
def python_file_to_json(req, file_name: str):
    try:
        with open(file_name, "r") as file:
            data = file.read()
    except IOError as e:
        data = "Error: {}".format(e.strerror)

    if req.accept_mimetypes.accept_html:
        html = highlight(data, Python3Lexer(), HtmlFormatter(full=True, linenos='table'))
        return Response(html, content_type="text/html")
    json_res = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
    return Response(json_res, content_type="application/json")
项目:docker-enforcer    作者:piontec    | 项目源码 | 文件源码
def to_formatted_json(data):
    if request.accept_mimetypes.accept_html:
        html = highlight(data, JsonLexer(), HtmlFormatter(full=True, linenos='table'))
        return Response(html, content_type="text/html")
    return Response(data, content_type="application/json")
项目:eoj3    作者:ultmaster    | 项目源码 | 文件源码
def transform_code_to_html(code, lang):
    return highlight(code, get_lexer_by_name(dict(LANG_REGULAR_NAME).get(lang, lang)), HtmlFormatter())
项目:eoj3    作者:ultmaster    | 项目源码 | 文件源码
def get(self, request, submission_id):
        submission = OldSubmission.objects.get(pk=submission_id)
        return HttpResponse(json.dumps({'code': highlight(submission.code, get_lexer_by_name(submission.lang), HtmlFormatter())}))
项目:paste    作者:NextFloor    | 项目源码 | 文件源码
def view(slug):
    paste = Paste.get_or_404(slug)
    if paste.password:
        form = PasswordForm()
        if form.validate_on_submit():
            if not paste.verify_password(form.password.data):
                flash('????? ???? ????.', 'error')
                return render_template('password.html', form=form)
        else:
            form.flash_errors()
            return render_template('password.html', form=form)

    viewed = session.setdefault('viewed', [])
    if paste.slug not in viewed:
        viewed.append(paste.slug)
        session.permanent = True
        session.modified = True
        paste.view_count += 1
        db.session.add(paste)
        db.session.commit()

    lexer = get_lexer_by_name(paste.lexer)
    formatter = HtmlFormatter(
        linenos=True,
        linespans='line',
        lineanchors='line',
        anchorlinenos=True,
    )

    return render_template(
        'view.html',
        styles=formatter.get_style_defs(),
        highlighted_source=highlight(paste.source, lexer, formatter),
        lexer=lexer,
        paste=paste,
    )