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
, functools
, glob
, os
, threading
, queue
, re
, tempfile
, atexit
, time
, warnings
25 from . import config
, unit
, box
, canvas
, trafo
, version
, attr
, style
, pycompat
, path
26 from pyx
.dvi
import dvifile
27 from . import bbox
as bboxmodule
29 class PyXTeXWarning(UserWarning): pass
30 warnings
.filterwarnings("always", category
=PyXTeXWarning
)
32 ###############################################################################
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 functools
.reduce(lambda x
, y
: "%s %s\n" % (x
,y
), firstlines
, "").rstrip())
71 self
.description
= description
74 return self
.description
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
)
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
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
):
124 s1
, s2
= texrunner
.texmessageparsed
.split("No file %s.%s." % (texrunner
.texfilename
, self
.fileending
), 1)
125 texrunner
.texmessageparsed
= s1
+ s2
126 except (IndexError, ValueError):
128 s1
, s2
= texrunner
.texmessageparsed
.split("No file %s%s%s.%s." % (os
.curdir
,
130 texrunner
.texfilename
,
132 texrunner
.texmessageparsed
= s1
+ s2
133 except (IndexError, ValueError):
137 class _texmessageinputmarker(texmessage
):
138 """validates the PyXInputMarker"""
140 __implements__
= _Itexmessage
142 def check(self
, texrunner
):
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():]
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
):
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)
188 texrunner.texmessageparsed = (texrunner.texmessageparsed[:m.start()] + texrunner.texmessageparsed[m.end():]).strip()
190 # check for "(see the transcript
file for additional information
)"
192 s1, s2 = texrunner.texmessageparsed.split("(see the transcript
file for additional information
)", 1)
193 texrunner.texmessageparsed = (s1 + s2).strip()
194 except (IndexError, ValueError):
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)
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():]
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
."
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
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"""
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]:
265 elif inquote and c == quotes[1]:
272 if level > highestlevel:
274 if level <= maxlevel:
278 if level == 0 and highestlevel > 0:
281 def check(self, texrunner):
282 search = self.baselevels(texrunner.texmessageparsed)
284 if search is not None:
285 m = self.pattern.search(search)
287 filename = m.group("filename").replace("\n", "")
289 additional = m.group("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()])
296 res.append(search[:m.end()])
297 search = search[m.end():]
298 m = self.pattern.search(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):
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):
327 class _texmessageignore(_texmessageload):
328 """validates any TeX/LaTeX response
329 - this might be used, when the expression is ok, but no suitable texmessage
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()
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)
377 texrunner.texmessageparsed = texrunner.texmessageparsed[:m.start()] + texrunner.texmessageparsed[m.end():]
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 ###############################################################################
392 ###############################################################################
394 _textattrspreamble = ""
397 "a textattr defines a apply method, which modifies a (La)TeX expression"
399 class _localattr: pass
401 _textattrspreamble += r"""\gdef\PyXFlushHAlign{0}%
403 \leftskip=0pt plus \PyXFlushHAlign fil%
404 \rightskip=0pt plus 1fil%
405 \advance\rightskip0pt plus -\PyXFlushHAlign fil%
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(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
):
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
):
479 def apply(self
, expr
):
480 return r
"\phantom{%s}" % expr
483 clearphantom
= attr
.clearclass(_phantom
)
486 _textattrspreamble
+= "\\newbox\\PyXBoxVBox%\n\\newdimen\\PyXDimenVBox%\n"
488 class parbox_pt(attr
.sortbeforeexclusiveattr
, textattr
):
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
)
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
):
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
):
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
]
587 raise IndexError("index out of sizelist range")
591 def apply(self
, expr
):
592 return r
"\%s{}%s" % (self
.size
, expr
)
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)
604 size
.clear
= attr
.clearclass(size
)
607 ###############################################################################
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)
627 self
.expectqueue
= expectqueue
628 self
.gotevent
= gotevent
629 self
.gotqueue
= gotqueue
630 self
.quitevent
= quitevent
636 # catch interupted system call errors while reading
639 return self
.pipe
.readline()
641 if e
.errno
!= errno
.EINTR
:
643 read
= _read() # read, what comes in
645 self
.expect
= self
.expectqueue
.get_nowait() # read, what should be expected
649 # universal EOL handling (convert everything into unix like EOLs)
650 # XXX is this necessary on pipes?
651 read
= read
.replace(b
"\r", b
"").replace(b
"\n", b
"") + b
"\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
657 self
.expect
= self
.expectqueue
.get_nowait()
662 if self
.expect
is not None and self
.expect
.find(b
"PyXInputMarker") != -1:
663 raise RuntimeError("TeX/LaTeX finished unexpectedly")
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"""
681 self
.width
= left
+ right
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
= False
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
)
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:
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
= True
711 def marker(self
, marker
):
712 self
.ensuredvicanvas()
713 return self
.texttrafo
.apply(*self
.dvicanvas
.markers
[marker
])
716 self
.ensuredvicanvas()
717 textpath
= path
.path()
718 for item
in self
.dvicanvas
.items
:
720 textpath
+= item
.textpath()
721 except AttributeError:
722 # ignore color settings etc.
724 return textpath
.transformed(self
.texttrafo
)
726 def processPS(self
, file, writer
, context
, registry
, bbox
):
727 self
.ensuredvicanvas()
728 abbox
= bboxmodule
.empty()
729 canvas
.canvas
.processPS(self
, file, writer
, context
, registry
, abbox
)
730 bbox
+= box
.rect
.bbox(self
)
732 def processPDF(self
, file, writer
, context
, registry
, bbox
):
733 self
.ensuredvicanvas()
734 abbox
= bboxmodule
.empty()
735 canvas
.canvas
.processPDF(self
, file, writer
, context
, registry
, abbox
)
736 bbox
+= box
.rect
.bbox(self
)
739 def _cleantmp(texrunner
):
740 """get rid of temporary files
741 - function to be registered by atexit
742 - files contained in usefiles are kept"""
743 if texrunner
.texruns
: # cleanup while TeX is still running?
744 texrunner
.expectqueue
.put_nowait(None) # do not expect any output anymore
745 if texrunner
.mode
== "latex": # try to immediately quit from TeX or LaTeX
746 texrunner
.texinput
.write(b
"\n\\catcode`\\@11\\relax\\@@end\n")
748 texrunner
.texinput
.write(b
"\n\\end\n")
749 texrunner
.texinput
.close() # close the input queue and
750 if not texrunner
.waitforevent(texrunner
.quitevent
): # wait for finish of the output
751 return # didn't got a quit from TeX -> we can't do much more
752 texrunner
.texruns
= 0
753 texrunner
.texdone
= True
754 for usefile
in texrunner
.usefiles
:
755 extpos
= usefile
.rfind(".")
757 os
.rename(texrunner
.texfilename
+ usefile
[extpos
:], usefile
)
760 for file in glob
.glob("%s.*" % texrunner
.texfilename
) + ["%sNotes.bib" % texrunner
.texfilename
]:
773 def __init__(self
, *files
):
776 def write(self
, data
):
777 for file in self
.files
:
781 for file in self
.files
:
786 """TeX/LaTeX interface
787 - runs TeX/LaTeX expressions instantly
788 - checks TeX/LaTeX response
789 - the instance variable texmessage stores the last TeX
791 - the instance variable texmessageparsed stores a parsed
792 version of texmessage; it should be empty after
793 texmessage.check was called, otherwise a TexResultError
795 - the instance variable errordebug controls the verbose
796 level of TexResultError"""
798 defaulttexmessagesstart
= [texmessage
.start
]
799 defaulttexmessagesdocclass
= [texmessage
.load
]
800 defaulttexmessagesbegindoc
= [texmessage
.load
, texmessage
.noaux
]
801 defaulttexmessagesend
= [texmessage
.end
, texmessage
.fontwarning
, texmessage
.rerunwarning
, texmessage
.nobblwarning
]
802 defaulttexmessagesdefaultpreamble
= [texmessage
.load
]
803 defaulttexmessagesdefaultrun
= [texmessage
.loaddef
, texmessage
.graphicsload
,
804 texmessage
.fontwarning
, texmessage
.boxwarning
, texmessage
.packagewarning
]
806 def __init__(self
, mode
="tex",
812 waitfortex
=config
.getint("text", "waitfortex", 60),
813 showwaitfortex
=config
.getint("text", "showwaitfortex", 5),
814 texipc
=config
.getboolean("text", "texipc", 0),
820 texmessagesdocclass
=[],
821 texmessagesbegindoc
=[],
823 texmessagesdefaultpreamble
=[],
824 texmessagesdefaultrun
=[]):
826 if mode
!= "tex" and mode
!= "latex":
827 raise ValueError("mode \"TeX\" or \"LaTeX\" expected")
830 self
.docclass
= docclass
833 self
.usefiles
= usefiles
[:]
834 self
.waitfortex
= waitfortex
835 self
.showwaitfortex
= showwaitfortex
837 self
.texdebug
= texdebug
838 self
.dvidebug
= dvidebug
839 self
.errordebug
= errordebug
840 self
.pyxgraphics
= pyxgraphics
841 self
.texmessagesstart
= texmessagesstart
[:]
842 self
.texmessagesdocclass
= texmessagesdocclass
[:]
843 self
.texmessagesbegindoc
= texmessagesbegindoc
[:]
844 self
.texmessagesend
= texmessagesend
[:]
845 self
.texmessagesdefaultpreamble
= texmessagesdefaultpreamble
[:]
846 self
.texmessagesdefaultrun
= texmessagesdefaultrun
[:]
850 self
.preamblemode
= True
854 self
.needdvitextboxes
= [] # when texipc-mode off
856 self
.textboxesincluded
= 0
857 savetempdir
= tempfile
.tempdir
858 tempfile
.tempdir
= os
.curdir
859 self
.texfilename
= os
.path
.basename(tempfile
.mktemp())
860 tempfile
.tempdir
= savetempdir
862 def waitforevent(self
, event
):
863 """waits verbosely with an timeout for an event
864 - observes an event while periodly while printing messages
865 - returns the status of the event (isSet)
866 - does not clear the event"""
867 if self
.showwaitfortex
:
870 while waited
< self
.waitfortex
and not hasevent
:
871 if self
.waitfortex
- waited
> self
.showwaitfortex
:
872 event
.wait(self
.showwaitfortex
)
873 waited
+= self
.showwaitfortex
875 event
.wait(self
.waitfortex
- waited
)
876 waited
+= self
.waitfortex
- waited
877 hasevent
= event
.isSet()
879 if waited
< self
.waitfortex
:
880 warnings
.warn("still waiting for %s after %i (of %i) seconds..." % (self
.mode
, waited
, self
.waitfortex
), PyXTeXWarning
)
882 warnings
.warn("the timeout of %i seconds expired and %s did not respond." % (waited
, self
.mode
), PyXTeXWarning
)
885 event
.wait(self
.waitfortex
)
888 def execute(self
, expr
, texmessages
):
889 """executes expr within TeX/LaTeX
890 - if self.texruns is not yet set, TeX/LaTeX is initialized,
891 self.texruns is set and self.preamblemode is set
892 - the method must not be called, when self.texdone is already set
893 - expr should be a string or None
894 - when expr is None, TeX/LaTeX is stopped, self.texruns is unset and
895 self.texdone becomes set
896 - when self.preamblemode is set, the expr is passed directly to TeX/LaTeX
897 - when self.preamblemode is unset, the expr is passed to \ProcessPyXBox
898 - texmessages is a list of texmessage instances"""
900 for usefile
in self
.usefiles
:
901 extpos
= usefile
.rfind(".")
903 os
.rename(usefile
, self
.texfilename
+ usefile
[extpos
:])
906 with
open("%s.tex" % self
.texfilename
, "w") as texfile
:
907 # start with filename -> creates dvi file with that name
908 texfile
.write("\\relax%\n")
913 self
.texinput
, self
.texoutput
= pycompat
.popen4("%s%s %s" % (self
.mode
, ipcflag
, self
.texfilename
), "t", 0)
915 self
.texinput
= Tee(self
.texinput
, open(self
.texdebug
, "wb"))
916 atexit
.register(_cleantmp
, self
)
917 self
.expectqueue
= queue
.Queue(1) # allow for a single entry only -> keeps the next InputMarker to be wait for
918 self
.gotevent
= threading
.Event() # keeps the got inputmarker event
919 self
.gotqueue
= queue
.Queue(0) # allow arbitrary number of entries
920 self
.quitevent
= threading
.Event() # keeps for end of terminal event
921 self
.readoutput
= _readpipe(self
.texoutput
, self
.expectqueue
, self
.gotevent
, self
.gotqueue
, self
.quitevent
)
923 oldpreamblemode
= self
.preamblemode
924 self
.preamblemode
= True
925 self
.readoutput
.start()
926 self
.execute("\\scrollmode\n\\raiseerror%\n" # switch to and check scrollmode
927 "\\def\\PyX{P\\kern-.3em\\lower.5ex\hbox{Y}\kern-.18em X}%\n" # just the PyX Logo
928 "\\gdef\\PyXBoxHAlign{0}%\n" # global PyXBoxHAlign (0.0-1.0) for the horizontal alignment, default to 0
929 "\\newbox\\PyXBox%\n" # PyXBox will contain the output
930 "\\newbox\\PyXBoxHAligned%\n" # PyXBox will contain the horizontal aligned output
931 "\\newdimen\\PyXDimenHAlignLT%\n" # PyXDimenHAlignLT/RT will contain the left/right extent
932 "\\newdimen\\PyXDimenHAlignRT%\n" +
933 _textattrspreamble
+ # insert preambles for textattrs macros
934 "\\long\\def\\ProcessPyXBox#1#2{%\n" # the ProcessPyXBox definition (#1 is expr, #2 is page number)
935 "\\setbox\\PyXBox=\\hbox{{#1}}%\n" # push expression into PyXBox
936 "\\PyXDimenHAlignLT=\\PyXBoxHAlign\\wd\\PyXBox%\n" # calculate the left/right extent
937 "\\PyXDimenHAlignRT=\\wd\\PyXBox%\n"
938 "\\advance\\PyXDimenHAlignRT by -\\PyXDimenHAlignLT%\n"
939 "\\gdef\\PyXBoxHAlign{0}%\n" # reset the PyXBoxHAlign to the default 0
940 "\\immediate\\write16{PyXBox:page=#2," # write page and extents of this box to stdout
941 "lt=\\the\\PyXDimenHAlignLT,"
942 "rt=\\the\\PyXDimenHAlignRT,"
943 "ht=\\the\\ht\\PyXBox,"
944 "dp=\\the\\dp\\PyXBox:}%\n"
945 "\\setbox\\PyXBoxHAligned=\\hbox{\\kern-\\PyXDimenHAlignLT\\box\\PyXBox}%\n" # align horizontally
946 "\\ht\\PyXBoxHAligned0pt%\n" # baseline alignment (hight to zero)
947 "{\\count0=80\\count1=121\\count2=88\\count3=#2\\shipout\\box\\PyXBoxHAligned}}%\n" # shipout PyXBox to Page 80.121.88.<page number>
948 "\\def\\PyXInput#1{\\immediate\\write16{PyXInputMarker:executeid=#1:}}%\n" # write PyXInputMarker to stdout
949 "\\def\\PyXMarker#1{\\hskip0pt\\special{PyX:marker #1}}%", # write PyXMarker special into the dvi-file
950 self
.defaulttexmessagesstart
+ self
.texmessagesstart
)
951 os
.remove("%s.tex" % self
.texfilename
)
952 if self
.mode
== "tex":
954 if not self
.lfs
.endswith(".lfs"):
955 self
.lfs
= "%s.lfs" % self
.lfs
956 with config
.open(self
.lfs
, []) as lfsfile
:
957 lfsdef
= lfsfile
.read().decode("ascii")
958 self
.execute(lfsdef
, [])
959 self
.execute("\\normalsize%\n", [])
960 self
.execute("\\newdimen\\linewidth\\newdimen\\textwidth%\n", [])
961 elif self
.mode
== "latex":
963 pyxdef_filename
= self
.texfilename
+ ".pyx.def"
964 with config
.open("pyx.def", []) as pyxdef
, open(pyxdef_filename
, "wb") as pyxdef_file
:
965 pyxdef_file
.write(pyxdef
.read())
966 pyxdef_filename_tex
= os
.path
.abspath(pyxdef_filename
).replace(os
.sep
, "/")
967 self
.execute("\\makeatletter%\n"
968 "\\let\\saveProcessOptions=\\ProcessOptions%\n"
969 "\\def\\ProcessOptions{%\n"
970 "\\def\\Gin@driver{" + pyxdef_filename_tex
+ "}%\n"
971 "\\def\\c@lor@namefile{dvipsnam.def}%\n"
972 "\\saveProcessOptions}%\n"
975 if self
.docopt
is not None:
976 self
.execute("\\documentclass[%s]{%s}" % (self
.docopt
, self
.docclass
),
977 self
.defaulttexmessagesdocclass
+ self
.texmessagesdocclass
)
979 self
.execute("\\documentclass{%s}" % self
.docclass
,
980 self
.defaulttexmessagesdocclass
+ self
.texmessagesdocclass
)
981 self
.preamblemode
= oldpreamblemode
983 if expr
is not None: # TeX/LaTeX should process expr
984 self
.expectqueue
.put_nowait(("PyXInputMarker:executeid=%i:" % self
.executeid
).encode(self
.texenc
))
985 if self
.preamblemode
:
986 self
.expr
= ("%s%%\n" % expr
+
987 "\\PyXInput{%i}%%\n" % self
.executeid
)
990 self
.expr
= ("\\ProcessPyXBox{%s%%\n}{%i}%%\n" % (expr
, self
.page
) +
991 "\\PyXInput{%i}%%\n" % self
.executeid
)
992 else: # TeX/LaTeX should be finished
993 self
.expectqueue
.put_nowait(("Transcript written on %s.log" % self
.texfilename
).encode(self
.texenc
))
994 if self
.mode
== "latex":
995 self
.expr
= "\\end{document}%\n"
997 self
.expr
= "\\end%\n"
998 self
.texinput
.write(self
.expr
.encode(self
.texenc
))
999 gotevent
= self
.waitforevent(self
.gotevent
)
1000 self
.gotevent
.clear()
1001 if expr
is None and gotevent
: # TeX/LaTeX should have finished
1004 self
.texinput
.close() # close the input queue and
1005 gotevent
= self
.waitforevent(self
.quitevent
) # wait for finish of the output
1007 self
.texmessage
= ""
1009 self
.texmessage
+= self
.gotqueue
.get_nowait().decode(self
.texenc
)
1012 self
.texmessage
= self
.texmessage
.replace("\r\n", "\n").replace("\r", "\n")
1013 self
.texmessageparsed
= self
.texmessage
1015 if expr
is not None:
1016 texmessage
.inputmarker
.check(self
)
1017 if not self
.preamblemode
:
1018 texmessage
.pyxbox
.check(self
)
1019 texmessage
.pyxpageout
.check(self
)
1020 texmessages
= attr
.mergeattrs(texmessages
)
1021 for t
in texmessages
:
1023 keeptexmessageparsed
= self
.texmessageparsed
1024 texmessage
.emptylines
.check(self
)
1025 if len(self
.texmessageparsed
):
1026 self
.texmessageparsed
= keeptexmessageparsed
1027 raise TexResultError("unhandled TeX response (might be an error)", self
)
1029 raise TexResultError("TeX didn't respond as expected within the timeout period (%i seconds)." % self
.waitfortex
, self
)
1031 def finishdvi(self
, ignoretail
=0):
1032 """finish TeX/LaTeX and read the dvifile
1033 - this method ensures that all textboxes can access their
1035 self
.execute(None, self
.defaulttexmessagesend
+ self
.texmessagesend
)
1036 dvifilename
= "%s.dvi" % self
.texfilename
1038 self
.dvifile
= dvifile
.DVIfile(dvifilename
, debug
=self
.dvidebug
)
1040 for box
in self
.needdvitextboxes
:
1041 box
.setdvicanvas(self
.dvifile
.readpage([ord("P"), ord("y"), ord("X"), page
, 0, 0, 0, 0, 0, 0], fontmap
=box
.fontmap
, singlecharmode
=box
.singlecharmode
))
1043 if not ignoretail
and self
.dvifile
.readpage(None) is not None:
1044 raise RuntimeError("end of dvifile expected")
1046 self
.needdvitextboxes
= []
1048 def reset(self
, reinit
=0):
1049 "resets the tex runner to its initial state (upto its record to old dvi file(s))"
1054 self
.texdone
= False
1056 self
.preamblemode
= True
1057 for expr
, texmessages
in self
.preambles
:
1058 self
.execute(expr
, texmessages
)
1059 if self
.mode
== "latex":
1060 self
.execute("\\begin{document}", self
.defaulttexmessagesbegindoc
+ self
.texmessagesbegindoc
)
1061 self
.preamblemode
= False
1064 self
.preamblemode
= True
1066 def set(self
, mode
=_unset
,
1073 showwaitfortex
=_unset
,
1079 texmessagesstart
=_unset
,
1080 texmessagesdocclass
=_unset
,
1081 texmessagesbegindoc
=_unset
,
1082 texmessagesend
=_unset
,
1083 texmessagesdefaultpreamble
=_unset
,
1084 texmessagesdefaultrun
=_unset
):
1085 """provide a set command for TeX/LaTeX settings
1086 - TeX/LaTeX must not yet been started
1087 - especially needed for the defaultrunner, where no access to
1088 the constructor is available"""
1090 raise RuntimeError("set not allowed -- TeX/LaTeX already started")
1091 if mode
is not _unset
:
1093 if mode
!= "tex" and mode
!= "latex":
1094 raise ValueError("mode \"TeX\" or \"LaTeX\" expected")
1096 if lfs
is not _unset
:
1098 if docclass
is not _unset
:
1099 self
.docclass
= docclass
1100 if docopt
is not _unset
:
1101 self
.docopt
= docopt
1102 if texenc
is not _unset
:
1103 self
.texenc
= texenc
1104 if usefiles
is not _unset
:
1105 self
.usefiles
= usefiles
1106 if waitfortex
is not _unset
:
1107 self
.waitfortex
= waitfortex
1108 if showwaitfortex
is not _unset
:
1109 self
.showwaitfortex
= showwaitfortex
1110 if texipc
is not _unset
:
1111 self
.texipc
= texipc
1112 if texdebug
is not _unset
:
1113 self
.texdebug
= texdebug
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, singlecharmode
=False):
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"""
1164 raise ValueError("None expression is invalid")
1166 self
.reset(reinit
=1)
1168 if self
.preamblemode
:
1169 if self
.mode
== "latex":
1170 self
.execute("\\begin{document}", self
.defaulttexmessagesbegindoc
+ self
.texmessagesbegindoc
)
1171 self
.preamblemode
= False
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
)
1183 self
.execute(expr
, self
.defaulttexmessagesdefaultrun
+ self
.texmessagesdefaultrun
+ texmessages
)
1184 except TexResultError
as e
:
1185 warnings
.warn("We try to finish the dvi due to an unhandled tex error", PyXTeXWarning
)
1187 self
.finishdvi(ignoretail
=1)
1188 except TexResultError
:
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
)
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
1204 box
.setdvicanvas(self
.dvifile
.readpage([ord("P"), ord("y"), ord("X"), self
.page
, 0, 0, 0, 0, 0, 0], fontmap
=fontmap
, singlecharmode
=singlecharmode
))
1206 box
.fontmap
= fontmap
1207 box
.singlecharmode
= singlecharmode
1208 self
.needdvitextboxes
.append(box
)
1211 def text_pt(self
, x
, y
, expr
, *args
, **kwargs
):
1212 return self
.text(x
* unit
.t_pt
, y
* unit
.t_pt
, expr
, *args
, **kwargs
)
1214 PyXVariableBoxPattern
= re
.compile(r
"PyXVariableBox:page=(?P<page>\d+),par=(?P<par>\d+),prevgraf=(?P<prevgraf>\d+):")
1216 def textboxes(self
, text
, pageshapes
):
1217 # this is some experimental code to put text into several boxes
1218 # while the bounding shape changes from box to box (rectangles only)
1219 # first we load sev.tex
1220 if not self
.textboxesincluded
:
1221 self
.execute(r
"\input textboxes.tex", [texmessage
.load
])
1222 self
.textboxesincluded
= True
1223 # define page shapes
1224 pageshapes_str
= "\\hsize=%.5ftruept%%\n\\vsize=%.5ftruept%%\n" % (72.27/72*unit
.topt(pageshapes
[0][0]), 72.27/72*unit
.topt(pageshapes
[0][1]))
1225 pageshapes_str
+= "\\lohsizes={%\n"
1226 for hsize
, vsize
in pageshapes
[1:]:
1227 pageshapes_str
+= "{\\global\\hsize=%.5ftruept}%%\n" % (72.27/72*unit
.topt(hsize
))
1228 pageshapes_str
+= "{\\relax}%\n}%\n"
1229 pageshapes_str
+= "\\lovsizes={%\n"
1230 for hsize
, vsize
in pageshapes
[1:]:
1231 pageshapes_str
+= "{\\global\\vsize=%.5ftruept}%%\n" % (72.27/72*unit
.topt(vsize
))
1232 pageshapes_str
+= "{\\relax}%\n}%\n"
1238 self
.execute(pageshapes_str
, [])
1239 parnos_str
= "}{".join(parnos
)
1241 parnos_str
= "{%s}" % parnos_str
1242 parnos_str
= "\\parnos={%s{\\relax}}%%\n" % parnos_str
1243 self
.execute(parnos_str
, [])
1244 parshapes_str
= "\\parshapes={%%\n%s%%\n{\\relax}%%\n}%%\n" % "%\n".join(parshapes
)
1245 self
.execute(parshapes_str
, [])
1246 self
.execute("\\global\\count0=1%%\n"
1247 "\\global\\parno=0%%\n"
1248 "\\global\\myprevgraf=0%%\n"
1249 "\\global\\showprevgraf=0%%\n"
1250 "\\global\\outputtype=0%%\n"
1251 "\\global\\leastcost=10000000%%\n"
1253 "\\vfill\\supereject%%\n" % text
, [texmessage
.ignore
])
1255 if self
.dvifile
is None:
1256 self
.dvifile
= dvifile
.DVIfile("%s.dvi" % self
.texfilename
, debug
=self
.dvidebug
)
1258 raise RuntimeError("textboxes currently needs texipc")
1261 lastparshapes
= parshapes
1264 lastpar
= prevgraf
= -1
1265 m
= self
.PyXVariableBoxPattern
.search(self
.texmessage
)
1268 page
= int(m
.group("page"))
1269 assert page
== pages
1270 par
= int(m
.group("par"))
1271 prevgraf
= int(m
.group("prevgraf"))
1272 if page
<= len(pageshapes
):
1273 width
= 72.27/72*unit
.topt(pageshapes
[page
-1][0])
1275 width
= 72.27/72*unit
.topt(pageshapes
[-1][0])
1276 if page
< len(pageshapes
):
1277 nextwidth
= 72.27/72*unit
.topt(pageshapes
[page
][0])
1279 nextwidth
= 72.27/72*unit
.topt(pageshapes
[-1][0])
1282 # a new paragraph is to be broken
1283 parnos
.append(str(par
))
1284 parshape
= " 0pt ".join(["%.5ftruept" % width
for i
in range(prevgraf
)])
1286 parshape
= " 0pt " + parshape
1287 parshapes
.append("{\\parshape %i%s 0pt %.5ftruept}" % (prevgraf
+ 1, parshape
, nextwidth
))
1288 elif prevgraf
== lastprevgraf
:
1291 # we have to append the breaking of the previous paragraph
1292 oldparshape
= " ".join(parshapes
[-1].split(" ")[2:2+2*lastprevgraf
])
1293 oldparshape
= oldparshape
.split("}")[0]
1295 oldparshape
= " " + oldparshape
1296 parshape
= " 0pt ".join(["%.5ftruept" % width
for i
in range(prevgraf
- lastprevgraf
)])
1298 parshape
= " 0pt " + parshape
1301 parshapes
[-1] = "{\\parshape %i%s%s 0pt %.5ftruept}" % (prevgraf
+ 1, oldparshape
, parshape
, nextwidth
)
1303 lastprevgraf
= prevgraf
1305 m
= self
.PyXVariableBoxPattern
.search(self
.texmessage
, nextpos
)
1307 for i
in range(pages
):
1308 result
.append(self
.dvifile
.readpage([i
+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]))
1309 if parnos
== lastparnos
and parshapes
== lastparshapes
:
1313 raise TexResultError("Too many loops in textboxes ", texrunner
)
1316 # the module provides an default texrunner and methods for direct access
1317 defaulttexrunner
= texrunner()
1318 reset
= defaulttexrunner
.reset
1319 set = defaulttexrunner
.set
1320 preamble
= defaulttexrunner
.preamble
1321 text
= defaulttexrunner
.text
1322 text_pt
= defaulttexrunner
.text_pt
1324 def escapestring(s
, replace
={" ": "~",
1336 "\\": "{$\setminus$}",
1338 "escape all ascii characters such that they are printable by TeX/LaTeX"
1341 if not 32 <= ord(s
[i
]) < 127:
1342 raise ValueError("escapestring function handles ascii strings only")
1349 s
= s
[:i
] + r
+ s
[i
+1:]