fix file opening for bbox reading when using filelocator (reported by Michael J Gruber)
[PyX/mjg.git] / pyx / text.py
blobf3027ed75370791a803dbb82ac2e8f04946093af
1 # -*- encoding: utf-8 -*-
4 # Copyright (C) 2002-2004 Jörg Lehmann <joergl@users.sourceforge.net>
5 # Copyright (C) 2003-2011 Michael Schindler <m-schindler@users.sourceforge.net>
6 # Copyright (C) 2002-2011 André Wobst <wobsta@users.sourceforge.net>
8 # This file is part of PyX (http://pyx.sourceforge.net/).
10 # PyX is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
15 # PyX is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with PyX; if not, write to the Free Software
22 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 import errno, glob, os, threading, Queue, re, tempfile, atexit, time, warnings
25 import config, unit, box, canvas, trafo, version, attr, style, filelocator, pycompat
26 from pyx.dvi import dvifile
27 import bbox as bboxmodule
29 class PyXTeXWarning(UserWarning): pass
30 warnings.filterwarnings('always', category=PyXTeXWarning)
32 ###############################################################################
33 # texmessages
34 # - please don't get confused:
35 # - there is a texmessage (and a texmessageparsed) attribute within the
36 # texrunner; it contains TeX/LaTeX response from the last command execution
37 # - instances of classes derived from the class texmessage are used to
38 # parse the TeX/LaTeX response as it is stored in the texmessageparsed
39 # attribute of a texrunner instance
40 # - the multiple usage of the name texmessage might be removed in the future
41 # - texmessage instances should implement _Itexmessage
42 ###############################################################################
44 class TexResultError(RuntimeError):
45 """specialized texrunner exception class
46 - it is raised by texmessage instances, when a texmessage indicates an error
47 - it is raised by the texrunner itself, whenever there is a texmessage left
48 after all parsing of this message (by texmessage instances)
49 prints a detailed report about the problem
50 - the verbose level is controlled by texrunner.errordebug"""
52 def __init__(self, description, texrunner):
53 if texrunner.errordebug >= 2:
54 self.description = ("%s\n" % description +
55 "The expression passed to TeX was:\n"
56 " %s\n" % texrunner.expr.replace("\n", "\n ").rstrip() +
57 "The return message from TeX was:\n"
58 " %s\n" % texrunner.texmessage.replace("\n", "\n ").rstrip() +
59 "After parsing this message, the following was left:\n"
60 " %s" % texrunner.texmessageparsed.replace("\n", "\n ").rstrip())
61 elif texrunner.errordebug == 1:
62 firstlines = texrunner.texmessageparsed.split("\n")
63 if len(firstlines) > 5:
64 firstlines = firstlines[:5] + ["(cut after 5 lines, increase errordebug for more output)"]
65 self.description = ("%s\n" % description +
66 "The expression passed to TeX was:\n"
67 " %s\n" % texrunner.expr.replace("\n", "\n ").rstrip() +
68 "After parsing the return message from TeX, the following was left:\n" +
69 reduce(lambda x, y: "%s %s\n" % (x,y), firstlines, "").rstrip())
70 else:
71 self.description = description
73 def __str__(self):
74 return self.description
77 class _Itexmessage:
78 """validates/invalidates TeX/LaTeX response"""
80 def check(self, texrunner):
81 """check a Tex/LaTeX response and respond appropriate
82 - read the texrunners texmessageparsed attribute
83 - if there is an problem found, raise TexResultError
84 - remove any valid and identified TeX/LaTeX response
85 from the texrunners texmessageparsed attribute
86 -> finally, there should be nothing left in there,
87 otherwise it is interpreted as an error"""
90 class texmessage(attr.attr): pass
93 class _texmessagestart(texmessage):
94 """validates TeX/LaTeX startup"""
96 __implements__ = _Itexmessage
98 startpattern = re.compile(r"This is [-0-9a-zA-Z\s_]*TeX")
100 def check(self, texrunner):
101 # check for "This is e-TeX"
102 m = self.startpattern.search(texrunner.texmessageparsed)
103 if not m:
104 raise TexResultError("TeX startup failed", texrunner)
105 texrunner.texmessageparsed = texrunner.texmessageparsed[m.end():]
107 # check for \raiseerror -- just to be sure that communication works
108 try:
109 texrunner.texmessageparsed = texrunner.texmessageparsed.split("*! Undefined control sequence.\n<*> \\raiseerror\n %\n", 1)[1]
110 except (IndexError, ValueError):
111 raise TexResultError("TeX scrollmode check failed", texrunner)
114 class _texmessagenofile(texmessage):
115 """allows for LaTeXs no-file warning"""
117 __implements__ = _Itexmessage
119 def __init__(self, fileending):
120 self.fileending = fileending
122 def check(self, texrunner):
123 try:
124 s1, s2 = texrunner.texmessageparsed.split("No file %s.%s." % (texrunner.texfilename, self.fileending), 1)
125 texrunner.texmessageparsed = s1 + s2
126 except (IndexError, ValueError):
127 try:
128 s1, s2 = texrunner.texmessageparsed.split("No file %s%s%s.%s." % (os.curdir,
129 os.sep,
130 texrunner.texfilename,
131 self.fileending), 1)
132 texrunner.texmessageparsed = s1 + s2
133 except (IndexError, ValueError):
134 pass
137 class _texmessageinputmarker(texmessage):
138 """validates the PyXInputMarker"""
140 __implements__ = _Itexmessage
142 def check(self, texrunner):
143 try:
144 s1, s2 = texrunner.texmessageparsed.split("PyXInputMarker:executeid=%s:" % texrunner.executeid, 1)
145 texrunner.texmessageparsed = s1 + s2
146 except (IndexError, ValueError):
147 raise TexResultError("PyXInputMarker expected", texrunner)
150 class _texmessagepyxbox(texmessage):
151 """validates the PyXBox output"""
153 __implements__ = _Itexmessage
155 pattern = re.compile(r"PyXBox:page=(?P<page>\d+),lt=-?\d*((\d\.?)|(\.?\d))\d*pt,rt=-?\d*((\d\.?)|(\.?\d))\d*pt,ht=-?\d*((\d\.?)|(\.?\d))\d*pt,dp=-?\d*((\d\.?)|(\.?\d))\d*pt:")
157 def check(self, texrunner):
158 m = self.pattern.search(texrunner.texmessageparsed)
159 if m and m.group("page") == str(texrunner.page):
160 texrunner.texmessageparsed = texrunner.texmessageparsed[:m.start()] + texrunner.texmessageparsed[m.end():]
161 else:
162 raise TexResultError("PyXBox expected", texrunner)
165 class _texmessagepyxpageout(texmessage):
166 """validates the dvi shipout message (writing a page to the dvi file)"""
168 __implements__ = _Itexmessage
170 def check(self, texrunner):
171 try:
172 s1, s2 = texrunner.texmessageparsed.split("[80.121.88.%s]" % texrunner.page, 1)
173 texrunner.texmessageparsed = s1 + s2
174 except (IndexError, ValueError):
175 raise TexResultError("PyXPageOutMarker expected", texrunner)
178 class _texmessageend(texmessage):
179 """validates TeX/LaTeX finish"""
181 __implements__ = _Itexmessage
183 auxPattern = re.compile(r"\(([^()]+\.aux|\"[^\"]+\.aux\")\)")
185 def check(self, texrunner):
186 m = self.auxPattern.search(texrunner.texmessageparsed)
187 if m:
188 texrunner.texmessageparsed = (texrunner.texmessageparsed[:m.start()] + texrunner.texmessageparsed[m.end():]).strip()
190 # check for "(see the transcript file for additional information)"
191 try:
192 s1, s2 = texrunner.texmessageparsed.split("(see the transcript file for additional information)", 1)
193 texrunner.texmessageparsed = (s1 + s2).strip()
194 except (IndexError, ValueError):
195 pass
197 # check for "Output written on ...dvi (1 page, 220 bytes)."
198 dvipattern = re.compile(r"Output written on %s\.dvi \((?P<page>\d+) pages?, \d+ bytes\)\." % texrunner.texfilename)
199 m = dvipattern.search(texrunner.texmessageparsed)
200 if texrunner.page:
201 if not m:
202 raise TexResultError("TeX dvifile messages expected", texrunner)
203 if m.group("page") != str(texrunner.page):
204 raise TexResultError("wrong number of pages reported", texrunner)
205 texrunner.texmessageparsed = texrunner.texmessageparsed[:m.start()] + texrunner.texmessageparsed[m.end():]
206 else:
207 try:
208 s1, s2 = texrunner.texmessageparsed.split("No pages of output.", 1)
209 texrunner.texmessageparsed = s1 + s2
210 except (IndexError, ValueError):
211 raise TexResultError("no dvifile expected", texrunner)
213 # check for "Transcript written on ...log."
214 try:
215 s1, s2 = texrunner.texmessageparsed.split("Transcript written on %s.log." % texrunner.texfilename, 1)
216 texrunner.texmessageparsed = s1 + s2
217 except (IndexError, ValueError):
218 raise TexResultError("TeX logfile message expected", texrunner)
221 class _texmessageemptylines(texmessage):
222 """validates "*-only" (TeX/LaTeX input marker in interactive mode) and empty lines
223 also clear TeX interactive mode warning (Please type a command or say `\\end')
226 __implements__ = _Itexmessage
228 def check(self, texrunner):
229 texrunner.texmessageparsed = texrunner.texmessageparsed.replace(r"(Please type a command or say `\end')", "")
230 texrunner.texmessageparsed = texrunner.texmessageparsed.replace(" ", "")
231 texrunner.texmessageparsed = texrunner.texmessageparsed.replace("*\n", "")
232 texrunner.texmessageparsed = texrunner.texmessageparsed.replace("\n", "")
235 class _texmessageload(texmessage):
236 """validates inclusion of arbitrary files
237 - the matched pattern is "(<filename> <arbitrary other stuff>)", where
238 <filename> is a readable file and other stuff can be anything
239 - If the filename is enclosed in double quotes, it may contain blank space.
240 - "(" and ")" must be used consistent (otherwise this validator just does nothing)
241 - this is not always wanted, but we just assume that file inclusion is fine"""
243 __implements__ = _Itexmessage
245 pattern = re.compile(r"\([\"]?(?P<filename>(?:(?<!\")[^()\s\n]+(?!\"))|[^\"\n]+)[\"]?(?P<additional>[^()]*)\)")
247 def baselevels(self, s, maxlevel=1, brackets="()", quotes='""'):
248 """strip parts of a string above a given bracket level
249 - return a modified (some parts might be removed) version of the string s
250 where all parts inside brackets with level higher than maxlevel are
251 removed
252 - if brackets do not match (number of left and right brackets is wrong
253 or at some points there were more right brackets than left brackets)
254 just return the unmodified string
255 - a quoted string immediately followed after a bracket is left untouched
256 even if it contains quotes itself"""
257 level = 0
258 highestlevel = 0
259 inquote = 0
260 res = ""
261 for i, c in enumerate(s):
262 if quotes and level <= maxlevel:
263 if not inquote and c == quotes[0] and i and s[i-1] == brackets[0]:
264 inquote = 1
265 elif inquote and c == quotes[1]:
266 inquote = 0
267 if inquote:
268 res += c
269 else:
270 if c == brackets[0]:
271 level += 1
272 if level > highestlevel:
273 highestlevel = level
274 if level <= maxlevel:
275 res += c
276 if c == brackets[1]:
277 level -= 1
278 if level == 0 and highestlevel > 0:
279 return res
281 def check(self, texrunner):
282 search = self.baselevels(texrunner.texmessageparsed)
283 res = []
284 if search is not None:
285 m = self.pattern.search(search)
286 while m:
287 filename = m.group("filename").replace("\n", "")
288 try:
289 additional = m.group("additional")
290 except IndexError:
291 additional = ""
292 if (os.access(filename, os.R_OK) or
293 len(additional) and additional[0] == "\n" and os.access(filename+additional.split()[0], os.R_OK)):
294 res.append(search[:m.start()])
295 else:
296 res.append(search[:m.end()])
297 search = search[m.end():]
298 m = self.pattern.search(search)
299 else:
300 res.append(search)
301 texrunner.texmessageparsed = "".join(res)
304 class _texmessageloaddef(_texmessageload):
305 """validates the inclusion of font description files (fd-files)
306 - works like _texmessageload
307 - filename must end with .def or .fd
308 - further text is allowed"""
310 pattern = re.compile(r"\([\"]?(?P<filename>(?:(?:(?<!\")[^\(\)\s\n\"]+)|(?:(?<=\")[^\(\)\"]+))(\.fd|\.def))[\"]?[\s\n]*(?P<additional>[\(]?[^\(\)]*[\)]?)[\s\n]*\)")
312 def baselevels(self, s, **kwargs):
313 return s
316 class _texmessagegraphicsload(_texmessageload):
317 """validates the inclusion of files as the graphics packages writes it
318 - works like _texmessageload, but using "<" and ">" as delimiters
319 - filename must end with .eps and no further text is allowed"""
321 pattern = re.compile(r"<(?P<filename>[^>]+.eps)>")
323 def baselevels(self, s, **kwargs):
324 return s
327 class _texmessageignore(_texmessageload):
328 """validates any TeX/LaTeX response
329 - this might be used, when the expression is ok, but no suitable texmessage
330 parser is available
331 - PLEASE: - consider writing suitable tex message parsers
332 - share your ideas/problems/solutions with others (use the PyX mailing lists)"""
334 __implements__ = _Itexmessage
336 def check(self, texrunner):
337 texrunner.texmessageparsed = ""
340 texmessage.start = _texmessagestart()
341 texmessage.noaux = _texmessagenofile("aux")
342 texmessage.nonav = _texmessagenofile("nav")
343 texmessage.end = _texmessageend()
344 texmessage.load = _texmessageload()
345 texmessage.loaddef = _texmessageloaddef()
346 texmessage.graphicsload = _texmessagegraphicsload()
347 texmessage.ignore = _texmessageignore()
349 # for internal use:
350 texmessage.inputmarker = _texmessageinputmarker()
351 texmessage.pyxbox = _texmessagepyxbox()
352 texmessage.pyxpageout = _texmessagepyxpageout()
353 texmessage.emptylines = _texmessageemptylines()
356 class _texmessageallwarning(texmessage):
357 """validates a given pattern 'pattern' as a warning 'warning'"""
359 def check(self, texrunner):
360 if texrunner.texmessageparsed:
361 warnings.warn("ignoring all warnings:\n%s" % texrunner.texmessageparsed)
362 texrunner.texmessageparsed = ""
364 texmessage.allwarning = _texmessageallwarning()
367 class texmessagepattern(texmessage):
368 """validates a given pattern and issue a warning (when set)"""
370 def __init__(self, pattern, warning=None):
371 self.pattern = pattern
372 self.warning = warning
374 def check(self, texrunner):
375 m = self.pattern.search(texrunner.texmessageparsed)
376 while m:
377 texrunner.texmessageparsed = texrunner.texmessageparsed[:m.start()] + texrunner.texmessageparsed[m.end():]
378 if self.warning:
379 warnings.warn("%s:\n%s" % (self.warning, m.string[m.start(): m.end()].rstrip()))
380 m = self.pattern.search(texrunner.texmessageparsed)
382 texmessage.fontwarning = texmessagepattern(re.compile(r"^LaTeX Font Warning: .*$(\n^\(Font\).*$)*", re.MULTILINE), "ignoring font warning")
383 texmessage.boxwarning = texmessagepattern(re.compile(r"^(Overfull|Underfull) \\[hv]box.*$(\n^..*$)*\n^$\n", re.MULTILINE), "ignoring overfull/underfull box warning")
384 texmessage.rerunwarning = texmessagepattern(re.compile(r"^(LaTeX Warning: Label\(s\) may have changed\. Rerun to get cross-references right\s*\.)$", re.MULTILINE), "ignoring rerun warning")
385 texmessage.packagewarning = texmessagepattern(re.compile(r"^package\s+(?P<packagename>\S+)\s+warning\s*:[^\n]+(?:\n\(?(?P=packagename)\)?[^\n]*)*", re.MULTILINE | re.IGNORECASE), "ignoring generic package warning")
386 texmessage.nobblwarning = texmessagepattern(re.compile(r"^[\s\*]*(No file .*\.bbl.)\s*", re.MULTILINE), "ignoring no-bbl warning")
390 ###############################################################################
391 # textattrs
392 ###############################################################################
394 _textattrspreamble = ""
396 class textattr:
397 "a textattr defines a apply method, which modifies a (La)TeX expression"
399 class _localattr: pass
401 _textattrspreamble += r"""\gdef\PyXFlushHAlign{0}%
402 \def\PyXragged{%
403 \leftskip=0pt plus \PyXFlushHAlign fil%
404 \rightskip=0pt plus 1fil%
405 \advance\rightskip0pt plus -\PyXFlushHAlign fil%
406 \parfillskip=0pt%
407 \pretolerance=9999%
408 \tolerance=9999%
409 \parindent=0pt%
410 \hyphenpenalty=9999%
411 \exhyphenpenalty=9999}%
414 class boxhalign(attr.exclusiveattr, textattr, _localattr):
416 def __init__(self, aboxhalign):
417 self.boxhalign = aboxhalign
418 attr.exclusiveattr.__init__(self, boxhalign)
420 def apply(self, expr):
421 return r"\gdef\PyXBoxHAlign{%.5f}%s" % (self.boxhalign, expr)
423 boxhalign.left = boxhalign(0)
424 boxhalign.center = boxhalign(0.5)
425 boxhalign.right = boxhalign(1)
426 # boxhalign.clear = attr.clearclass(boxhalign) # we can't defined a clearclass for boxhalign since it can't clear a halign's boxhalign
429 class flushhalign(attr.exclusiveattr, textattr, _localattr):
431 def __init__(self, aflushhalign):
432 self.flushhalign = aflushhalign
433 attr.exclusiveattr.__init__(self, flushhalign)
435 def apply(self, expr):
436 return r"\gdef\PyXFlushHAlign{%.5f}\PyXragged{}%s" % (self.flushhalign, expr)
438 flushhalign.left = flushhalign(0)
439 flushhalign.center = flushhalign(0.5)
440 flushhalign.right = flushhalign(1)
441 # flushhalign.clear = attr.clearclass(flushhalign) # we can't defined a clearclass for flushhalign since it couldn't clear a halign's flushhalign
444 class halign(attr.exclusiveattr, textattr, boxhalign, flushhalign, _localattr):
446 def __init__(self, aboxhalign, aflushhalign):
447 self.boxhalign = aboxhalign
448 self.flushhalign = aflushhalign
449 attr.exclusiveattr.__init__(self, halign)
451 def apply(self, expr):
452 return r"\gdef\PyXBoxHAlign{%.5f}\gdef\PyXFlushHAlign{%.5f}\PyXragged{}%s" % (self.boxhalign, self.flushhalign, expr)
454 halign.left = halign(0, 0)
455 halign.center = halign(0.5, 0.5)
456 halign.right = halign(1, 1)
457 halign.clear = attr.clearclass(halign)
458 halign.boxleft = boxhalign.left
459 halign.boxcenter = boxhalign.center
460 halign.boxright = boxhalign.right
461 halign.flushleft = halign.raggedright = flushhalign.left
462 halign.flushcenter = halign.raggedcenter = flushhalign.center
463 halign.flushright = halign.raggedleft = flushhalign.right
466 class _mathmode(attr.attr, textattr, _localattr):
467 "math mode"
469 def apply(self, expr):
470 return r"$\displaystyle{%s}$" % expr
472 mathmode = _mathmode()
473 clearmathmode = attr.clearclass(_mathmode)
476 class _phantom(attr.attr, textattr, _localattr):
477 "phantom text"
479 def apply(self, expr):
480 return r"\phantom{%s}" % expr
482 phantom = _phantom()
483 clearphantom = attr.clearclass(_phantom)
486 _textattrspreamble += "\\newbox\\PyXBoxVBox%\n\\newdimen\\PyXDimenVBox%\n"
488 class parbox_pt(attr.sortbeforeexclusiveattr, textattr):
490 top = 1
491 middle = 2
492 bottom = 3
494 def __init__(self, width, baseline=top):
495 self.width = width * 72.27 / (unit.scale["x"] * 72)
496 self.baseline = baseline
497 attr.sortbeforeexclusiveattr.__init__(self, parbox_pt, [_localattr])
499 def apply(self, expr):
500 if self.baseline == self.top:
501 return r"\linewidth=%.5ftruept\vtop{\hsize=\linewidth\textwidth=\linewidth{}%s}" % (self.width, expr)
502 elif self.baseline == self.middle:
503 return r"\linewidth=%.5ftruept\setbox\PyXBoxVBox=\hbox{{\vtop{\hsize=\linewidth\textwidth=\linewidth{}%s}}}\PyXDimenVBox=0.5\dp\PyXBoxVBox\setbox\PyXBoxVBox=\hbox{{\vbox{\hsize=\linewidth\textwidth=\linewidth{}%s}}}\advance\PyXDimenVBox by -0.5\dp\PyXBoxVBox\lower\PyXDimenVBox\box\PyXBoxVBox" % (self.width, expr, expr)
504 elif self.baseline == self.bottom:
505 return r"\linewidth=%.5ftruept\vbox{\hsize=\linewidth\textwidth=\linewidth{}%s}" % (self.width, expr)
506 else:
507 RuntimeError("invalid baseline argument")
509 parbox_pt.clear = attr.clearclass(parbox_pt)
511 class parbox(parbox_pt):
513 def __init__(self, width, **kwargs):
514 parbox_pt.__init__(self, unit.topt(width), **kwargs)
516 parbox.clear = parbox_pt.clear
519 _textattrspreamble += "\\newbox\\PyXBoxVAlign%\n\\newdimen\\PyXDimenVAlign%\n"
521 class valign(attr.sortbeforeexclusiveattr, textattr):
523 def __init__(self, avalign):
524 self.valign = avalign
525 attr.sortbeforeexclusiveattr.__init__(self, valign, [parbox_pt, _localattr])
527 def apply(self, expr):
528 return r"\setbox\PyXBoxVAlign=\hbox{{%s}}\PyXDimenVAlign=%.5f\ht\PyXBoxVAlign\advance\PyXDimenVAlign by -%.5f\dp\PyXBoxVAlign\lower\PyXDimenVAlign\box\PyXBoxVAlign" % (expr, 1-self.valign, self.valign)
530 valign.top = valign(0)
531 valign.middle = valign(0.5)
532 valign.bottom = valign(1)
533 valign.clear = valign.baseline = attr.clearclass(valign)
536 _textattrspreamble += "\\newdimen\\PyXDimenVShift%\n"
538 class _vshift(attr.sortbeforeattr, textattr):
540 def __init__(self):
541 attr.sortbeforeattr.__init__(self, [valign, parbox_pt, _localattr])
543 def apply(self, expr):
544 return r"%s\setbox0\hbox{{%s}}\lower\PyXDimenVShift\box0" % (self.setheightexpr(), expr)
546 class vshift(_vshift):
547 "vertical down shift by a fraction of a character height"
549 def __init__(self, lowerratio, heightstr="0"):
550 _vshift.__init__(self)
551 self.lowerratio = lowerratio
552 self.heightstr = heightstr
554 def setheightexpr(self):
555 return r"\setbox0\hbox{{%s}}\PyXDimenVShift=%.5f\ht0" % (self.heightstr, self.lowerratio)
557 class _vshiftmathaxis(_vshift):
558 "vertical down shift by the height of the math axis"
560 def setheightexpr(self):
561 return r"\setbox0\hbox{$\vcenter{\vrule width0pt}$}\PyXDimenVShift=\ht0"
564 vshift.bottomzero = vshift(0)
565 vshift.middlezero = vshift(0.5)
566 vshift.topzero = vshift(1)
567 vshift.mathaxis = _vshiftmathaxis()
568 vshift.clear = attr.clearclass(_vshift)
571 defaultsizelist = ["normalsize", "large", "Large", "LARGE", "huge", "Huge",
572 None, "tiny", "scriptsize", "footnotesize", "small"]
574 class size(attr.sortbeforeattr, textattr):
575 "font size"
577 def __init__(self, sizeindex=None, sizename=None, sizelist=defaultsizelist):
578 if (sizeindex is None and sizename is None) or (sizeindex is not None and sizename is not None):
579 raise RuntimeError("either specify sizeindex or sizename")
580 attr.sortbeforeattr.__init__(self, [_mathmode, _vshift])
581 if sizeindex is not None:
582 if sizeindex >= 0 and sizeindex < sizelist.index(None):
583 self.size = sizelist[sizeindex]
584 elif sizeindex < 0 and sizeindex + len(sizelist) > sizelist.index(None):
585 self.size = sizelist[sizeindex]
586 else:
587 raise IndexError("index out of sizelist range")
588 else:
589 self.size = sizename
591 def apply(self, expr):
592 return r"\%s{}%s" % (self.size, expr)
594 size.tiny = size(-4)
595 size.scriptsize = size.script = size(-3)
596 size.footnotesize = size.footnote = size(-2)
597 size.small = size(-1)
598 size.normalsize = size.normal = size(0)
599 size.large = size(1)
600 size.Large = size(2)
601 size.LARGE = size(3)
602 size.huge = size(4)
603 size.Huge = size(5)
604 size.clear = attr.clearclass(size)
607 ###############################################################################
608 # texrunner
609 ###############################################################################
612 class _readpipe(threading.Thread):
613 """threaded reader of TeX/LaTeX output
614 - sets an event, when a specific string in the programs output is found
615 - sets an event, when the terminal ends"""
617 def __init__(self, pipe, expectqueue, gotevent, gotqueue, quitevent):
618 """initialize the reader
619 - pipe: file to be read from
620 - expectqueue: keeps the next InputMarker to be wait for
621 - gotevent: the "got InputMarker" event
622 - gotqueue: a queue containing the lines recieved from TeX/LaTeX
623 - quitevent: the "end of terminal" event"""
624 threading.Thread.__init__(self)
625 self.setDaemon(1) # don't care if the output might not be finished (nevertheless, it shouldn't happen)
626 self.pipe = pipe
627 self.expectqueue = expectqueue
628 self.gotevent = gotevent
629 self.gotqueue = gotqueue
630 self.quitevent = quitevent
631 self.expect = None
633 def run(self):
634 """thread routine"""
635 def _read():
636 # catch interupted system call errors while reading
637 while 1:
638 try:
639 return self.pipe.readline()
640 except IOError, e:
641 if e.errno != errno.EINTR:
642 raise
643 read = _read() # read, what comes in
644 try:
645 self.expect = self.expectqueue.get_nowait() # read, what should be expected
646 except Queue.Empty:
647 pass
648 while len(read):
649 # universal EOL handling (convert everything into unix like EOLs)
650 # XXX is this necessary on pipes?
651 read = read.replace("\r", "").replace("\n", "") + "\n"
652 self.gotqueue.put(read) # report, whats read
653 if self.expect is not None and read.find(self.expect) != -1:
654 self.gotevent.set() # raise the got event, when the output was expected (XXX: within a single line)
655 read = _read() # read again
656 try:
657 self.expect = self.expectqueue.get_nowait()
658 except Queue.Empty:
659 pass
660 # EOF reached
661 self.pipe.close()
662 if self.expect is not None and self.expect.find("PyXInputMarker") != -1:
663 raise RuntimeError("TeX/LaTeX finished unexpectedly")
664 self.quitevent.set()
667 class textbox(box.rect, canvas._canvas):
668 """basically a box.rect, but it contains a text created by the texrunner
669 - texrunner._text and texrunner.text return such an object
670 - _textbox instances can be inserted into a canvas
671 - the output is contained in a page of the dvifile available thru the texrunner"""
672 # TODO: shouldn't all boxes become canvases? how about inserts then?
674 def __init__(self, x, y, left, right, height, depth, finishdvi, attrs):
676 - finishdvi is a method to be called to get the dvicanvas
677 (e.g. the finishdvi calls the setdvicanvas method)
678 - attrs are fillstyles"""
679 self.left = left
680 self.right = right
681 self.width = left + right
682 self.height = height
683 self.depth = depth
684 self.texttrafo = trafo.scale(unit.scale["x"]).translated(x, y)
685 box.rect.__init__(self, x - left, y - depth, left + right, depth + height, abscenter = (left, depth))
686 canvas._canvas.__init__(self, attrs)
687 self.finishdvi = finishdvi
688 self.dvicanvas = None
689 self.insertdvicanvas = 0
691 def transform(self, *trafos):
692 if self.insertdvicanvas:
693 raise RuntimeError("can't apply transformation after dvicanvas was inserted")
694 box.rect.transform(self, *trafos)
695 for trafo in trafos:
696 self.texttrafo = trafo * self.texttrafo
698 def setdvicanvas(self, dvicanvas):
699 if self.dvicanvas is not None:
700 raise RuntimeError("multiple call to setdvicanvas")
701 self.dvicanvas = dvicanvas
703 def ensuredvicanvas(self):
704 if self.dvicanvas is None:
705 self.finishdvi()
706 assert self.dvicanvas is not None, "finishdvi is broken"
707 if not self.insertdvicanvas:
708 self.insert(self.dvicanvas, [self.texttrafo])
709 self.insertdvicanvas = 1
711 def marker(self, marker):
712 self.ensuredvicanvas()
713 return self.texttrafo.apply(*self.dvicanvas.markers[marker])
715 def processPS(self, file, writer, context, registry, bbox):
716 self.ensuredvicanvas()
717 abbox = bboxmodule.empty()
718 canvas._canvas.processPS(self, file, writer, context, registry, abbox)
719 bbox += box.rect.bbox(self)
721 def processPDF(self, file, writer, context, registry, bbox):
722 self.ensuredvicanvas()
723 abbox = bboxmodule.empty()
724 canvas._canvas.processPDF(self, file, writer, context, registry, abbox)
725 bbox += box.rect.bbox(self)
728 def _cleantmp(texrunner):
729 """get rid of temporary files
730 - function to be registered by atexit
731 - files contained in usefiles are kept"""
732 if texrunner.texruns: # cleanup while TeX is still running?
733 texrunner.expectqueue.put_nowait(None) # do not expect any output anymore
734 if texrunner.mode == "latex": # try to immediately quit from TeX or LaTeX
735 texrunner.texinput.write("\n\\catcode`\\@11\\relax\\@@end\n")
736 else:
737 texrunner.texinput.write("\n\\end\n")
738 texrunner.texinput.close() # close the input queue and
739 if not texrunner.waitforevent(texrunner.quitevent): # wait for finish of the output
740 return # didn't got a quit from TeX -> we can't do much more
741 texrunner.texruns = 0
742 texrunner.texdone = 1
743 for usefile in texrunner.usefiles:
744 extpos = usefile.rfind(".")
745 try:
746 os.rename(texrunner.texfilename + usefile[extpos:], usefile)
747 except OSError:
748 pass
749 for file in glob.glob("%s.*" % texrunner.texfilename) + ["%sNotes.bib" % texrunner.texfilename]:
750 try:
751 os.unlink(file)
752 except OSError:
753 pass
754 if texrunner.texdebug is not None:
755 try:
756 texrunner.texdebug.close()
757 texrunner.texdebug = None
758 except IOError:
759 pass
762 class _unset:
763 pass
765 class texrunner:
766 """TeX/LaTeX interface
767 - runs TeX/LaTeX expressions instantly
768 - checks TeX/LaTeX response
769 - the instance variable texmessage stores the last TeX
770 response as a string
771 - the instance variable texmessageparsed stores a parsed
772 version of texmessage; it should be empty after
773 texmessage.check was called, otherwise a TexResultError
774 is raised
775 - the instance variable errordebug controls the verbose
776 level of TexResultError"""
778 defaulttexmessagesstart = [texmessage.start]
779 defaulttexmessagesdocclass = [texmessage.load]
780 defaulttexmessagesbegindoc = [texmessage.load, texmessage.noaux]
781 defaulttexmessagesend = [texmessage.end, texmessage.fontwarning, texmessage.rerunwarning, texmessage.nobblwarning]
782 defaulttexmessagesdefaultpreamble = [texmessage.load]
783 defaulttexmessagesdefaultrun = [texmessage.loaddef, texmessage.graphicsload,
784 texmessage.fontwarning, texmessage.boxwarning, texmessage.packagewarning]
786 def __init__(self, mode="tex",
787 lfs="10pt",
788 docclass="article",
789 docopt=None,
790 usefiles=[],
791 waitfortex=config.getint("text", "waitfortex", 60),
792 showwaitfortex=config.getint("text", "showwaitfortex", 5),
793 texipc=config.getboolean("text", "texipc", 0),
794 texdebug=None,
795 dvidebug=0,
796 errordebug=1,
797 pyxgraphics=1,
798 texmessagesstart=[],
799 texmessagesdocclass=[],
800 texmessagesbegindoc=[],
801 texmessagesend=[],
802 texmessagesdefaultpreamble=[],
803 texmessagesdefaultrun=[]):
804 mode = mode.lower()
805 if mode != "tex" and mode != "latex":
806 raise ValueError("mode \"TeX\" or \"LaTeX\" expected")
807 self.mode = mode
808 self.lfs = lfs
809 self.docclass = docclass
810 self.docopt = docopt
811 self.usefiles = usefiles[:]
812 self.waitfortex = waitfortex
813 self.showwaitfortex = showwaitfortex
814 self.texipc = texipc
815 if texdebug is not None:
816 if texdebug[-4:] == ".tex":
817 self.texdebug = open(texdebug, "w")
818 else:
819 self.texdebug = open("%s.tex" % texdebug, "w")
820 else:
821 self.texdebug = None
822 self.dvidebug = dvidebug
823 self.errordebug = errordebug
824 self.pyxgraphics = pyxgraphics
825 self.texmessagesstart = texmessagesstart[:]
826 self.texmessagesdocclass = texmessagesdocclass[:]
827 self.texmessagesbegindoc = texmessagesbegindoc[:]
828 self.texmessagesend = texmessagesend[:]
829 self.texmessagesdefaultpreamble = texmessagesdefaultpreamble[:]
830 self.texmessagesdefaultrun = texmessagesdefaultrun[:]
832 self.texruns = 0
833 self.texdone = 0
834 self.preamblemode = 1
835 self.executeid = 0
836 self.page = 0
837 self.preambles = []
838 self.needdvitextboxes = [] # when texipc-mode off
839 self.dvifile = None
840 self.textboxesincluded = 0
841 savetempdir = tempfile.tempdir
842 tempfile.tempdir = os.curdir
843 self.texfilename = os.path.basename(tempfile.mktemp())
844 tempfile.tempdir = savetempdir
846 def waitforevent(self, event):
847 """waits verbosely with an timeout for an event
848 - observes an event while periodly while printing messages
849 - returns the status of the event (isSet)
850 - does not clear the event"""
851 if self.showwaitfortex:
852 waited = 0
853 hasevent = 0
854 while waited < self.waitfortex and not hasevent:
855 if self.waitfortex - waited > self.showwaitfortex:
856 event.wait(self.showwaitfortex)
857 waited += self.showwaitfortex
858 else:
859 event.wait(self.waitfortex - waited)
860 waited += self.waitfortex - waited
861 hasevent = event.isSet()
862 if not hasevent:
863 if waited < self.waitfortex:
864 warnings.warn("still waiting for %s after %i (of %i) seconds..." % (self.mode, waited, self.waitfortex), PyXTeXWarning)
865 else:
866 warnings.warn("the timeout of %i seconds expired and %s did not respond." % (waited, self.mode), PyXTeXWarning)
867 return hasevent
868 else:
869 event.wait(self.waitfortex)
870 return event.isSet()
872 def execute(self, expr, texmessages):
873 """executes expr within TeX/LaTeX
874 - if self.texruns is not yet set, TeX/LaTeX is initialized,
875 self.texruns is set and self.preamblemode is set
876 - the method must not be called, when self.texdone is already set
877 - expr should be a string or None
878 - when expr is None, TeX/LaTeX is stopped, self.texruns is unset and
879 self.texdone becomes set
880 - when self.preamblemode is set, the expr is passed directly to TeX/LaTeX
881 - when self.preamblemode is unset, the expr is passed to \ProcessPyXBox
882 - texmessages is a list of texmessage instances"""
883 if not self.texruns:
884 if self.texdebug is not None:
885 self.texdebug.write("%% PyX %s texdebug file\n" % version.version)
886 self.texdebug.write("%% mode: %s\n" % self.mode)
887 self.texdebug.write("%% date: %s\n" % time.asctime(time.localtime(time.time())))
888 for usefile in self.usefiles:
889 extpos = usefile.rfind(".")
890 try:
891 os.rename(usefile, self.texfilename + usefile[extpos:])
892 except OSError:
893 pass
894 texfile = open("%s.tex" % self.texfilename, "w") # start with filename -> creates dvi file with that name
895 texfile.write("\\relax%\n")
896 texfile.close()
897 if self.texipc:
898 ipcflag = " --ipc"
899 else:
900 ipcflag = ""
901 try:
902 self.texinput, self.texoutput = pycompat.popen4("%s%s %s" % (self.mode, ipcflag, self.texfilename), "t", 0)
903 except ValueError:
904 # workaround: bufsize = 0 is not supported on MS windows for os.open4 (Python 2.4 and below, i.e. where subprocess is not available)
905 self.texinput, self.texoutput = pycompat.popen4("%s%s %s" % (self.mode, ipcflag, self.texfilename), "t")
906 atexit.register(_cleantmp, self)
907 self.expectqueue = Queue.Queue(1) # allow for a single entry only -> keeps the next InputMarker to be wait for
908 self.gotevent = threading.Event() # keeps the got inputmarker event
909 self.gotqueue = Queue.Queue(0) # allow arbitrary number of entries
910 self.quitevent = threading.Event() # keeps for end of terminal event
911 self.readoutput = _readpipe(self.texoutput, self.expectqueue, self.gotevent, self.gotqueue, self.quitevent)
912 self.texruns = 1
913 oldpreamblemode = self.preamblemode
914 self.preamblemode = 1
915 self.readoutput.start()
916 self.execute("\\scrollmode\n\\raiseerror%\n" # switch to and check scrollmode
917 "\\def\\PyX{P\\kern-.3em\\lower.5ex\hbox{Y}\kern-.18em X}%\n" # just the PyX Logo
918 "\\gdef\\PyXBoxHAlign{0}%\n" # global PyXBoxHAlign (0.0-1.0) for the horizontal alignment, default to 0
919 "\\newbox\\PyXBox%\n" # PyXBox will contain the output
920 "\\newbox\\PyXBoxHAligned%\n" # PyXBox will contain the horizontal aligned output
921 "\\newdimen\\PyXDimenHAlignLT%\n" # PyXDimenHAlignLT/RT will contain the left/right extent
922 "\\newdimen\\PyXDimenHAlignRT%\n" +
923 _textattrspreamble + # insert preambles for textattrs macros
924 "\\long\\def\\ProcessPyXBox#1#2{%\n" # the ProcessPyXBox definition (#1 is expr, #2 is page number)
925 "\\setbox\\PyXBox=\\hbox{{#1}}%\n" # push expression into PyXBox
926 "\\PyXDimenHAlignLT=\\PyXBoxHAlign\\wd\\PyXBox%\n" # calculate the left/right extent
927 "\\PyXDimenHAlignRT=\\wd\\PyXBox%\n"
928 "\\advance\\PyXDimenHAlignRT by -\\PyXDimenHAlignLT%\n"
929 "\\gdef\\PyXBoxHAlign{0}%\n" # reset the PyXBoxHAlign to the default 0
930 "\\immediate\\write16{PyXBox:page=#2," # write page and extents of this box to stdout
931 "lt=\\the\\PyXDimenHAlignLT,"
932 "rt=\\the\\PyXDimenHAlignRT,"
933 "ht=\\the\\ht\\PyXBox,"
934 "dp=\\the\\dp\\PyXBox:}%\n"
935 "\\setbox\\PyXBoxHAligned=\\hbox{\\kern-\\PyXDimenHAlignLT\\box\\PyXBox}%\n" # align horizontally
936 "\\ht\\PyXBoxHAligned0pt%\n" # baseline alignment (hight to zero)
937 "{\\count0=80\\count1=121\\count2=88\\count3=#2\\shipout\\box\\PyXBoxHAligned}}%\n" # shipout PyXBox to Page 80.121.88.<page number>
938 "\\def\\PyXInput#1{\\immediate\\write16{PyXInputMarker:executeid=#1:}}%\n" # write PyXInputMarker to stdout
939 "\\def\\PyXMarker#1{\\hskip0pt\\special{PyX:marker #1}}%", # write PyXMarker special into the dvi-file
940 self.defaulttexmessagesstart + self.texmessagesstart)
941 os.remove("%s.tex" % self.texfilename)
942 if self.mode == "tex":
943 if self.lfs:
944 if not self.lfs.endswith(".lfs"):
945 self.lfs = "%s.lfs" % self.lfs
946 lfsfile = filelocator.open(self.lfs, [], "r")
947 lfsdef = lfsfile.read()
948 lfsfile.close()
949 self.execute(lfsdef, [])
950 self.execute("\\normalsize%\n", [])
951 self.execute("\\newdimen\\linewidth\\newdimen\\textwidth%\n", [])
952 elif self.mode == "latex":
953 if self.pyxgraphics:
954 pyxdef = filelocator.open("pyx.def", [], "rb")
955 pyxdef_filename = self.texfilename + ".pyxdef"
956 pyxdef_file = open(pyxdef_filename, "wb")
957 pyxdef_file.write(pyxdef.read())
958 pyxdef.close()
959 pyxdef_file.close()
960 pyxdef_filename_tex = os.path.abspath(pyxdef_filename).replace(os.sep, "/")
961 self.execute("\\makeatletter%\n"
962 "\\let\\saveProcessOptions=\\ProcessOptions%\n"
963 "\\def\\ProcessOptions{%\n"
964 "\\def\\Gin@driver{" + pyxdef_filename_tex + "}%\n"
965 "\\def\\c@lor@namefile{dvipsnam.def}%\n"
966 "\\saveProcessOptions}%\n"
967 "\\makeatother",
969 if self.docopt is not None:
970 self.execute("\\documentclass[%s]{%s}" % (self.docopt, self.docclass),
971 self.defaulttexmessagesdocclass + self.texmessagesdocclass)
972 else:
973 self.execute("\\documentclass{%s}" % self.docclass,
974 self.defaulttexmessagesdocclass + self.texmessagesdocclass)
975 self.preamblemode = oldpreamblemode
976 self.executeid += 1
977 if expr is not None: # TeX/LaTeX should process expr
978 self.expectqueue.put_nowait("PyXInputMarker:executeid=%i:" % self.executeid)
979 if self.preamblemode:
980 self.expr = ("%s%%\n" % expr +
981 "\\PyXInput{%i}%%\n" % self.executeid)
982 else:
983 self.page += 1
984 self.expr = ("\\ProcessPyXBox{%s%%\n}{%i}%%\n" % (expr, self.page) +
985 "\\PyXInput{%i}%%\n" % self.executeid)
986 else: # TeX/LaTeX should be finished
987 self.expectqueue.put_nowait("Transcript written on %s.log" % self.texfilename)
988 if self.mode == "latex":
989 self.expr = "\\end{document}%\n"
990 else:
991 self.expr = "\\end%\n"
992 if self.texdebug is not None:
993 self.texdebug.write(self.expr)
994 self.texinput.write(self.expr)
995 gotevent = self.waitforevent(self.gotevent)
996 self.gotevent.clear()
997 if expr is None and gotevent: # TeX/LaTeX should have finished
998 self.texruns = 0
999 self.texdone = 1
1000 self.texinput.close() # close the input queue and
1001 gotevent = self.waitforevent(self.quitevent) # wait for finish of the output
1002 try:
1003 self.texmessage = ""
1004 while 1:
1005 self.texmessage += self.gotqueue.get_nowait()
1006 except Queue.Empty:
1007 pass
1008 self.texmessage = self.texmessage.replace("\r\n", "\n").replace("\r", "\n")
1009 self.texmessageparsed = self.texmessage
1010 if gotevent:
1011 if expr is not None:
1012 texmessage.inputmarker.check(self)
1013 if not self.preamblemode:
1014 texmessage.pyxbox.check(self)
1015 texmessage.pyxpageout.check(self)
1016 texmessages = attr.mergeattrs(texmessages)
1017 for t in texmessages:
1018 t.check(self)
1019 keeptexmessageparsed = self.texmessageparsed
1020 texmessage.emptylines.check(self)
1021 if len(self.texmessageparsed):
1022 self.texmessageparsed = keeptexmessageparsed
1023 raise TexResultError("unhandled TeX response (might be an error)", self)
1024 else:
1025 raise TexResultError("TeX didn't respond as expected within the timeout period (%i seconds)." % self.waitfortex, self)
1027 def finishdvi(self, ignoretail=0):
1028 """finish TeX/LaTeX and read the dvifile
1029 - this method ensures that all textboxes can access their
1030 dvicanvas"""
1031 self.execute(None, self.defaulttexmessagesend + self.texmessagesend)
1032 dvifilename = "%s.dvi" % self.texfilename
1033 if not self.texipc:
1034 self.dvifile = dvifile.DVIfile(dvifilename, debug=self.dvidebug)
1035 page = 1
1036 for box in self.needdvitextboxes:
1037 box.setdvicanvas(self.dvifile.readpage([ord("P"), ord("y"), ord("X"), page, 0, 0, 0, 0, 0, 0], fontmap=box.fontmap))
1038 page += 1
1039 if not ignoretail and self.dvifile.readpage(None) is not None:
1040 raise RuntimeError("end of dvifile expected")
1041 self.dvifile = None
1042 self.needdvitextboxes = []
1044 def reset(self, reinit=0):
1045 "resets the tex runner to its initial state (upto its record to old dvi file(s))"
1046 if self.texruns:
1047 self.finishdvi()
1048 if self.texdebug is not None:
1049 self.texdebug.write("%s\n%% preparing restart of %s\n" % ("%"*80, self.mode))
1050 self.executeid = 0
1051 self.page = 0
1052 self.texdone = 0
1053 if reinit:
1054 self.preamblemode = 1
1055 for expr, texmessages in self.preambles:
1056 self.execute(expr, texmessages)
1057 if self.mode == "latex":
1058 self.execute("\\begin{document}", self.defaulttexmessagesbegindoc + self.texmessagesbegindoc)
1059 self.preamblemode = 0
1060 else:
1061 self.preambles = []
1062 self.preamblemode = 1
1064 def set(self, mode=_unset,
1065 lfs=_unset,
1066 docclass=_unset,
1067 docopt=_unset,
1068 usefiles=_unset,
1069 waitfortex=_unset,
1070 showwaitfortex=_unset,
1071 texipc=_unset,
1072 texdebug=_unset,
1073 dvidebug=_unset,
1074 errordebug=_unset,
1075 pyxgraphics=_unset,
1076 texmessagesstart=_unset,
1077 texmessagesdocclass=_unset,
1078 texmessagesbegindoc=_unset,
1079 texmessagesend=_unset,
1080 texmessagesdefaultpreamble=_unset,
1081 texmessagesdefaultrun=_unset):
1082 """provide a set command for TeX/LaTeX settings
1083 - TeX/LaTeX must not yet been started
1084 - especially needed for the defaultrunner, where no access to
1085 the constructor is available"""
1086 if self.texruns:
1087 raise RuntimeError("set not allowed -- TeX/LaTeX already started")
1088 if mode is not _unset:
1089 mode = mode.lower()
1090 if mode != "tex" and mode != "latex":
1091 raise ValueError("mode \"TeX\" or \"LaTeX\" expected")
1092 self.mode = mode
1093 if lfs is not _unset:
1094 self.lfs = lfs
1095 if docclass is not _unset:
1096 self.docclass = docclass
1097 if docopt is not _unset:
1098 self.docopt = docopt
1099 if usefiles is not _unset:
1100 self.usefiles = usefiles
1101 if waitfortex is not _unset:
1102 self.waitfortex = waitfortex
1103 if showwaitfortex is not _unset:
1104 self.showwaitfortex = showwaitfortex
1105 if texipc is not _unset:
1106 self.texipc = texipc
1107 if texdebug is not _unset:
1108 if self.texdebug is not None:
1109 self.texdebug.close()
1110 if texdebug[-4:] == ".tex":
1111 self.texdebug = open(texdebug, "w")
1112 else:
1113 self.texdebug = open("%s.tex" % texdebug, "w")
1114 if dvidebug is not _unset:
1115 self.dvidebug = dvidebug
1116 if errordebug is not _unset:
1117 self.errordebug = errordebug
1118 if pyxgraphics is not _unset:
1119 self.pyxgraphics = pyxgraphics
1120 if errordebug is not _unset:
1121 self.errordebug = errordebug
1122 if texmessagesstart is not _unset:
1123 self.texmessagesstart = texmessagesstart
1124 if texmessagesdocclass is not _unset:
1125 self.texmessagesdocclass = texmessagesdocclass
1126 if texmessagesbegindoc is not _unset:
1127 self.texmessagesbegindoc = texmessagesbegindoc
1128 if texmessagesend is not _unset:
1129 self.texmessagesend = texmessagesend
1130 if texmessagesdefaultpreamble is not _unset:
1131 self.texmessagesdefaultpreamble = texmessagesdefaultpreamble
1132 if texmessagesdefaultrun is not _unset:
1133 self.texmessagesdefaultrun = texmessagesdefaultrun
1135 def preamble(self, expr, texmessages=[]):
1136 r"""put something into the TeX/LaTeX preamble
1137 - in LaTeX, this is done before the \begin{document}
1138 (you might use \AtBeginDocument, when you're in need for)
1139 - it is not allowed to call preamble after calling the
1140 text method for the first time (for LaTeX this is needed
1141 due to \begin{document}; in TeX it is forced for compatibility
1142 (you should be able to switch from TeX to LaTeX, if you want,
1143 without breaking something)
1144 - preamble expressions must not create any dvi output
1145 - args might contain texmessage instances"""
1146 if self.texdone or not self.preamblemode:
1147 raise RuntimeError("preamble calls disabled due to previous text calls")
1148 texmessages = self.defaulttexmessagesdefaultpreamble + self.texmessagesdefaultpreamble + texmessages
1149 self.execute(expr, texmessages)
1150 self.preambles.append((expr, texmessages))
1152 PyXBoxPattern = re.compile(r"PyXBox:page=(?P<page>\d+),lt=(?P<lt>-?\d*((\d\.?)|(\.?\d))\d*)pt,rt=(?P<rt>-?\d*((\d\.?)|(\.?\d))\d*)pt,ht=(?P<ht>-?\d*((\d\.?)|(\.?\d))\d*)pt,dp=(?P<dp>-?\d*((\d\.?)|(\.?\d))\d*)pt:")
1154 def text(self, x, y, expr, textattrs=[], texmessages=[], fontmap=None):
1155 """create text by passing expr to TeX/LaTeX
1156 - returns a textbox containing the result from running expr thru TeX/LaTeX
1157 - the box center is set to x, y
1158 - *args may contain attr parameters, namely:
1159 - textattr instances
1160 - texmessage instances
1161 - trafo._trafo instances
1162 - style.fillstyle instances"""
1163 if expr is None:
1164 raise ValueError("None expression is invalid")
1165 if self.texdone:
1166 self.reset(reinit=1)
1167 first = 0
1168 if self.preamblemode:
1169 if self.mode == "latex":
1170 self.execute("\\begin{document}", self.defaulttexmessagesbegindoc + self.texmessagesbegindoc)
1171 self.preamblemode = 0
1172 first = 1
1173 textattrs = attr.mergeattrs(textattrs) # perform cleans
1174 attr.checkattrs(textattrs, [textattr, trafo.trafo_pt, style.fillstyle])
1175 trafos = attr.getattrs(textattrs, [trafo.trafo_pt])
1176 fillstyles = attr.getattrs(textattrs, [style.fillstyle])
1177 textattrs = attr.getattrs(textattrs, [textattr])
1178 # reverse loop over the merged textattrs (last is applied first)
1179 lentextattrs = len(textattrs)
1180 for i in range(lentextattrs):
1181 expr = textattrs[lentextattrs-1-i].apply(expr)
1182 try:
1183 self.execute(expr, self.defaulttexmessagesdefaultrun + self.texmessagesdefaultrun + texmessages)
1184 except TexResultError, e:
1185 warnings.warn("We try to finish the dvi due to an unhandled tex error", PyXTeXWarning)
1186 try:
1187 self.finishdvi(ignoretail=1)
1188 except TexResultError:
1189 pass
1190 raise e
1191 if self.texipc:
1192 if first:
1193 self.dvifile = dvifile.DVIfile("%s.dvi" % self.texfilename, debug=self.dvidebug)
1194 match = self.PyXBoxPattern.search(self.texmessage)
1195 if not match or int(match.group("page")) != self.page:
1196 raise TexResultError("box extents not found", self)
1197 left, right, height, depth = [float(xxx)*72/72.27*unit.x_pt for xxx in match.group("lt", "rt", "ht", "dp")]
1198 box = textbox(x, y, left, right, height, depth, self.finishdvi, fillstyles)
1199 for t in trafos:
1200 box.reltransform(t) # TODO: should trafos really use reltransform???
1201 # this is quite different from what we do elsewhere!!!
1202 # see https://sourceforge.net/mailarchive/forum.php?thread_id=9137692&forum_id=23700
1203 if self.texipc:
1204 box.setdvicanvas(self.dvifile.readpage([ord("P"), ord("y"), ord("X"), self.page, 0, 0, 0, 0, 0, 0], fontmap=fontmap))
1205 else:
1206 box.fontmap = fontmap
1207 self.needdvitextboxes.append(box)
1208 return box
1210 def text_pt(self, x, y, expr, *args, **kwargs):
1211 return self.text(x * unit.t_pt, y * unit.t_pt, expr, *args, **kwargs)
1213 PyXVariableBoxPattern = re.compile(r"PyXVariableBox:page=(?P<page>\d+),par=(?P<par>\d+),prevgraf=(?P<prevgraf>\d+):")
1215 def textboxes(self, text, pageshapes):
1216 # this is some experimental code to put text into several boxes
1217 # while the bounding shape changes from box to box (rectangles only)
1218 # first we load sev.tex
1219 if not self.textboxesincluded:
1220 self.execute(r"\input textboxes.tex", [texmessage.load])
1221 self.textboxesincluded = 1
1222 # define page shapes
1223 pageshapes_str = "\\hsize=%.5ftruept%%\n\\vsize=%.5ftruept%%\n" % (72.27/72*unit.topt(pageshapes[0][0]), 72.27/72*unit.topt(pageshapes[0][1]))
1224 pageshapes_str += "\\lohsizes={%\n"
1225 for hsize, vsize in pageshapes[1:]:
1226 pageshapes_str += "{\\global\\hsize=%.5ftruept}%%\n" % (72.27/72*unit.topt(hsize))
1227 pageshapes_str += "{\\relax}%\n}%\n"
1228 pageshapes_str += "\\lovsizes={%\n"
1229 for hsize, vsize in pageshapes[1:]:
1230 pageshapes_str += "{\\global\\vsize=%.5ftruept}%%\n" % (72.27/72*unit.topt(vsize))
1231 pageshapes_str += "{\\relax}%\n}%\n"
1232 page = 0
1233 parnos = []
1234 parshapes = []
1235 loop = 0
1236 while 1:
1237 self.execute(pageshapes_str, [])
1238 parnos_str = "}{".join(parnos)
1239 if parnos_str:
1240 parnos_str = "{%s}" % parnos_str
1241 parnos_str = "\\parnos={%s{\\relax}}%%\n" % parnos_str
1242 self.execute(parnos_str, [])
1243 parshapes_str = "\\parshapes={%%\n%s%%\n{\\relax}%%\n}%%\n" % "%\n".join(parshapes)
1244 self.execute(parshapes_str, [])
1245 self.execute("\\global\\count0=1%%\n"
1246 "\\global\\parno=0%%\n"
1247 "\\global\\myprevgraf=0%%\n"
1248 "\\global\\showprevgraf=0%%\n"
1249 "\\global\\outputtype=0%%\n"
1250 "\\global\\leastcost=10000000%%\n"
1251 "%s%%\n"
1252 "\\vfill\\supereject%%\n" % text, [texmessage.ignore])
1253 if self.texipc:
1254 if self.dvifile is None:
1255 self.dvifile = dvifile.DVIfile("%s.dvi" % self.texfilename, debug=self.dvidebug)
1256 else:
1257 raise RuntimeError("textboxes currently needs texipc")
1258 lastparnos = parnos
1259 parnos = []
1260 lastparshapes = parshapes
1261 parshapes = []
1262 pages = 0
1263 lastpar = prevgraf = -1
1264 m = self.PyXVariableBoxPattern.search(self.texmessage)
1265 while m:
1266 pages += 1
1267 page = int(m.group("page"))
1268 assert page == pages
1269 par = int(m.group("par"))
1270 prevgraf = int(m.group("prevgraf"))
1271 if page <= len(pageshapes):
1272 width = 72.27/72*unit.topt(pageshapes[page-1][0])
1273 else:
1274 width = 72.27/72*unit.topt(pageshapes[-1][0])
1275 if page < len(pageshapes):
1276 nextwidth = 72.27/72*unit.topt(pageshapes[page][0])
1277 else:
1278 nextwidth = 72.27/72*unit.topt(pageshapes[-1][0])
1280 if par != lastpar:
1281 # a new paragraph is to be broken
1282 parnos.append(str(par))
1283 parshape = " 0pt ".join(["%.5ftruept" % width for i in range(prevgraf)])
1284 if len(parshape):
1285 parshape = " 0pt " + parshape
1286 parshapes.append("{\\parshape %i%s 0pt %.5ftruept}" % (prevgraf + 1, parshape, nextwidth))
1287 elif prevgraf == lastprevgraf:
1288 pass
1289 else:
1290 # we have to append the breaking of the previous paragraph
1291 oldparshape = " ".join(parshapes[-1].split(' ')[2:2+2*lastprevgraf])
1292 oldparshape = oldparshape.split('}')[0]
1293 if len(parshape):
1294 oldparshape = " " + oldparshape
1295 parshape = " 0pt ".join(["%.5ftruept" % width for i in range(prevgraf - lastprevgraf)])
1296 if len(parshape):
1297 parshape = " 0pt " + parshape
1298 else:
1299 parshape = " "
1300 parshapes[-1] = "{\\parshape %i%s%s 0pt %.5ftruept}" % (prevgraf + 1, oldparshape, parshape, nextwidth)
1301 lastpar = par
1302 lastprevgraf = prevgraf
1303 nextpos = m.end()
1304 m = self.PyXVariableBoxPattern.search(self.texmessage, nextpos)
1305 result = []
1306 for i in range(pages):
1307 result.append(self.dvifile.readpage([i + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]))
1308 if parnos == lastparnos and parshapes == lastparshapes:
1309 return result
1310 loop += 1
1311 if loop > 100:
1312 raise TexResultError("Too many loops in textboxes ", texrunner)
1315 # the module provides an default texrunner and methods for direct access
1316 defaulttexrunner = texrunner()
1317 reset = defaulttexrunner.reset
1318 set = defaulttexrunner.set
1319 preamble = defaulttexrunner.preamble
1320 text = defaulttexrunner.text
1321 text_pt = defaulttexrunner.text_pt
1323 def escapestring(s, replace={" ": "~",
1324 "$": "\\$",
1325 "&": "\\&",
1326 "#": "\\#",
1327 "_": "\\_",
1328 "%": "\\%",
1329 "^": "\\string^",
1330 "~": "\\string~",
1331 "<": "{$<$}",
1332 ">": "{$>$}",
1333 "{": "{$\{$}",
1334 "}": "{$\}$}",
1335 "\\": "{$\setminus$}",
1336 "|": "{$\mid$}"}):
1337 "escape all ascii characters such that they are printable by TeX/LaTeX"
1338 i = 0
1339 while i < len(s):
1340 if not 32 <= ord(s[i]) < 127:
1341 raise ValueError("escapestring function handles ascii strings only")
1342 c = s[i]
1343 try:
1344 r = replace[c]
1345 except KeyError:
1346 i += 1
1347 else:
1348 s = s[:i] + r + s[i+1:]
1349 i += len(r)
1350 return s