3 # Author: David Goodger, an unknown Pygments author|contributor, 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 colorized code 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 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
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
):
43 lexer
= get_lexer_by_name(arguments
[0])
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/