How to use the pygments.highlight function in Pygments

To help you get started, we’ve selected a few Pygments examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gleitz / howdoi / howdoi / howdoi.py View on Github external
# or the query arguments
    for keyword in args['query'].split() + args['tags']:
        try:
            lexer = get_lexer_by_name(keyword)
            break
        except ClassNotFound:
            pass

    # no lexer found above, use the guesser
    if not lexer:
        try:
            lexer = guess_lexer(code)
        except ClassNotFound:
            return code

    return highlight(code,
                     lexer,
                     TerminalFormatter(bg='dark'))
github healthchecks / healthchecks / hc / front / management / commands / pygmentize.py View on Github external
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)
github levskaya / OW / jinja_extensions / jinja.py View on Github external
except ImportError:
        logger.error(u"pygments library is required to"
                        " use syntax highlighting tags.")
        raise TemplateError("Cannot load pygments")

    pyg = (lexers.get_lexer_by_name(lexer)
                if lexer else
                    lexers.guess_lexer(value))
    settings = {}
    if hasattr(env.config, 'syntax'):
        settings = getattr(env.config.syntax,
                            'options',
                            Expando({})).to_dict()

    formatter = formatters.HtmlFormatter(**settings)
    code = pygments.highlight(value, pyg, formatter)
    code = code.replace('\n\n', '\n&nbsp;\n').replace('\n', '<br>')
    caption = filename if filename else pyg.name
    if hasattr(env.config, 'syntax'):
        if not getattr(env.config.syntax, 'use_figure', True):
            return Markup(code)
    return Markup(
            '<div class="codebox"><figure class="code">%s<figcaption>%s</figcaption></figure></div>\n\n'
                        % (code, caption))
github springmeyer / quantumnik / quantumnik.py View on Github external
os.close(handle)
                mapnik.save_map(m,str(mapfile))
                xml = open(mapfile,'rb').read()
        e = self.canvas.extent()
        bbox = '%s %s %s %s' % (e.xMinimum(),e.yMinimum(),
                                e.xMaximum(),e.yMaximum())
        cmd = '\n\n' % (self.canvas.width(), self.canvas.height(), bbox)
        try:
            if self.mapnik_map:
                cmd += '\n' % (self.mapnik_map.scale_denominator())
        except:
            pass

        code = xml + cmd
        if HIGHLIGHTING:
            highlighted = highlight(code, XmlLexer(), HtmlFormatter(linenos=False, nowrap=False, full=True))
            self.dock_window.textEdit.setHtml(highlighted)
        else:
            self.dock_window.textEdit.setText(xml + cmd)
github honza / socrates / socrates / processors.py View on Github external
def highlight_code(self, language, code):
            return highlight(code, get_lexer_by_name(language),
                             HtmlFormatter())
github spiffytech / MobileBlur / gluon / contrib / markdown / markdown2.py View on Github external
class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
            def _wrap_code(self, inner):
                """A function for use in a Pygments Formatter which
                wraps in <code> tags.
                """
                yield 0, "<code>"
                for tup in inner:
                    yield tup
                yield 0, "</code>"

            def wrap(self, source, outfile):
                """Return the source with a code, pre, and div."""
                return self._wrap_div(self._wrap_pre(self._wrap_code(source)))

        formatter = HtmlCodeFormatter(cssclass="codehilite", **formatter_opts)
        return pygments.highlight(codeblock, lexer, formatter)
</code>
github aliparsai / LittleDarwin / littledarwin / MutantDensityGenerator.py View on Github external
def highlightCode(self, javaCode, lineGroups):
        """
        Generates HTML highlights
        """
        javaLexer = JavaLexer()
        formatter = DensityFormatter(linenos='inline', highlight_groups=lineGroups)

        return highlight(javaCode, javaLexer, formatter)
github mike820324 / microProxy / microproxy / viewer / formatter.py View on Github external
def colorize(lexer_name, raw_text):  # pragma: no cover
    lexer = get_lexer_by_name(lexer_name, stripall=True)
    formatter = Terminal256Formatter()
    return highlight(raw_text, lexer, formatter)
github taurus-org / taurus / lib / taurus / qt / qtgui / panel / taurusmessagepanel.py View on Github external
msgbox.setDetailedHtml(msg)

        html_orig = '<style type="text/css">{style}</style>' \
                    ''
        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 += ""
        msgbox.setOriginHtml(html)