/kai/lib/pygmentsupport.py

https://bitbucket.org/bbangert/kai/ · Python · 55 lines · 40 code · 1 blank · 14 comment · 0 complexity · 628e3c571d93a511485f3205c909909f MD5 · raw file

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