rest2html.py 1.8 KB

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