PageRenderTime 115ms CodeModel.GetById 96ms app.highlight 12ms RepoModel.GetById 2ms app.codeStats 0ms

/kai/lib/pygmentsupport.py

https://bitbucket.org/bbangert/kai/
Python | 55 lines | 40 code | 1 blank | 14 comment | 0 complexity | 628e3c571d93a511485f3205c909909f MD5 | raw file
 1import docutils.parsers.rst
 2from pygments import highlight
 3from pygments.lexers import get_lexer_by_name, get_all_lexers
 4from pygments.formatters import HtmlFormatter
 5
 6def code_block( name, arguments, options, content, lineno,
 7             content_offset, block_text, state, state_machine ):
 8    """
 9    The code-block directive provides syntax highlighting for blocks
10    of code.  It is used with the the following syntax::
11
12    .. code-block:: Python
13 
14        class Test(object):
15            pass
16    
17    The code will be highlighted with the pygments syntax highlighter. It's
18    recommended that you include the appropriate stylesheets when using this
19    highlighter.
20    """
21
22    try:
23        language = arguments[0]
24    except IndexError:
25        language = options.get('language', '')
26    try:
27        linenos = arguments[1]
28    except IndexError:
29        linenos = options.get('linenos', False)
30
31    language = language.lower()
32    if language == 'hypertext':
33        language = 'html'
34    if language == 'pasteini':
35        language = 'ini'
36    content = '\n'.join(content)
37    if not language:
38        if content.strip().startswith('>>>'):
39            language = 'pycon'
40        else:
41            language = 'python'
42    lexer = get_lexer_by_name(language, stripall=True)
43    formatter = HtmlFormatter(linenos=linenos, cssclass="syntax", encoding='utf-8')
44    html = highlight(unicode(content), lexer, formatter).decode('utf-8')
45    raw = docutils.nodes.raw('',html, format = 'html')
46    return [raw]
47
48#code_block.arguments = (1,0,0)
49code_block.arguments = (1,0,0)
50code_block.options = {'linenos':docutils.parsers.rst.directives, 
51                      'language':docutils.parsers.rst.directives.unchanged}
52code_block.content = 1
53  
54# Simply importing this module will make the directive available.
55docutils.parsers.rst.directives.register_directive( 'code-block', code_block )