Example stylesheets for syntax highlight of code snippets.
[docutils/kirr.git] / sandbox / code-block-directive / tools / pygments-enhanced-front-ends / rst2latex-pygments
blobc53c2aa74d7144a90c87e84c2ff8ea7403dea25c
1 #!/usr/bin/python
3 # Author: David Goodger, the Pygments team, Günter Milde
4 # Date: $Date: $
5 # Copyright: This module has been placed in the public domain.
7 # This is a merge of the docutils_ `rst2latex` front end with an extension
8 # suggestion taken from the pygments_ documentation.
10 """
11 A front end to docutils, producing LaTeX with syntax colouring 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 LaTeX documents from standalone reStructuredText '
23 'sources. Uses `pygments` to colorize the content of'
24 '"code-block" directives. Needs an adapted stylesheet'
25 + default_description)
27 # Define a new directive `code-block` that uses the `pygments` source
28 # highlighter to render code in color.
30 # Code from the `pygments`_ documentation for `Using Pygments in ReST
31 # documents`_.
33 from docutils import nodes
34 from docutils.parsers.rst import directives
35 from pygments import highlight
36 from pygments.lexers import get_lexer_by_name
37 from pygments.formatters import LatexFormatter
39 pygments_formatter = LatexFormatter()
41 def pygments_directive(name, arguments, options, content, lineno,
42 content_offset, block_text, state, state_machine):
43 try:
44 lexer = get_lexer_by_name(arguments[0])
45 except ValueError:
46 # no lexer found - use the text one instead of an exception
47 lexer = get_lexer_by_name('text')
48 parsed = highlight(u'\n'.join(content), lexer, pygments_formatter)
49 return [nodes.raw('', parsed, format='latex')]
50 pygments_directive.arguments = (1, 0, 1)
51 pygments_directive.content = 1
52 directives.register_directive('code-block', pygments_directive)
54 # Call the docutils publisher to render the input as latex::
56 publish_cmdline(writer_name='latex', description=description)
58 # .. _doctutile: http://docutils.sf.net/
59 # .. _pygments: http://pygments.org/
60 # .. _Using Pygments in ReST documents: http://pygments.org/docs/rstdirective/