/shabti/templates/pyblosxom/+package+/lib/rstdirective.py_tmpl

https://bitbucket.org/gawel/shabti · Unknown · 77 lines · 56 code · 21 blank · 0 comment · 0 complexity · c2b385554c44591320914f1ed25c187e MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. """
  3. The Pygments reStructuredText directive
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. This fragment is a Docutils_ 0.4 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-2009 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
  40. from pygments import highlight
  41. from pygments.lexers import get_lexer_by_name, TextLexer
  42. def pygments_directive(name, arguments, options, content, lineno,
  43. content_offset, block_text, state, state_machine):
  44. try:
  45. lexer = get_lexer_by_name(arguments[0])
  46. except ValueError:
  47. # no lexer found - use the text one instead of an exception
  48. lexer = TextLexer()
  49. # take an arbitrary option if more than one is given
  50. formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
  51. parsed = highlight(u'\n'.join(content), lexer, formatter)
  52. return [nodes.raw('', parsed, format='html')]
  53. pygments_directive.arguments = (1, 0, 1)
  54. pygments_directive.content = 1
  55. pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])
  56. directives.register_directive('sourcecode', pygments_directive)