pylit: code cleanup in `Text2Code.__iter__`
[pylit.git] / rstdocs / features / rst2html-pygments
blobfba7da66206a0ce2d81c602c739f02e4b55f2726
1 #!/usr/bin/python
3 # Author: David Goodger, an unknown Pygments author|contributor, Guenter Milde
4 # Date: $Date: $
5 # Copyright: This module has been placed in the public domain.
7 # This is a merge of the docutils_ `rst2html` front end with an extension
8 # suggestion taken from the pygments_ documentation.
10 """
11 A front end to docutils, producing HTML with colorized code using pygments
12 """
14 try:
15 import locale
16 locale.setlocale(locale.LC_ALL, '')
17 except:
18 pass
20 from docutils.core import publish_cmdline, default_description
22 description = ('Generates (X)HTML documents from standalone reStructuredText '
23 'sources. Uses `pygments` to colorize code. '
24 'Needs an adapted stylesheet' + default_description)
26 # Define a new directive `sourcecode` that uses the `pygments` source
27 # highligther to render code in color.
29 # Code from the `pygments`_ documentation for `Using Pygments in ReST
30 # documents`_.
32 from docutils import nodes
33 from docutils.parsers.rst import directives
34 from pygments import highlight
35 from pygments.lexers import get_lexer_by_name
36 from pygments.formatters import HtmlFormatter
38 pygments_formatter = HtmlFormatter()
40 def pygments_directive(name, arguments, options, content, lineno,
41 content_offset, block_text, state, state_machine):
42 try:
43 lexer = get_lexer_by_name(arguments[0])
44 except ValueError:
45 # no lexer found - use the text one instead of an exception
46 lexer = get_lexer_by_name('text')
47 parsed = highlight(u'\n'.join(content), lexer, pygments_formatter)
48 return [nodes.raw('', parsed, format='html')]
49 pygments_directive.arguments = (1, 0, 1)
50 pygments_directive.content = 1
51 directives.register_directive('sourcecode', pygments_directive)
53 # Call the docutils publisher to render the input as html::
55 publish_cmdline(writer_name='html', description=description)
57 # .. _doctutile: http://docutils.sf.net/
58 # .. _pygments: http://pygments.org/
59 # .. _Using Pygments in ReST documents: http://pygments.org/docs/rstdirective/