summaryrefslogtreecommitdiff
path: root/content/resources/rstodt/rst2html-pygments.py
blob: 7e2a8265ff5d984eb337e2d7d6459b38851e1550 (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
#!/usr/bin/python
# -*- coding: utf-8 -*-

from docutils.core import publish_cmdline

# Define a new directive `code-block` that uses the `pygments` source
# highlighter to render code in color. 
#

from docutils import nodes
from docutils.parsers.rst import directives, Directive
from pygments import highlight

from pygments.lexers import get_lexer_by_name, TextLexer
from pygments.formatters import HtmlFormatter

INLINESTYLES = False
pygments_formatter = HtmlFormatter()
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES,linenos="table")
VARIANTS = {}

class Pygments(Directive):
    """ Source code syntax hightlighting.
    """
    required_arguments = 1
    optional_arguments = 1
    final_argument_whitespace = True

    has_content = True
    linenos=1

    def run(self):
        dic = {}

        # On crée un dictionnaire à partir des options
        for options in self.arguments[1:]:
            clef, arg = options.split("=")
            dic[clef] = arg

        self.assert_has_content()
        try:
            lexer = get_lexer_by_name(self.arguments[0], **dic)
        except ValueError:
            # no lexer found - use the text one instead of an exception
            lexer = TextLexer()
        # take an arbitrary option if more than one is given
        formatter = self.options and VARIANTS[self.options.keys()[0]] or DEFAULT
        parsed = highlight(u'\n'.join(self.content), lexer, formatter)
        return [nodes.raw('', parsed, format='html')]


directives.register_directive('code-block', Pygments)

publish_cmdline(writer_name='html')