gallery example for curved text along text path
[PyX/mjg.git] / manual / text.rst
blobef7e903c55fd175251eb066214ecd24acd9df57f
2 .. module:: text
4 ***************************************
5 Module :mod:`text`: TeX/LaTeX interface
6 ***************************************
9 Basic functionality
10 ===================
12 The :mod:`text` module seamlessly integrates Donald E. Knuths famous TeX
13 typesetting engine into PyX. The basic procedure is:
15 * start a TeX/LaTeX instance as soon as a TeX/LaTeX preamble setting or a text
16   creation is requested
18 * create boxes containing the requested text and shipout those boxes to the dvi
19   file
21 * immediately analyse the TeX/LaTeX output for errors; the box extents are also
22   contained in the TeX/LaTeX output and thus become available immediately
24 * when your TeX installation supports the ``ipc`` mode and PyX is configured to
25   use it, the dvi output is also analysed immediately; alternatively PyX quits the
26   TeX/LaTeX instance to read the dvi file once the output needs to be generated or
27   marker positions are accessed
29 * Type1 fonts are used for the PostScript generation
31 Note that for using Type1 fonts an appropriate font mapping file has to be
32 provided. When your TeX installation is configured to use Type1 fonts by
33 default, the ``psfonts.map`` will contain entries for the standard TeX fonts
34 already. Alternatively, you may either look for ``updmap`` used by many TeX
35 distributions to create an appropriate font mapping file. You may also specify
36 one or several alternative font mapping files like ``psfonts.cmz`` in the global
37 ``pyxrc`` or your local ``.pyxrc``. Finally you can also use the *fontmap*
38 keyword argument to a texrunners :meth:`text` method to use different mappings
39 within a single outout file.
42 TeX/LaTeX instances: the :class:`texrunner` class
43 =================================================
46 Instances of the class :class:`texrunner` are responsible for executing and
47 controling a TeX/LaTeX instance.
50 .. class:: texrunner(mode="tex", lfs="10pt", docclass="article", docopt=None, usefiles=[], fontmaps=config.get("text", "fontmaps", "psfonts.map"), waitfortex=config.getint("text", "waitfortex", 60), showwaitfortex=config.getint("text", "showwaitfortex", 5), texipc=config.getboolean("text", "texipc", 0), texdebug=None, dvidebug=0, errordebug=1, pyxgraphics=1, texmessagesstart=[], texmessagesdocclass=[], texmessagesbegindoc=[], texmessagesend=[], texmessagesdefaultpreamble=[], texmessagesdefaultrun=[])
52    *mode* should the string ``tex`` or ``latex`` and defines whether TeX or LaTeX
53    will be used. *lfs* specifies an ``lfs`` file to simulate LaTeX font size
54    selection macros in plain TeX. PyX comes with a set of ``lfs`` files and a LaTeX
55    script to generate those files. For *lfs* being ``None`` and *mode* equals
56    ``tex`` a list of installed ``lfs`` files is shown.
58    *docclass* is the document class to be used in LaTeX mode and *docopt* are the
59    options to be passed to the document class.
61    *usefiles* is a list of TeX/LaTeX jobname files. PyX will take care of the
62    creation and storing of the corresponding temporary files. A typical use-case
63    would be *usefiles=["spam.aux"]*, but you can also use it to access TeXs log and
64    dvi file.
66    *fontmaps* is a string containing whitespace separated names of font mapping
67    files. *waitfortex* is a number of seconds PyX should wait for TeX/LaTeX to
68    process a request. While waiting for TeX/LaTeX a PyX process might seem to do
69    not perform any work anymore. To give some feedback to the user, a messages is
70    issued each *waitfortex* seconds. The ``texipc`` flag indicates whether PyX
71    should use the ``--ipc`` option of TeX/LaTeX for immediate dvi file access to
72    increase the execution speed of certain operations. See the output of ``tex
73    --help`` whether the option is available at your TeX installation.
75    *texdebug* can be set to a filename to store the commands passed to TeX/LaTeX
76    for debugging. The flag *dvidebug* enables debugging output in the dvi parser
77    similar to ``dvitype``. *errordebug* controls the amount of information
78    returned, when an texmessage parser raises an error. Valid values are ``0``,
79    ``1``, and ``2``.
81    *pyxgraphics* allows use LaTeXs graphics package without further configuration
82    of ``pyx.def``.
84    The TeX message parsers verify whether TeX/LaTeX could properly process its
85    input. By the parameters *texmessagesstart*, *texmessagesdocclass*,
86    *texmessagesbegindoc*, and *texmessagesend* you can set TeX message parsers to
87    be used then TeX/LaTeX is started, when the ``documentclass`` command is issued
88    (LaTeX only), when the ``\\begin{document}`` is sent, and when the TeX/LaTeX is
89    stopped, respectively. The lists of TeX message parsers are merged with the
90    following defaults: ``[texmessage.start]`` for *texmessagesstart*,
91    ``[texmessage.load]`` for *texmessagesdocclass*, ``[texmessage.load,
92    texmessage.noaux]`` for *texmessagesbegindoc*, and ``[texmessage.texend,
93    texmessage.fontwarning]`` for *texmessagesend*.
95    Similarily *texmessagesdefaultpreamble* and *texmessagesdefaultrun* take TeX
96    message parser to be merged to the TeX message parsers given in the
97    :meth:`preamble` and :meth:`text` methods. The *texmessagesdefaultpreamble* and
98    *texmessagesdefaultrun* are merged with ``[texmessage.load]`` and
99    ``[texmessage.loaddef, texmessage.graphicsload, texmessage.fontwarning,
100    texmessage.boxwarning]``, respectively.
102 :class:`texrunner` instances provides several methods to be called by the user:
105 .. method:: texrunner.set(**kwargs)
107    This method takes the same keyword arguments as the :class:`texrunner`
108    constructor. Its purpose is to reconfigure an already constructed
109    :class:`texrunner` instance. The most prominent use-case is to alter the
110    configuration of the default :class:`texrunner` instance ``defaulttexrunner``
111    which is created at the time of loading of the :mod:`text` module.
113    The ``set`` method fails, when a modification cannot be applied anymore (e.g.
114    TeX/LaTeX has already been started).
117 .. method:: texrunner.preamble(expr, texmessages=[])
119    The :meth:`preamble` can be called prior to the :meth:`text` method only or
120    after reseting a texrunner instance by :meth:`reset`. The *expr* is passed to
121    the TeX/LaTeX instance not encapsulated in a group. It should not generate any
122    output to the dvi file. In LaTeX preamble expressions are inserted prior to the
123    ``\\begin{document}`` and a typical use-case is to load packages by
124    ``\\usepackage``. Note, that you may use ``\\AtBeginDocument`` to postpone the
125    immediate evaluation.
127    *texmessages* are TeX message parsers to handle the output of TeX/LaTeX. They
128    are merged with the default TeX message parsers for the :meth:`preamble` method.
129    See the constructur description for details on the default TeX message parsers.
132 .. method:: texrunner.text(x, y, expr, textattrs=[], texmessages=[])
134    *x* and *y* are the position where a text should be typeset and *expr* is the
135    TeX/LaTeX expression to be passed to TeX/LaTeX.
137    *textattrs* is a list of TeX/LaTeX settings as described below, PyX
138    transformations, and PyX fill styles (like colors).
140    *texmessages* are TeX message parsers to handle the output of TeX/LaTeX. They
141    are merged with the default TeX message parsers for the :meth:`text` method. See
142    the constructur description for details on the default TeX message parsers.
144    The :meth:`text` method returns a :class:`textbox` instance, which is a special
145    :class:`canvas` instance. It has the methods :meth:`width`, :meth:`height`, and
146    :meth:`depth` to access the size of the text. Additionally the :meth:`marker`
147    method, which takes a string *s*, returns a position in the text, where the
148    expression ``\\PyXMarker{s}`` is contained in *expr*. You should not use ``@``
149    within your strings *s* to prevent name clashes with PyX internal macros
150    (although we don't the marker feature internally right now).
152 Note that for the outout generation and the marker access the TeX/LaTeX instance
153 must be terminated except when ``texipc`` is turned on. However, after such a
154 termination a new TeX/LaTeX instance is started when the :meth:`text` method is
155 called again.
158 .. method:: texrunner.reset(reinit=0)
160    This method can be used to manually force a restart of TeX/LaTeX. The flag
161    *reinit* will initialize the TeX/LaTeX by repeating the :meth:`preamble` calls.
162    New :meth:`set` and :meth:`preamble` calls are allowed when *reinit* was not set
163    only.
166 TeX/LaTeX attributes
167 ====================
170 TeX/LaTeX attributes are instances to be passed to a :class:`texrunner`\ s
171 :meth:`text` method. They stand for TeX/LaTeX expression fragments and handle
172 dependencies by proper ordering.
175 .. class:: halign(boxhalign, flushhalign)
177    Instances of this class set the horizontal alignment of a text box and the
178    contents of a text box to be left, center and right for *boxhalign* and
179    *flushhalign* being ``0``, ``0.5``, and ``1``. Other values are allowed as well,
180    although such an alignment seems quite unusual.
182 Note that there are two separate classes :class:`boxhalign` and
183 :class:`flushhalign` to set the alignment of the box and its contents
184 independently, but those helper classes can't be cleared independently from each
185 other. Some handy instances available as class members:
188 .. attribute:: halign.boxleft
190    Left alignment of the text box, *i.e.* sets *boxhalign* to ``0`` and doesn't set
191    *flushhalign*.
194 .. attribute:: halign.boxcenter
196    Center alignment of the text box, *i.e.* sets *boxhalign* to ``0.5`` and doesn't
197    set *flushhalign*.
200 .. attribute:: halign.boxright
202    Right alignment of the text box, *i.e.* sets *boxhalign* to ``1`` and doesn't
203    set *flushhalign*.
206 .. attribute:: halign.flushleft
208    Left alignment of the content of the text box in a multiline box, *i.e.* sets
209    *flushhalign* to ``0`` and doesn't set *boxhalign*.
212 .. attribute:: halign.raggedright
214    Identical to :attr:`flushleft`.
217 .. attribute:: halign.flushcenter
219    Center alignment of the content of the text box in a multiline box, *i.e.* sets
220    *flushhalign* to ``0.5`` and doesn't set *boxhalign*.
223 .. attribute:: halign.raggedcenter
225    Identical to :attr:`flushcenter`.
228 .. attribute:: halign.flushright
230    Right alignment of the content of the text box in a multiline box, *i.e.* sets
231    *flushhalign* to ``1`` and doesn't set *boxhalign*.
234 .. attribute:: halign.raggedleft
236    Identical to :attr:`flushright`.
239 .. attribute:: halign.left
241    Combines :attr:`boxleft` and :attr:`flushleft`, *i.e.* ``halign(0, 0)``.
244 .. attribute:: halign.center
246    Combines :attr:`boxcenter` and :attr:`flushcenter`, *i.e.* ``halign(0.5, 0.5)``.
249 .. attribute:: halign.right
251    Combines :attr:`boxright` and :attr:`flushright`, *i.e.* ``halign(1, 1)``.
253 .. _fig_textvalign:
254 .. figure:: textvalign.*
255    :align:  center
257    valign example
260 .. class:: valign(valign)
262    Instances of this class set the vertical alignment of a text box to be top,
263    center and bottom for *valign* being ``0``, ``0.5``, and ``1``. Other values are
264    allowed as well, although such an alignment seems quite unusual. See the left
265    side of figure :ref:`fig_textvalign` for an example.
267 Some handy instances available as class members:
270 .. attribute:: valign.top
272    ``valign(0)``
275 .. attribute:: valign.middle
277    ``valign(0.5)``
280 .. attribute:: valign.bottom
282    ``valign(1)``
285 .. attribute:: valign.baseline
287    Identical to clearing the vertical alignment by :attr:`clear` to emphasise that
288    a baseline alignment is not a box-related alignment. Baseline alignment is the
289    default, *i.e.* no valign is set by default.
292 .. class:: parbox(width, baseline=top)
294    Instances of this class create a box with a finite width, where the typesetter
295    creates multiple lines in. Note, that you can't create multiple lines in
296    TeX/LaTeX without specifying a box width. Since PyX doesn't know a box width, it
297    uses TeXs LR-mode by default, which will always put everything into a single
298    line. Since in a vertical box there are several baselines, you can specify the
299    baseline to be used by the optional *baseline* argument. You can set it to the
300    symbolic names :attr:`top`, :attr:`parbox.middle`, and :attr:`parbox.bottom`
301    only, which are members of :class:`valign`. See the right side of figure
302    :ref:`fig_textvalign` for an example.
304 Since you need to specify a box width no predefined instances are available as
305 class members.
308 .. class:: vshift(lowerratio, heightstr="0")
310    Instances of this class lower the output by *lowerratio* of the height of the
311    string *heigthstring*. Note, that you can apply several shifts to sum up the
312    shift result. However, there is still a :attr:`clear` class member to remove all
313    vertical shifts.
315 Some handy instances available as class members:
318 .. attribute:: vshift.bottomzero
320    ``vshift(0)`` (this doesn't shift at all)
323 .. attribute:: vshift.middlezero
325    ``vshift(0.5)``
328 .. attribute:: vshift.topzero
330    ``vshift(1)``
333 .. attribute:: vshift.mathaxis
335    This is a special vertical shift to lower the output by the height of the
336    mathematical axis. The mathematical axis is used by TeX for the vertical
337    alignment in mathematical expressions and is often usefull for vertical
338    alignment. The corresponding vertical shift is less than :attr:`middlezero` and
339    usually fits the height of the minus sign. (It is the height of the minus sign
340    in mathematical mode, since that's that the mathematical axis is all about.)
342 There is a TeX/LaTeX attribute to switch to TeXs math mode. The appropriate
343 instances ``mathmode`` and ``clearmathmode`` (to clear the math mode attribute)
344 are available at module level.
347 .. data:: mathmode
349    Enables TeXs mathematical mode in display style.
351 The :class:`size` class creates TeX/LaTeX attributes for changing the font size.
354 .. class:: size(sizeindex=None, sizename=None, sizelist=defaultsizelist)
356    LaTeX knows several commands to change the font size. The command names are
357    stored in the *sizelist*, which defaults to ``["normalsize", "large", "Large",
358    "LARGE", "huge", "Huge", None, "tiny", "scriptsize", "footnotesize", "small"]``.
360    You can either provide an index *sizeindex* to access an item in *sizelist* or
361    set the command name by *sizename*.
363 Instances for the LaTeXs default size change commands are available as class
364 members:
367 .. attribute:: size.tiny
369    ``size(-4)``
372 .. attribute:: size.scriptsize
374    ``size(-3)``
377 .. attribute:: size.footnotesize
379    ``size(-2)``
382 .. attribute:: size.small
384    ``size(-1)``
387 .. attribute:: size.normalsize
389    ``size(0)``
392 .. attribute:: size.large
394    ``size(1)``
397 .. attribute:: size.Large
399    ``size(2)``
402 .. attribute:: size.LARGE
404    ``size(3)``
407 .. attribute:: size.huge
409    ``size(4)``
412 .. attribute:: size.Huge
414    ``size(5)``
416 There is a TeX/LaTeX attribute to create empty text boxes with the size of the
417 material passed in. The appropriate instances ``phantom`` and ``clearphantom``
418 (to clear the phantom attribute) are available at module level.
421 .. data:: phantom
423    Skip the text in the box, but keep its size.
426 Using the graphics-bundle with LaTeX
427 ====================================
429 The packages in the LaTeX graphics bundle (``color.sty``, ``graphics.sty``,
430 ``graphicx.sty``, ...) make extensive use of ``\\special`` commands. PyX defines
431 a clean set of such commands to fit the needs of the LaTeX graphics bundle. This
432 is done via the ``pyx.def`` driver file, which tells the graphics bundle about
433 the syntax of the ``\\special`` commands as expected by PyX. You can install the
434 driver file ``pyx.def`` into your LaTeX search path and add the content of both
435 files ``color.cfg`` and ``graphics.cfg`` to your personal configuration files.
436 [#]_ After you have installed the ``cfg`` files, please use the :mod:`text`
437 module with unset ``pyxgraphics`` keyword argument which will switch off a
438 convenience hack for less experienced LaTeX users. You can then import the LaTeX
439 graphics bundle packages and related packages (e.g. ``rotating``, ...) with the
440 option ``pyx``, e.g. ``\\usepackage[pyx]{color,graphicx}``. Note that the option
441 ``pyx`` is only available with unset *pyxgraphics* keyword argument and a
442 properly installed driver file. Otherwise, omit the specification of a driver
443 when loading the packages.
445 When you define colors in LaTeX via one of the color models ``gray``, ``cmyk``,
446 ``rgb``, ``RGB``, ``hsb``, then PyX will use the corresponding values (one to
447 four real numbers). In case you use any of the ``named`` colors in LaTeX, PyX
448 will use the corresponding predefined color (see module ``color`` and the color
449 table at the end of the manual). The additional LaTeX color model ``pyx`` allows
450 to use a PyX color expression, such as ``color.cmyk(0,0,0,0)`` directly in
451 LaTeX. It is passed to PyX.
453 When importing Encapsulated PostScript files (``eps`` files) PyX will rotate,
454 scale and clip your file like you expect it. Other graphic formats can not be
455 imported via the graphics package at the moment.
457 For reference purpose, the following specials can be handled by PyX at the
458 moment:
460 ``PyX:color_begin (model) (spec)``
461    starts a color. ``(model)`` is one of ``gray``, ``cmyk``, ``rgb``, ``hsb``,
462    ``texnamed``, or ``pyxcolor``. ``(spec)`` depends on the model: a name or some
463    numbers
465 ``PyX:color_end``
466    ends a color.
468 ``PyX:epsinclude file= llx= lly= urx= ury= width= height= clip=0/1``
469    includes an Encapsulated PostScript file (``eps`` files). The values of ``llx``
470    to ``ury`` are in the files' coordinate system and specify the part of the
471    graphics that should become the specified ``width`` and ``height`` in the
472    outcome. The graphics may be clipped. The last three parameters are optional.
474 ``PyX:scale_begin (x) (y)``
475    begins scaling from the current point.
477 ``PyX:scale_end``
478    ends scaling.
480 ``PyX:rotate_begin (angle)``
481    begins rotation around the current point.
483 ``PyX:rotate_end``
484    ends rotation.
487 TeX message parsers
488 ===================
491 Message parsers are used to scan the output of TeX/LaTeX. The output is analysed
492 by a sequence of TeX message parsers. Each message parser analyses the output
493 and removes those parts of the output, it feels responsible for. If there is
494 nothing left in the end, the message got validated, otherwise an exception is
495 raised reporting the problem. A message parser might issue a warning when
496 removing some output to give some feedback to the user.
499 .. class:: texmessage()
501    This class acts as a container for TeX message parsers instances, which are all
502    instances of classes derived from :class:`texmessage`.
504 The following TeX message parser instances are available:
507 .. attribute:: texmessage.start
509    Check for TeX/LaTeX startup message including scrollmode test.
512 .. attribute:: texmessage.noaux
514    Ignore LaTeXs no-aux-file warning.
517 .. attribute:: texmessage.end
519    Check for proper TeX/LaTeX tear down message.
522 .. attribute:: texmessage.load
524    Accepts arbitrary loading of files without checking for details, *i.e.* accept
525    ``(file ...)`` where ``file`` is an readable file.
528 .. attribute:: texmessage.loaddef
530    Accepts arbitrary loading of ``fd`` files, *i.e.* accept ``(file.def)`` and
531    ``(file.fd)`` where ``file.def`` or ``file.fd`` is an readable file,
532    respectively.
535 .. attribute:: texmessage.graphicsload
537    Accepts arbitrary loading of ``eps`` files, *i.e.* accept ``(file.eps)`` where
538    ``file.eps`` is an readable file.
541 .. attribute:: texmessage.ignore
543    Ignores everything (this is probably a bad idea, but sometimes you might just
544    want to ignore everything).
547 .. attribute:: texmessage.allwarning
549    Ignores everything but issues a warning.
552 .. attribute:: texmessage.fontwarning
554    Issues a warning about font substitutions of the LaTeXs NFSS.
557 .. attribute:: texmessage.boxwarning
559    Issues a warning on under- and overfull horizontal and vertical boxes.
562 .. class:: texmessagepattern(pattern, warning=None)
564    This is a derived class of :class:`texmessage`. It can be used to construct
565    simple TeX message parsers, which validate a TeX message matching a certain
566    regular expression pattern *pattern*. When *warning* is set, a warning message
567    is issued. Several of the TeX message parsers described above are implemented
568    using this class.
571 The :attr:`defaulttexrunner` instance
572 =====================================
575 .. data:: defaulttexrunner
577    The ``defaulttexrunner`` is an instance of :class:`texrunner`. It is created
578    when the :mod:`text` module is loaded and it is used as the default texrunner
579    instance by all :class:`canvas` instances to implement its :meth:`text` method.
582 .. function:: preamble(...)
584    ``defaulttexrunner.preamble``
587 .. function:: text(...)
589    ``defaulttexrunner.text``
592 .. function:: set(...)
594    ``defaulttexrunner.set``
597 .. function:: reset(...)
599    ``defaulttexrunner.reset``
602 Some internals on temporary files
603 =================================
605 It is not totally obvious how TeX processes are supervised by PyX and why it's
606 done that way. However there are good reasons for it and the following
607 description is intended for people wanting and/or needing to understand how
608 temporary files are used by PyX. All others don't need to care.
610 Each time PyX needs to start a new TeX process, it creates a base file name for
611 temporary files associated with this process. This file name is used as
612 ``\jobname`` by TeX. Since TeX does not handle directory names as part of
613 ``\jobname``, the temporary files will be created in the current directory. The
614 PyX developers decided to not change the current directory at all, avoiding all
615 kind of issues with accessing files in the local directory, like for loading
616 graph data, LaTeX style files etc.
618 PyX creates a TeX file containing ``\relax`` only. It's only use is to set TeXs
619 ``\jobname``. Immediately after processing ``\relax`` TeX falls back to stdin to
620 read more commands. PyX than uses ``stdin`` and ``stdout`` to avoid various
621 buffering issues which would occur when using files (or named pipes). By that
622 PyX can fetch TeX errors as soon as they occur while keeping the TeX process
623 running (i.e. in a waiting state) for further input. The size of the TeX output
624 is also availble immediately without fetching the ``dvi`` file created by TeX,
625 since PyX uses some TeX macros to output the extents of the boxes created for
626 the requested texts to ``stdout`` immediately. There is a TeX hack ``--ipc``
627 which PyX knows to take advantage of to fetch informations from the ``dvi`` file
628 immediately as well, but it's not available on all TeXinstallations. Thus this
629 feature is disabled by default and fetching informations from the ``dvi`` is
630 tried to be limited to those cases, where no other option exists. By that TeX
631 usually doesn't need to be started several times.
633 By default PyX will clean up all temporary files after TeX was stopped. However
634 the ``usefiles`` list allows for a renaming of the files from (and to, if
635 existing) the temporary ``\jobname`` (+ suffix) handled by PyX. Additionally,
636 since PyX does not write a useful TeX input file in a file and thus a
637 ``usefiles=["example.tex"]`` would not contain the code actually passed to TeX,
638 the ``texdebug`` feature of the texrunner can be used instead to get a the full
639 input passed to TeX.
641 In case you need to control the position where the temporary files are created
642 (say, you're working on a read-only directory), the suggested solution is to
643 switch the current directory before starting with text processing in PyX (i.e.
644 an ``os.chdir`` at the beginning of your script will do fine). You than just
645 need to take care of specifying full paths when accessing data from your
646 original working directory, but that's intended and necessary for that case.
648 .. rubric:: Footnotes
650 .. [#] If you do not know what this is all about, you can just ignore this paragraph.
651    But be sure that the *pyxgraphics* keyword argument is always set!