initial setup of thesis repository
[cluster_expansion_thesis.git] / little_helpers / tikz / tikz2pdf
blob831891d8662bfe863e6800559826241b4d749094
1 #!/usr/bin/env python
3 # Copyright (c) 2007, Hans Meine <hans_meine@gmx.net>
4 # All rights reserved.
6 # This is licensed according to the new BSD license.
7 # Please send patches / comments, I would be happy about any feedback.
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
11 # are met:
13 # * Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
16 # * Redistributions in binary form must reproduce the above copyright
17 # notice, this list of conditions and the following disclaimer in the
18 # documentation and/or other materials provided with the distribution.
20 # * Neither the name of the University of Hamburg nor the names of its
21 # contributors may be used to endorse or promote products derived from
22 # this software without specific prior written permission.
24 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 # POSSIBILITY OF SUCH DAMAGE.
37 import sys, os.path, subprocess, glob, time, optparse, tempfile
39 op = optparse.OptionParser(usage="%prog [options] foo.tikz")
40 op.add_option("-v", "--verbose", action = "store_true", default = False,
41 dest = "verbose", help = "verbose output")
42 op.add_option("-o", "--once", action = "store_true",
43 dest = "once", default = False,
44 help = "only convert once, then clean up temporary files and quit")
45 op.add_option("-s", "--view", action = "store_true",
46 dest = "view", default = False,
47 help = "start viewer after first successful compilation")
49 options, args = op.parse_args()
50 tikzName, = args # exactly one filename expected
52 basename = "tikz2pdf_temp"
53 texName = basename + ".tex"
54 pdfName = basename + ".pdf"
56 templateFilename = os.path.expanduser("~/.tikz2pdf.tex")
57 searchDir = os.getcwd()
58 while searchDir != "/":
59 candidate = os.path.join(searchDir, ".tikz2pdf.tex")
60 if os.path.exists(candidate):
61 templateFilename = candidate
62 sys.stdout.write("Using template %r.\n" % candidate)
63 break
64 searchDir = os.path.split(searchDir)[0]
66 # re-use texdoc's configuration variables for viewing TeX's output:
67 viewCommand = "xpdf -remote localhost %r"
68 reloadCommand = "xpdf -remote localhost -reload "
69 texdocViewCommand = os.environ.get("TEXDOCVIEW_pdf", None)
70 if texdocViewCommand:
71 viewCommand = texdocViewCommand.rstrip("&").replace("%s", "%r")
73 if os.path.exists(templateFilename):
74 template = file(templateFilename).read()
75 else:
76 template = r"""\documentclass{article}
78 \usepackage{tikz,nicefrac,amsmath,pifont}
79 \usetikzlibrary{arrows,snakes,backgrounds,patterns,matrix,shapes,fit,calc,shadows,plotmarks}
81 \usepackage[graphics,tightpage,active]{preview}
82 \PreviewEnvironment{tikzpicture}
83 \newlength{\imagewidth}
84 \newlength{\imagescale}
86 \begin{document}
88 \input{%s}
90 \end{document}
91 """
92 sys.stderr.write("INFO: '%s' did not exist, saving default template - please configure!\n" % templateFilename)
93 file(templateFilename, "w").write(template)
95 file(texName, "w").write(template % tikzName)
97 def verboseUnlink(filename):
98 # FIXME: check mtime
99 if options.verbose:
100 print "cleaning up %r..." % filename
101 try:
102 os.unlink(filename)
103 except OSError, e:
104 if e.errno != 2:
105 raise e
107 viewer = None
109 previous = 0
110 while True:
111 try:
112 mtime = os.path.getmtime(tikzName)
113 if mtime > previous:
114 out = None
115 print "tikz2pdf: calling pdflatex..."
116 if not options.verbose:
117 out = tempfile.TemporaryFile()
118 ec = subprocess.call(
119 ["pdflatex", "-halt-on-error", texName], stdout = out)
120 if ec:
121 if out:
122 out.seek(0)
123 sys.stdout.write(out.read())
124 print "tikz2pdf: ERROR generating %r with pdflatex." % pdfName
125 else:
126 print "tikz2pdf: Successfully generated %r." % pdfName
127 if options.view and viewer is None:
128 print "tikz2pdf: starting viewer..."
129 viewer = subprocess.Popen(viewCommand % pdfName, shell = True)
130 elif options.view:
131 print "tikz2pdf: Reloading viewer ..."
132 viewer = subprocess.Popen(reloadCommand, shell = True)
134 if out:
135 out.close()
137 previous = mtime
138 if options.once:
139 break
140 time.sleep(1)
141 except KeyboardInterrupt:
142 verboseUnlink(pdfName)
143 break
145 verboseUnlink(texName)
146 for temp in glob.glob("tikz2pdf_temp.*"):
147 if temp != pdfName:
148 verboseUnlink(temp)
149 # for ext in (".aux", ".log"):
150 # verboseUnlink(basename + ext)