/hyde/lib/pygments/rst_directive.py

http://github.com/hyde/hyde · Python · 83 lines · 27 code · 11 blank · 45 comment · 5 complexity · 8bbf257c8d45381617804b411395f63c MD5 · raw file

  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. from docutils import nodes
  28. from docutils.parsers.rst import directives, Directive
  29. from pygments import highlight
  30. from pygments.formatters import HtmlFormatter
  31. from pygments.lexers import get_lexer_by_name, TextLexer
  32. # Options
  33. # ~~~~~~~
  34. # Set to True if you want inline CSS styles instead of classes
  35. INLINESTYLES = False
  36. # The default formatter
  37. DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)
  38. # Add name -> formatter pairs for every variant you want to use
  39. VARIANTS = {
  40. 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
  41. }
  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)