| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
""" |
| 4 |
A minimal front end to the Docutils Publisher, producing HTML with |
| 5 |
Pygments syntax highlighting. |
| 6 |
""" |
| 7 |
|
| 8 |
# Set to True if you want inline CSS styles instead of classes |
| 9 |
INLINESTYLES = False |
| 10 |
|
| 11 |
|
| 12 |
try: |
| 13 |
import locale |
| 14 |
locale.setlocale(locale.LC_ALL, '') |
| 15 |
except Exception: |
| 16 |
pass |
| 17 |
|
| 18 |
# set up Pygments |
| 19 |
|
| 20 |
from pygments.formatters import HtmlFormatter |
| 21 |
|
| 22 |
# The default formatter |
| 23 |
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES, cssclass='syntax') |
| 24 |
|
| 25 |
# Add name -> formatter pairs for every variant you want to use |
| 26 |
VARIANTS = { |
| 27 |
# 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True), |
| 28 |
} |
| 29 |
|
| 30 |
|
| 31 |
from docutils import nodes |
| 32 |
from docutils.parsers.rst import directives |
| 33 |
|
| 34 |
from pygments import highlight |
| 35 |
from pygments.lexers import get_lexer_by_name, TextLexer |
| 36 |
|
| 37 |
def pygments_directive(name, arguments, options, content, lineno, |
| 38 |
content_offset, block_text, state, state_machine): |
| 39 |
try: |
| 40 |
lexer = get_lexer_by_name(arguments[0]) |
| 41 |
except ValueError: |
| 42 |
# no lexer found - use the text one instead of an exception |
| 43 |
lexer = TextLexer() |
| 44 |
# take an arbitrary option if more than one is given |
| 45 |
formatter = options and VARIANTS[options.keys()[0]] or DEFAULT |
| 46 |
parsed = highlight(u'\n'.join(content), lexer, formatter) |
| 47 |
return [nodes.raw('', parsed, format='html')] |
| 48 |
|
| 49 |
pygments_directive.arguments = (1, 0, 1) |
| 50 |
pygments_directive.content = 1 |
| 51 |
pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS]) |
| 52 |
|
| 53 |
directives.register_directive('sourcecode', pygments_directive) |
| 54 |
|
| 55 |
|
| 56 |
# run the generation |
| 57 |
|
| 58 |
from docutils.core import publish_cmdline, default_description |
| 59 |
|
| 60 |
description = ('Generates (X)HTML documents from standalone reStructuredText ' |
| 61 |
'sources. ' + default_description) |
| 62 |
|
| 63 |
publish_cmdline(writer_name='html', description=description) |