| 1 |
#!/usr/bin/env python |
|---|
| 2 |
|
|---|
| 3 |
import docutils.parsers.rst |
|---|
| 4 |
import StringIO |
|---|
| 5 |
from pygments import highlight |
|---|
| 6 |
from pygments.lexers import get_lexer_by_name |
|---|
| 7 |
from pygments.formatters import HtmlFormatter |
|---|
| 8 |
|
|---|
| 9 |
def code_block( name, arguments, options, content, lineno, |
|---|
| 10 |
content_offset, block_text, state, state_machine ): |
|---|
| 11 |
""" |
|---|
| 12 |
The code-block directive provides syntax highlighting for blocks |
|---|
| 13 |
of code. It is used with the the following syntax:: |
|---|
| 14 |
|
|---|
| 15 |
.. code-block:: CPP |
|---|
| 16 |
|
|---|
| 17 |
#include <iostream> |
|---|
| 18 |
|
|---|
| 19 |
int main( int argc, char* argv[] ) |
|---|
| 20 |
{ |
|---|
| 21 |
std::cout << "Hello world" << std::endl; |
|---|
| 22 |
} |
|---|
| 23 |
|
|---|
| 24 |
The directive requires the name of a language supported by Pygments |
|---|
| 25 |
as its only argument. All code in the indented block following |
|---|
| 26 |
the directive will be colourized. Note that this directive is only |
|---|
| 27 |
supported for HTML writers. |
|---|
| 28 |
""" |
|---|
| 29 |
language = arguments[0] |
|---|
| 30 |
formatter = HtmlFormatter() |
|---|
| 31 |
|
|---|
| 32 |
try: |
|---|
| 33 |
lexer = get_lexer_by_name(language) |
|---|
| 34 |
except Exception: |
|---|
| 35 |
error = state_machine.reporter.error( "No Pygments lexer found " |
|---|
| 36 |
"for language '%s'." % language, |
|---|
| 37 |
docutils.nodes.literal_block(block_text, block_text), line=lineno ) |
|---|
| 38 |
return [error] |
|---|
| 39 |
io = StringIO.StringIO() |
|---|
| 40 |
html = highlight('\n'.join(content), lexer, formatter) |
|---|
| 41 |
raw = docutils.nodes.raw('',html, format = 'html') |
|---|
| 42 |
return [raw] |
|---|
| 43 |
|
|---|
| 44 |
code_block.arguments = (1,0,0) |
|---|
| 45 |
code_block.options = {'language' : docutils.parsers.rst.directives.unchanged } |
|---|
| 46 |
code_block.content = 1 |
|---|
| 47 |
|
|---|
| 48 |
# Simply importing this module will make the directive available. |
|---|
| 49 |
docutils.parsers.rst.directives.register_directive( 'code-block', code_block ) |
|---|
| 50 |
|
|---|
| 51 |
if __name__ == "__main__": |
|---|
| 52 |
import docutils.core |
|---|
| 53 |
docutils.core.publish_cmdline(writer_name='html', argv=['--stylesheet-path=stylesheet.css']) |
|---|