1 # -*- coding: utf-8 -*-
3 The Pygments reStructuredText directive
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 This fragment is a Docutils_ 0.5 directive that renders source code
7 (to HTML only, currently) via Pygments.
9 To use it, adjust the options below and copy the code into a module
10 that you import on initialization. The code then automatically
11 registers a ``sourcecode`` directive that you can use instead of
12 normal code blocks like this::
14 .. sourcecode:: python
18 If you want to have different code styles, e.g. one with line numbers
19 and one without, add formatters with their names in the VARIANTS dict
20 below. You can invoke them instead of the DEFAULT one by using a
23 .. sourcecode:: python
28 Look at the `directive documentation`_ to get all the gory details.
30 .. _Docutils: http://docutils.sf.net/
31 .. _directive documentation:
32 http://docutils.sourceforge.net/docs/howto/rst-directives.html
34 :copyright: Copyright 2006-2009 by the Pygments team, see AUTHORS.
35 :license: BSD, see LICENSE for details.
41 # Set to True if you want inline CSS styles instead of classes
45 from pygments.formatters import HtmlFormatter
47 # The default formatter
48 DEFAULT = HtmlFormatter(noclasses=INLINESTYLES, style=STYLE)
50 # Add name -> formatter pairs for every variant you want to use
52 # 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
56 from docutils import nodes
57 from docutils.parsers.rst import directives, Directive
59 from pygments import highlight
60 from pygments.lexers import get_lexer_by_name, TextLexer
62 class Pygments(Directive):
63 """ Source code syntax highlighting.
65 required_arguments = 1
66 optional_arguments = 0
67 final_argument_whitespace = True
68 option_spec = dict([(key, directives.flag) for key in VARIANTS])
72 self.assert_has_content()
74 lexer = get_lexer_by_name(self.arguments[0])
76 # no lexer found - use the text one instead of an exception
78 # take an arbitrary option if more than one is given
79 formatter = self.options and VARIANTS[self.options.keys()[0]] or DEFAULT
81 # print >>open('ui/default/pygments.css', 'w'), formatter.get_style_defs('.highlight')
82 parsed = highlight(u'\n'.join(self.content), lexer, formatter)
83 return [nodes.raw('', parsed, format='html')]
85 directives.register_directive('sourcecode', Pygments)
87 from docutils.core import publish_cmdline, default_description
89 description = ('Generates S5 (X)HTML slideshow documents from standalone '
90 'reStructuredText sources. ' + default_description)
92 publish_cmdline(writer_name='s5', description=description)