PageRenderTime 31ms CodeModel.GetById 23ms app.highlight 7ms RepoModel.GetById 0ms app.codeStats 1ms

/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
 6    This fragment is a Docutils_ 0.4 directive that renders source code
 7    (to HTML only, currently) via Pygments.
 8
 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::
13
14        .. sourcecode:: python
15
16            My code goes here.
17
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::
22
23        .. sourcecode:: python
24            :linenos:
25
26            My code goes here.
27
28    Look at the `directive documentation`_ to get all the gory details.
29
30    .. _Docutils: http://docutils.sf.net/
31    .. _directive documentation:
32       http://docutils.sourceforge.net/docs/howto/rst-directives.html
33
34    :copyright: Copyright 2006-2009 by the Pygments team, see AUTHORS.
35    :license: BSD, see LICENSE for details.
36"""
37
38# Options
39# ~~~~~~~
40
41# Set to True if you want inline CSS styles instead of classes
42INLINESTYLES = False
43
44from pygments.formatters import HtmlFormatter
45
46# The default formatter
47DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)
48
49# Add name -> formatter pairs for every variant you want to use
50VARIANTS = {
51    # 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
52}
53
54
55from docutils import nodes
56from docutils.parsers.rst import directives
57
58from pygments import highlight
59from pygments.lexers import get_lexer_by_name, TextLexer
60
61def 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')]
72
73pygments_directive.arguments = (1, 0, 1)
74pygments_directive.content = 1
75pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])
76
77directives.register_directive('sourcecode', pygments_directive)