summaryrefslogtreecommitdiff
path: root/creole/shared/example_macros.py
blob: 635e92062c427df87211237e8782ab6fa99fd3bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
    Creole macros
    ~~~~~~~~~~~~~

    Note: all mecro functions must return unicode!

    :copyleft: 2008-2014 by python-creole team, see AUTHORS for more details.
    :license: GNU GPL v3 or above, see LICENSE for more details.

"""


from xml.sax.saxutils import escape

from creole.shared.utils import get_pygments_formatter, get_pygments_lexer


try:
    from pygments import highlight
    PYGMENTS = True
except ImportError:
    PYGMENTS = False


def html(text):
    """
    Macro tag <<html>>...<</html>>
    Pass-trought for html code (or other stuff)
    """
    return text


def pre(text):
    """
    Macro tag <<pre>>...<</pre>>.
    Put text between html pre tag.
    """
    return f'<pre>{escape(text)}</pre>'


def code(ext, text):
    """
    Macro tag <<code ext=".some_extension">>...<</code>>
    If pygments is present, highlight the text according to the extension.
    """
    if not PYGMENTS:
        return pre(text)

    try:
        source_type = ''
        if '.' in ext:
            source_type = ext.strip().split('.')[1]
        else:
            source_type = ext.strip()
    except IndexError:
        source_type = ''

    lexer = get_pygments_lexer(source_type, code)
    formatter = get_pygments_formatter()

    try:
        highlighted_text = highlight(text, lexer, formatter).decode('utf-8')
    except BaseException:
        highlighted_text = pre(text)
    finally:
        return highlighted_text.replace('\n', '<br />\n')