A fork of hyde, the static site generation. Some patches will be pushed upstream.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

86 lines
2.5 KiB

  1. # -*- coding: utf-8 -*-
  2. """
  3. The Pygments reStructuredText directive
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. This fragment is a Docutils_ 0.5 directive that renders source code
  6. (to HTML only, currently) via Pygments.
  7. To use it, adjust the options below and copy the code into a module
  8. that you import on initialization. The code then automatically
  9. registers a ``sourcecode`` directive that you can use instead of
  10. normal code blocks like this::
  11. .. sourcecode:: python
  12. My code goes here.
  13. If you want to have different code styles, e.g. one with line numbers
  14. and one without, add formatters with their names in the VARIANTS dict
  15. below. You can invoke them instead of the DEFAULT one by using a
  16. directive option::
  17. .. sourcecode:: python
  18. :linenos:
  19. My code goes here.
  20. Look at the `directive documentation`_ to get all the gory details.
  21. .. _Docutils: http://docutils.sf.net/
  22. .. _directive documentation:
  23. http://docutils.sourceforge.net/docs/howto/rst-directives.html
  24. :copyright: Copyright 2006-2011 by the Pygments team, see AUTHORS.
  25. :license: BSD, see LICENSE for details.
  26. """
  27. # Options
  28. # ~~~~~~~
  29. # Set to True if you want inline CSS styles instead of classes
  30. INLINESTYLES = False
  31. from pygments.formatters import HtmlFormatter
  32. # The default formatter
  33. DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)
  34. # Add name -> formatter pairs for every variant you want to use
  35. VARIANTS = {
  36. 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
  37. }
  38. from docutils import nodes
  39. from docutils.parsers.rst import directives, Directive
  40. from pygments import highlight
  41. from pygments.lexers import get_lexer_by_name, TextLexer
  42. class Pygments(Directive):
  43. """ Source code syntax hightlighting.
  44. """
  45. required_arguments = 1
  46. optional_arguments = 0
  47. final_argument_whitespace = True
  48. option_spec = dict([(key, directives.flag) for key in VARIANTS])
  49. has_content = True
  50. def run(self):
  51. self.assert_has_content()
  52. try:
  53. lexer = get_lexer_by_name(self.arguments[0])
  54. except ValueError:
  55. # no lexer found - use the text one instead of an exception
  56. lexer = TextLexer()
  57. # take an arbitrary option if more than one is given
  58. formatter = self.options and VARIANTS[
  59. self.options.keys()[0]] or DEFAULT
  60. parsed = highlight(u'\n'.join(self.content), lexer, formatter)
  61. return [nodes.raw('', parsed, format='html')]
  62. directives.register_directive('sourcecode', Pygments)