From 2c3cf5179f16e8303ece57e3dbb191a46f3dcb85 Mon Sep 17 00:00:00 2001 From: Sébastien Dailly Date: Sat, 4 Oct 2014 16:59:06 +0200 Subject: Moved resources to the blog site --- content/resources/rstodt/rst2html-pygments.py | 55 +++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 content/resources/rstodt/rst2html-pygments.py (limited to 'content/resources/rstodt/rst2html-pygments.py') diff --git a/content/resources/rstodt/rst2html-pygments.py b/content/resources/rstodt/rst2html-pygments.py new file mode 100644 index 0000000..7e2a826 --- /dev/null +++ b/content/resources/rstodt/rst2html-pygments.py @@ -0,0 +1,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') + -- cgit v1.2.3