Created
September 3, 2011 16:42
-
-
Save marsam/1191442 to your computer and use it in GitHub Desktop.
rst2html.py with source-code directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
""" | |
A minimal front end to the Docutils Publisher, producing HTML. | |
Pygments: external/rst-directive.py | |
""" | |
try: | |
import locale | |
locale.setlocale(locale.LC_ALL, '') | |
except: | |
pass | |
from docutils import nodes | |
from docutils.core import publish_cmdline, default_description | |
from docutils.parsers.rst import directives, Directive | |
from pygments.formatters import HtmlFormatter | |
from pygments import highlight | |
from pygments.lexers import get_lexer_by_name, TextLexer | |
# Set to True if you want inline CSS styles instead of classes | |
INLINESTYLES = True | |
# The default formatter | |
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES) | |
# Add name -> formatter pairs for every variant you want to use | |
VARIANTS = { | |
'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True), | |
} | |
class Pygments(Directive): | |
""" Source code syntax hightlighting. | |
""" | |
required_arguments = 1 | |
optional_arguments = 0 | |
final_argument_whitespace = True | |
option_spec = dict([(key, directives.flag) for key in VARIANTS]) | |
has_content = True | |
def run(self): | |
self.assert_has_content() | |
try: | |
lexer = get_lexer_by_name(self.arguments[0]) | |
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('sourcecode', Pygments) | |
directives.register_directive('code-block', Pygments) | |
description = ('Generates (X)HTML documents from standalone reStructuredText ' | |
'sources. ' + default_description) | |
publish_cmdline(writer_name='html', description=description) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment