3 # :Author: David Goodger, the Pygments team, Guenter Milde
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.
11 A front end to docutils, producing HTML with syntax colouring using pygments
16 locale
.setlocale(locale
.LC_ALL
, '')
20 from docutils
.core
import publish_cmdline
, default_description
22 description
= ('Generates (X)HTML 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
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 HtmlFormatter
39 pygments_formatter
= HtmlFormatter()
41 def pygments_directive(name
, arguments
, options
, content
, lineno
,
42 content_offset
, block_text
, state
, state_machine
):
44 lexer
= get_lexer_by_name(arguments
[0])
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
='html')]
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 html::
56 publish_cmdline(writer_name
='html', description
=description
)
58 # .. _doctutile: http://docutils.sf.net/
59 # .. _pygments: http://pygments.org/
60 # .. _Using Pygments in ReST documents: http://pygments.org/docs/rstdirective/