rst_directive.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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-2015 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.lexers import get_lexer_by_name, TextLexer
  31. from pygments.formatters import HtmlFormatter
  32. class Pygments(Directive):
  33. """ Source code syntax hightlighting.
  34. """
  35. required_arguments = 1
  36. optional_arguments = 1
  37. final_argument_whitespace = True
  38. has_content = True
  39. def run(self):
  40. self.assert_has_content()
  41. try:
  42. if self.arguments[1] == 'linenos':
  43. linenos = 'table'
  44. else:
  45. linenos = False
  46. except IndexError as exc:
  47. linenos = False
  48. try:
  49. lexer = get_lexer_by_name(self.arguments[0])
  50. except ValueError:
  51. # no lexer found - use the text one instead of an exception
  52. lexer = TextLexer()
  53. formatter = HtmlFormatter(
  54. noclasses = False,
  55. cssclass = 'codehilite',
  56. linenos = linenos,
  57. linenospecial = 5,
  58. lineanchors = 'lineno',
  59. anchorlinenos = True)
  60. # parse the code, which shall be highlighted
  61. parsed = highlight(u'\n'.join(self.content), lexer, formatter)
  62. return [nodes.raw('', parsed, format='html')]
  63. directives.register_directive('sourcecode', Pygments)