#!/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') 

