summaryrefslogtreecommitdiff
path: root/sandbox/jensj/latex_math/tools/rst2latexmath.py
blob: 38592e83116095466365acb9238cd9e7d34d9742 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python

"""
A minimal front end to the Docutils Publisher, producing LaTeX.
"""

try:
    import locale
    locale.setlocale(locale.LC_ALL, '')
except:
    pass

from docutils.parsers.rst.roles import register_canonical_role
from docutils import nodes
from docutils.writers.latex2e import LaTeXTranslator
from docutils.core import publish_cmdline, default_description


# Define LaTeX math node:
class latex_math(nodes.Element):
    tagname = '#latex-math'
    def __init__(self, rawsource, latex):
        nodes.Element.__init__(self, rawsource)
        self.latex = latex

# Register role:
def latex_math_role(role, rawtext, text, lineno, inliner,
                    options={}, content=[]):
    i = rawtext.find('`')
    latex = rawtext[i+1:-1]
    node = latex_math(rawtext, latex)
    return [node], []
register_canonical_role('latex-math', latex_math_role)


# Register directive:
try:
    from docutils.parsers.rst import Directive
except ImportError:
    from docutils.parsers.rst.directives import _directives
    def latex_math_directive(name, arguments, options, content, lineno,
                             content_offset, block_text, state, state_machine):
        latex = ''.join(content)
        node = latex_math(block_text, latex)
        return [node]
    latex_math_directive.arguments = None
    latex_math_directive.options = {}
    latex_math_directive.content = 1
    _directives['latex-math'] = latex_math_directive
else:
    from docutils.parsers.rst import directives
    class latex_math_directive(Directive):
        has_content = True
        def run(self): 
            latex = ''.join(self.content)
            node = latex_math(self.block_text, latex)
            return [node]
    directives.register_directive('latex-math', latex_math_directive)

# Add visit/depart methods to HTML-Translator:
def visit_latex_math(self, node):
    inline = isinstance(node.parent, nodes.TextElement)
    if inline:
        self.body.append('$%s$' % node.latex)
    else:
        self.body.extend(['\\begin{equation*}\\begin{split}',
                          node.latex,
                          '\\end{split}\\end{equation*}'])
def depart_latex_math(self, node):
    pass
LaTeXTranslator.visit_latex_math = visit_latex_math
LaTeXTranslator.depart_latex_math = depart_latex_math


description = ('Generates LaTeX documents from standalone reStructuredText '
               'sources.  ' + default_description)

publish_cmdline(writer_name='latex', description=description)