rest2latex.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/python
  2. # Testing:
  3. # python rest2latex.py objectify.txt > latex/objectify.tex
  4. """
  5. A minimal front end to the Docutils Publisher, producing LaTeX with
  6. some syntax highlighting.
  7. """
  8. # Set to True if you want inline CSS styles instead of classes
  9. INLINESTYLES = False
  10. try:
  11. import locale
  12. locale.setlocale(locale.LC_ALL, '')
  13. except:
  14. pass
  15. # set up Pygments
  16. from pygments.formatters import LatexFormatter
  17. # The default formatter
  18. DEFAULT = LatexFormatter()
  19. # Add name -> formatter pairs for every variant you want to use
  20. VARIANTS = {
  21. # 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True),
  22. }
  23. from docutils import nodes
  24. from docutils.parsers.rst import directives
  25. from pygments import highlight
  26. from pygments.lexers import get_lexer_by_name, TextLexer
  27. def pygments_directive(name, arguments, options, content, lineno,
  28. content_offset, block_text, state, state_machine):
  29. try:
  30. lexer = get_lexer_by_name(arguments[0])
  31. except ValueError, e:
  32. # no lexer found - use the text one instead of an exception
  33. lexer = TextLexer()
  34. # take an arbitrary option if more than one is given
  35. formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
  36. parsed = highlight(u'\n'.join(content), lexer, formatter)
  37. return [nodes.raw('', parsed, format='latex')]
  38. pygments_directive.arguments = (1, 0, 1)
  39. pygments_directive.content = 1
  40. pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])
  41. directives.register_directive('sourcecode', pygments_directive)
  42. # run the generation
  43. from docutils.core import publish_cmdline, default_description
  44. description = ('Generates LaTeX documents from standalone reStructuredText '
  45. 'sources. ' + default_description)
  46. publish_cmdline(writer_name='latex2e', description=description)