cubicweb/misc/source_highlight.py
author Laurent Peuch <cortex@worlddomination.be>
Wed, 31 Jul 2019 04:16:20 +0200
changeset 12762 f14dde905818
parent 12758 db95a417a5ec
child 12769 a61e0fe17a69
permissions -rw-r--r--
[pyramid/ctl/debugtoolbar] automatically include custom panels on -t

"""This module provide syntaxe highlight functions"""

from logilab.common.logging_ext import _colorable_terminal

try:
    from pygments import highlight as pygments_highlight
    from pygments.lexers import get_lexer_by_name
    from pygments.formatters.terminal import TerminalFormatter
    from pygments.formatters.html import HtmlFormatter
    has_pygments = True
except ImportError:
    has_pygments = False


def highlight_terminal(code, language):
    if not has_pygments:
        return code

    if not _colorable_terminal():
        return code

    return pygments_highlight(code, get_lexer_by_name(language), TerminalFormatter())


def highlight_html(code, language, linenos=False):
    if not has_pygments:
        return code

    return pygments_highlight(str(code), get_lexer_by_name(language), HtmlFormatter(wrapcode=True, linenos=linenos))


def generate_css():
    if has_pygments:
        return HtmlFormatter().get_style_defs()
    else:
        return ""