viff.dk

view pygments_rst.py @ 176:9e1de2a70022

Update copyright to 2010.
author Martin Geisler <mg@lazybytes.net>
date Mon, 01 Feb 2010 10:04:59 +0100
parents
children
line source
1 # -*- coding: utf-8 -*-
2 """
3 The Pygments reStructuredText directive
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 This fragment is a Docutils_ 0.4 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
16 My code goes here.
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
21 directive option::
23 .. sourcecode:: python
24 :linenos:
26 My code goes here.
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: 2007 by Georg Brandl.
35 :license: BSD, see LICENSE for more details.
36 """
38 # Options
39 # ~~~~~~~
41 # Set to True if you want inline CSS styles instead of classes
42 INLINESTYLES = False
44 from pygments.formatters import HtmlFormatter
46 # The default formatter
47 DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)
49 # Add name -> formatter pairs for every variant you want to use
50 VARIANTS = {
51 # 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
52 }
55 from docutils import nodes
56 from docutils.parsers.rst import directives
58 from pygments import highlight
59 from pygments.lexers import get_lexer_by_name, TextLexer
61 def pygments_directive(name, arguments, options, content, lineno,
62 content_offset, block_text, state, state_machine):
63 try:
64 lexer = get_lexer_by_name(arguments[0])
65 except ValueError:
66 # no lexer found - use the text one instead of an exception
67 lexer = TextLexer()
68 # take an arbitrary option if more than one is given
69 formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
70 parsed = highlight(u'\n'.join(content), lexer, formatter)
71 return [nodes.raw('', parsed, format='html')]
73 pygments_directive.arguments = (1, 0, 1)
74 pygments_directive.content = 1
75 pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])
77 directives.register_directive('sourcecode', pygments_directive)