summaryrefslogtreecommitdiff
path: root/content/resources/rst_graphviz/rst2latex.py
blob: 615d2e54b4282e2f1ad111fc81b7c256d4f3c0c1 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/python

# $Id: rst2latex.py 5905 2009-04-16 12:04:49Z milde $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.

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

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

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

import subprocess
import os.path

from docutils.core import publish_cmdline
from docutils.parsers.rst import directives
from docutils.parsers.rst.directives.images import Figure, Image

description = ('Generates LaTeX documents from standalone reStructuredText '
               'sources. '
               'Reads from <source> (default is stdin) and writes to '
               '<destination> (default is stdout).  See '
               '<http://docutils.sourceforge.net/docs/user/latex.html> for '
               'the full reference.')

DOT2TEX = "dot2tex"

def processContent(node):

    if node.content.count("..") == 0:
        sep = -1 
        text = '\n'.join(node.content)
    else:
        sep = node.content.index("..")
        text = '\n'.join(node.content[:sep])
    extension = 'pdf'
    pdfFile = "tmp/%s.pdf" % (hash(text))


    if not os.path.exists(pdfFile):
        conversion = subprocess.Popen(['dot',
            '-T', extension,
            "-Gcharset=utf8",
            ],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            )

        ps2pdf = subprocess.Popen(['ps2pdf',
            "-",
            pdfFile
            ],
            stdin = conversion.stdout
            )
        conversion.stdin.write("%s G {\n" %
                node.arguments[0].encode("utf-8"))
        conversion.stdin.write(text.encode("utf-8"))
        conversion.stdin.write("\n}")
        conversion.stdin.close()
        conversion.stdout.close()

        ps2pdf.wait()
        conversion.wait()
        if conversion.returncode != 0:
            raise node.error(
                'Error in "%s" directive:\n' % node.name)

    return (sep, pdfFile)

class GraphvizImage(Image):
    """ Generate a graphviz image
    """
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True

    has_content = True

    option_spec = Image.option_spec.copy()

    def run(self):


        sep, arguments = processContent(self)
        self.arguments = [arguments]
        self.options['scale'] = 66
        if sep == -1:
            self.content = None
        else:
            self.content = self.content[sep+1:]

        return Image.run(self)

class Graphviz(Figure):
    """ Generate a graphviz image
    """
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True

    has_content = True

    option_spec = Figure.option_spec.copy()

    def run(self):

        sep, arguments = processContent(self)
        self.arguments = [arguments]
        self.options['scale'] = 66
        if sep == -1:
            self.content = None
        else:
            self.content = self.content[sep+1:]

        return Figure.run(self)


class Dot2Tex(Figure):
    """ Generate a graphviz image using dot2tex
    """
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True

    has_content = True

    option_spec = Figure.option_spec.copy()

    def run(self):

        if self.content.count("..") == 0:
            sep = -1 
            text = '\n'.join(self.content)
        else:
            sep = self.content.index("..")
            text = '\n'.join(self.content[:sep])
        pdfFile = "tmp/%s.pdf" % (hash(text))
        texFile = "tmp/%s.tex" % (hash(text))


        if not os.path.exists(pdfFile):
            conversion = subprocess.Popen([DOT2TEX,
                '-c',
                '-o', texFile,
                ],
                stdin=subprocess.PIPE
                )
            conversion.communicate("%s G { \n %s \n}" 
                    % (self.arguments[0], text))
            conversion.wait()

            ps2pdf = subprocess.Popen(['pdflatex',
                '-output-directory', 'tmp',
                texFile,
                ],
                )
            ps2pdf.wait()
            if conversion.returncode != 0:
                raise self.error(
                    'Error in "%s" directive:\n' % self.name)

        self.arguments = [pdfFile]
        self.options['scale'] = 66
        if sep == -1:
            self.content = None
        else:
            self.content = self.content[sep+1:]

        return Figure.run(self)

#try:
#    # Check if dot2tex exists and register the conversion with dot2tex and
#    # pdftex
#    subprocess.check_call([DOT2TEX, "-V"])
#    directives.register_directive('graphviz', Dot2Tex)
#    directives.register_directive('graphimg', GraphvizImage)
#except:
#    # Otherwise use the old graphviz program
directives.register_directive('graphviz', Graphviz)
directives.register_directive('graphimg', GraphvizImage)

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