add xy12axesat feature to graphxyz
[PyX.git] / manual / text.rst
blob1705b5d5d74af7bf3efdba3edb67a3ceeac472ad
2 .. module:: text
3    :synopsis: High-level interface for text output including a TeX/LaTeX
4               interface
6 ****
7 Text
8 ****
10 Rationale
11 =========
13 The :mod:`text` module is used to create text output. It seamlessly integrates
14 Donald E. Knuths famous TeX typesetting engine\ [#]_. The module is a
15 high-level interface to an extensive stack of TeX and font related
16 functionality in PyX, whose details are way beyond this manual and completely
17 irrelevant for the typical PyX user. However, the basic concept should be
18 described briefly, as it provides important insights into essential properties
19 of the whole machinery.
21 PyX does not apply any limitations on the text submitted by the user. Instead
22 the text is directly passed to TeX. This has the implication, that the text to
23 be typeset should come from a trusted source or some special security measures
24 should be applied (see :ref:`chroot`). PyX just adds a light and transparent
25 wrapper using basic TeX functionality for later identification and output
26 extraction. This procedure enables full access to all TeX features and makes
27 PyX on the other hand dependent on the error handling provided by TeX. However,
28 a detailed and immediate control of the TeX output allows PyX to report
29 problems back to the user as they occur.
31 While we only talked about TeX so far (and will continue to do so in the rest
32 of this section), it is important to note that the coupling is not limited to
33 plain TeX. Currently, PyX can also use LaTeX for typesetting, and other TeX
34 variants could be added in the future. What PyX really depends on is the
35 ability of the typesetting program to generate DVI\ [#]_.
37 As soon as some text creation is requested or, even before that, a preamble
38 setting or macro definition is submitted, the TeX program is started as a
39 separate process. The input and output is bound to a :class:`SingleRunner`
40 instance. Typically, the process will be kept alive and will be reused for all
41 future typesetting requests until the end of the PyX process. However, there
42 are certain situations when the TeX program needs to be shutdown early, which
43 are be described in detail in the :ref:`texipc` section.
45 Whenever PyX sends some commands to the TeX interpreter, it adds an output
46 marker at the end, and waits for this output marker to be echoed in the TeX
47 output. All intermediate output is attributed to the commands just sent and
48 will be analysed for problems. This is done by :class:`texmessage` parsers.
49 Here, a problem could be logged to the PyX logger at warning level, thus
50 be reported to ``stderr`` by default. This happens for over- or underful boxes
51 or font warnings emitted by TeX. For other unknown problems (*i.e.* output not
52 handled by any of the given :class:`texmessage` parsers), a
53 :exc:`TexResultError` is raised, which creates a detailed error report
54 including the traceback, the commands submitted to TeX and the output returned
55 by TeX.
57 PyX wraps each text to be typeset in a TeX box and adds a shipout of this box
58 to the TeX code before forwarding it to TeX. Thus a page in the DVI file is
59 created containing just this output. Furthermore TeX is asked to output the box
60 extent. By that PyX will immediately know the size of the text without
61 referring to the DVI. This also allows faking the box size by TeX means, as you
62 would expect it.
64 Once the actual output is requested, PyX reads the content of the DVI file,
65 accessing the page related to the output in question. It then does all the
66 necessary steps to transform the DVI content to the requested output format,
67 like searching for virtual font files, font metrices, font mapping files, and
68 PostScript Type1 fonts to be used in the final output. Here a present
69 limitation has been mentioned: PyX presently can use PostScript Type1 fonts
70 only to generate text output. While this is a serious limitation, all the
71 default fonts in TeX are available in Type1 nowadays and current TeX
72 installations are alreadily configured to use them by default.
75 TeX interface
76 =============
78 .. autoclass:: SingleRunner
79    :members: preamble, text, text_pt, texmessages_start_default, texmessages_end_default, texmessages_preamble_default, texmessages_run_default
81 .. autoclass:: SingleTexRunner
83 .. autoclass:: SingleLatexRunner
84    :members: texmessages_docclass_default, texmessages_begindoc_default
86 The :class:`SingleRunner` classes described above do not handle restarts of the
87 interpreter when the actuall DVI result is required and is not available via
88 the :ref:`texipc` feature.
90 The :class:`MultiRunner` classes below are not derived from
91 :class:`SingleRunner` even though the provide the same functional interface
92 (:meth:`MultiRunner.preamble`, :meth:`MultiRunner.text`, and
93 :meth:`MultiRunner.text_pt`), but instead wrap a :class:`SingleRunner`
94 instance, and provide an automatic (or manual by the :meth:`MultiRunner.reset`
95 function) restart of the interpreter as required.
97 .. autoclass:: MultiRunner
98    :members: preamble, text, text_pt, reset
100 .. autoclass:: TexRunner
102 .. autoclass:: LatexRunner
104 .. autoclass:: textbox_pt
105    :members: marker
107 .. unfortunately we cannot list left, right, etc. as members, as they will show up with the value None
108 .. see https://bitbucket.org/birkenfeld/sphinx/issue/904/autodocs-does-not-work-well-with-instance
109 .. we're using the undocumented autoinstanceattribute as a workaround
111 .. autoinstanceattribute:: textbox_pt.left
112    :annotation:
114 .. autoinstanceattribute:: textbox_pt.right
115    :annotation:
117 .. autoinstanceattribute:: textbox_pt.width
118    :annotation:
120 .. autoinstanceattribute:: textbox_pt.height
121    :annotation:
123 .. autoinstanceattribute:: textbox_pt.depth
124    :annotation:
127 Module level functionality
128 ==========================
130 The text module provides the public interface of the :class:`SingleRunner`
131 class by module level functions. For that, a module level :class:`MultiRunner`
132 is created and configured by the :func:`set` function. Each time the
133 :func:`set` function is called, the existing module level :class:`MultiRunner`
134 is replaced by a new one.
136 .. autodata:: default_runner
137    :annotation:
139 .. autodata:: preamble
140    :annotation:
142 .. autodata:: text_pt
143    :annotation:
145 .. autodata:: text
146    :annotation:
148 .. autodata:: reset
149    :annotation:
151 .. autofunction:: set
153 .. autofunction:: escapestring
156 TeX output parsers
157 ==================
159 While running TeX (and variants thereof) a variety of information is written to
160 ``stdout`` like status messages, details about file access, and also warnings
161 and errors. PyX reads all the output and analyses it. Some of the output is
162 triggered as a direct response to the TeX input and is thus easy to understand
163 for PyX. This includes page output information, but also workflow control
164 information injected by PyX into the input stream. PyX uses it to check the
165 communication and typeset progress. All the other output is handled by a list
166 of :class:`texmessage` parsers, an individual set of functions applied to the
167 TeX output one after the other. Each of the function receives the TeX output as
168 a string and return it back (maybe altered). Such a function must perform one
169 of the following actions in response to the TeX output is receives:
171  1. If it does not find any text in the TeX output it feals responsible for, it
172     should just return the unchanged string.
174  2. If it finds a text it is responsible for, and the message is just fine
175     (doesn't need to be communicated to the user), it should just remove this
176     text and return the rest of the TeX output.
178  3. If the text should be communicated to the user, a message should be written
179     the the pyx logger at warning level, thus being reported to the user on
180     ``stderr`` by default. Examples are underfull and overfull box warnings or
181     font warnings. In addition, the text should be removed as in 2 above.
183  4. In case of an error, :exc:`TexResultError` should be raised.
185 This is rather uncommon, that the fourth option is taken directly. Instead,
186 errors can just be kept in the output as PyX considers unhandled TeX output
187 left after applying all given :class:`texmessage` parsers as an error. In
188 addition to the error message, information about the TeX in- and output will be
189 added to the exception description text by the :class:`SingleRunner` according
190 to the :class:`errordetail` setting. The following verbosity levels are
191 available:
193 .. autoclass:: errordetail
194    :members:
196 .. autoexception:: TexResultError
198 To prevent any unhandled TeX output to be reported as an error,
199 :attr:`texmessage.warn` or :attr:`texmessage.ignore` can be used. To complete
200 the description, here is a list of all available :class:`texmessage` parsers:
202 .. autoclass:: texmessage
203    :members:
206 TeX/LaTeX attributes
207 ====================
210 TeX/LaTeX attributes are instances to be passed to a :class:`texrunner`\ s
211 :meth:`text` method. They stand for TeX/LaTeX expression fragments and handle
212 dependencies by proper ordering.
215 .. class:: halign(boxhalign, flushhalign)
217    Instances of this class set the horizontal alignment of a text box and the
218    contents of a text box to be left, center and right for *boxhalign* and
219    *flushhalign* being ``0``, ``0.5``, and ``1``. Other values are allowed as well,
220    although such an alignment seems quite unusual.
222 Note that there are two separate classes :class:`boxhalign` and
223 :class:`flushhalign` to set the alignment of the box and its contents
224 independently, but those helper classes can't be cleared independently from each
225 other. Some handy instances available as class members:
228 .. attribute:: halign.boxleft
230    Left alignment of the text box, *i.e.* sets *boxhalign* to ``0`` and doesn't set
231    *flushhalign*.
234 .. attribute:: halign.boxcenter
236    Center alignment of the text box, *i.e.* sets *boxhalign* to ``0.5`` and doesn't
237    set *flushhalign*.
240 .. attribute:: halign.boxright
242    Right alignment of the text box, *i.e.* sets *boxhalign* to ``1`` and doesn't
243    set *flushhalign*.
246 .. attribute:: halign.flushleft
248    Left alignment of the content of the text box in a multiline box, *i.e.* sets
249    *flushhalign* to ``0`` and doesn't set *boxhalign*.
252 .. attribute:: halign.raggedright
254    Identical to :attr:`flushleft`.
257 .. attribute:: halign.flushcenter
259    Center alignment of the content of the text box in a multiline box, *i.e.* sets
260    *flushhalign* to ``0.5`` and doesn't set *boxhalign*.
263 .. attribute:: halign.raggedcenter
265    Identical to :attr:`flushcenter`.
268 .. attribute:: halign.flushright
270    Right alignment of the content of the text box in a multiline box, *i.e.* sets
271    *flushhalign* to ``1`` and doesn't set *boxhalign*.
274 .. attribute:: halign.raggedleft
276    Identical to :attr:`flushright`.
279 .. attribute:: halign.left
281    Combines :attr:`boxleft` and :attr:`flushleft`, *i.e.* ``halign(0, 0)``.
284 .. attribute:: halign.center
286    Combines :attr:`boxcenter` and :attr:`flushcenter`, *i.e.* ``halign(0.5, 0.5)``.
289 .. attribute:: halign.right
291    Combines :attr:`boxright` and :attr:`flushright`, *i.e.* ``halign(1, 1)``.
293 .. _fig_textvalign:
294 .. figure:: textvalign.*
295    :align:  center
297    valign example
300 .. class:: valign(valign)
302    Instances of this class set the vertical alignment of a text box to be top,
303    center and bottom for *valign* being ``0``, ``0.5``, and ``1``. Other values are
304    allowed as well, although such an alignment seems quite unusual. See the left
305    side of figure :ref:`fig_textvalign` for an example.
307 Some handy instances available as class members:
310 .. attribute:: valign.top
312    ``valign(0)``
315 .. attribute:: valign.middle
317    ``valign(0.5)``
320 .. attribute:: valign.bottom
322    ``valign(1)``
325 .. attribute:: valign.baseline
327    Identical to clearing the vertical alignment by :attr:`clear` to emphasise that
328    a baseline alignment is not a box-related alignment. Baseline alignment is the
329    default, *i.e.* no valign is set by default.
332 .. class:: parbox(width, baseline=top)
334    Instances of this class create a box with a finite width, where the typesetter
335    creates multiple lines in. Note, that you can't create multiple lines in
336    TeX/LaTeX without specifying a box width. Since PyX doesn't know a box width, it
337    uses TeXs LR-mode by default, which will always put everything into a single
338    line. Since in a vertical box there are several baselines, you can specify the
339    baseline to be used by the optional *baseline* argument. You can set it to the
340    symbolic names :attr:`top`, :attr:`parbox.middle`, and :attr:`parbox.bottom`
341    only, which are members of :class:`valign`. See the right side of figure
342    :ref:`fig_textvalign` for an example.
344 Since you need to specify a box width no predefined instances are available as
345 class members.
348 .. class:: vshift(lowerratio, heightstr="0")
350    Instances of this class lower the output by *lowerratio* of the height of the
351    string *heigthstring*. Note, that you can apply several shifts to sum up the
352    shift result. However, there is still a :attr:`clear` class member to remove all
353    vertical shifts.
355 Some handy instances available as class members:
358 .. attribute:: vshift.bottomzero
360    ``vshift(0)`` (this doesn't shift at all)
363 .. attribute:: vshift.middlezero
365    ``vshift(0.5)``
368 .. attribute:: vshift.topzero
370    ``vshift(1)``
373 .. attribute:: vshift.mathaxis
375    This is a special vertical shift to lower the output by the height of the
376    mathematical axis. The mathematical axis is used by TeX for the vertical
377    alignment in mathematical expressions and is often usefull for vertical
378    alignment. The corresponding vertical shift is less than :attr:`middlezero` and
379    usually fits the height of the minus sign. (It is the height of the minus sign
380    in mathematical mode, since that's that the mathematical axis is all about.)
382 There is a TeX/LaTeX attribute to switch to TeXs math mode. The appropriate
383 instances ``mathmode`` and ``clearmathmode`` (to clear the math mode attribute)
384 are available at module level.
387 .. data:: mathmode
389    Enables TeXs mathematical mode in display style.
391 The :class:`size` class creates TeX/LaTeX attributes for changing the font size.
394 .. class:: size(sizeindex=None, sizename=None, sizelist=defaultsizelist)
396    LaTeX knows several commands to change the font size. The command names are
397    stored in the *sizelist*, which defaults to ``["normalsize", "large", "Large",
398    "LARGE", "huge", "Huge", None, "tiny", "scriptsize", "footnotesize", "small"]``.
400    You can either provide an index *sizeindex* to access an item in *sizelist* or
401    set the command name by *sizename*.
403 Instances for the LaTeXs default size change commands are available as class
404 members:
407 .. attribute:: size.tiny
409    ``size(-4)``
412 .. attribute:: size.scriptsize
414    ``size(-3)``
417 .. attribute:: size.footnotesize
419    ``size(-2)``
422 .. attribute:: size.small
424    ``size(-1)``
427 .. attribute:: size.normalsize
429    ``size(0)``
432 .. attribute:: size.large
434    ``size(1)``
437 .. attribute:: size.Large
439    ``size(2)``
442 .. attribute:: size.LARGE
444    ``size(3)``
447 .. attribute:: size.huge
449    ``size(4)``
452 .. attribute:: size.Huge
454    ``size(5)``
456 There is a TeX/LaTeX attribute to create empty text boxes with the size of the
457 material passed in. The appropriate instances ``phantom`` and ``clearphantom``
458 (to clear the phantom attribute) are available at module level.
461 .. data:: phantom
463    Skip the text in the box, but keep its size.
466 .. _pyxgraphics:
468 Using the graphics-bundle with LaTeX
469 ====================================
471 The packages in the LaTeX graphics bundle (``color.sty``, ``graphics.sty``,
472 ``graphicx.sty``, ...) make extensive use of ``\\special`` commands. PyX
473 defines a clean set of such commands to fit the needs of the LaTeX graphics
474 bundle. This is done via the ``pyx.def`` driver file, which tells the graphics
475 bundle about the syntax of the ``\\special`` commands as expected by PyX. You
476 can install the driver file ``pyx.def`` into your LaTeX search path and add the
477 content of both files ``color.cfg`` and ``graphics.cfg`` to your personal
478 configuration files\ [#]_. After you have installed the ``cfg`` files, please
479 use the :mod:`text` module with unset ``pyxgraphics`` keyword argument which
480 will switch off a convenience hack for less experienced LaTeX users. You can
481 then import the LaTeX graphics bundle packages and related packages (e.g.
482 ``rotating``, ...) with the option ``pyx``, e.g.
483 ``\\usepackage[pyx]{color,graphicx}``. Note that the option ``pyx`` is only
484 available with unset *pyxgraphics* keyword argument and a properly installed
485 driver file. Otherwise, omit the specification of a driver when loading the
486 packages.
488 When you define colors in LaTeX via one of the color models ``gray``, ``cmyk``,
489 ``rgb``, ``RGB``, ``hsb``, then PyX will use the corresponding values (one to
490 four real numbers). In case you use any of the ``named`` colors in LaTeX, PyX
491 will use the corresponding predefined color (see module ``color`` and the color
492 table at the end of the manual). The additional LaTeX color model ``pyx`` allows
493 to use a PyX color expression, such as ``color.cmyk(0,0,0,0)`` directly in
494 LaTeX. It is passed to PyX.
496 When importing Encapsulated PostScript files (``eps`` files) PyX will rotate,
497 scale and clip your file like you expect it. Other graphic formats can not be
498 imported via the graphics package at the moment.
500 For reference purpose, the following specials can be handled by PyX at the
501 moment:
503 ``PyX:color_begin (model) (spec)``
504    starts a color. ``(model)`` is one of ``gray``, ``cmyk``, ``rgb``, ``hsb``,
505    ``texnamed``, or ``pyxcolor``. ``(spec)`` depends on the model: a name or some
506    numbers
508 ``PyX:color_end``
509    ends a color.
511 ``PyX:epsinclude file= llx= lly= urx= ury= width= height= clip=0/1``
512    includes an Encapsulated PostScript file (``eps`` files). The values of ``llx``
513    to ``ury`` are in the files' coordinate system and specify the part of the
514    graphics that should become the specified ``width`` and ``height`` in the
515    outcome. The graphics may be clipped. The last three parameters are optional.
517 ``PyX:scale_begin (x) (y)``
518    begins scaling from the current point.
520 ``PyX:scale_end``
521    ends scaling.
523 ``PyX:rotate_begin (angle)``
524    begins rotation around the current point.
526 ``PyX:rotate_end``
527    ends rotation.
530 .. _config:
532 .. _pyxrc:
534 Configuration
535 =============
537 While the PyX configuration technically has nothing to do with the text module,
538 we mention it here as part of the text module since its main purpose is the
539 configuration of various aspects related to the typesetting of text.
541 PyX comes with reasonable defaults which should work out of the box on most TeX
542 installations. The default values are defined in the PyX source code itself and
543 are repeated in the system-wide config file in INI file format located at
544 ``pyx/data/pyxrc``. This file also contains a description of each of the listed
545 config values and is read at PyX startup. Thus the system-wide configuration
546 can be adjusted by editing this file.
548 In addition, a user-specific configuration can be setup by a ``~/.pyxrc`` on
549 unix-like Systems (including OS X) or ``pyxrc`` in the directory defined by the
550 environment variable ``APPDATA`` on MS Windows. This user-specific
551 configuration will overwrite the system-wide settings.
553 Yet another configuration can be set by the environment variable ``PYXRC``. The
554 given file will is loaded on top of the configuration defined in the previous
555 steps.
558 .. _texipc:
560 TeX ipc mode
561 ------------
563 For output generation of typeset text and to calculate the positions of markers
564 (see :meth:`textbox_pt.marker`) the DVI output of the TeX interpreter must be
565 read. In contrast, the text extent (:attr:`textbox_pt.left`,
566 :attr:`textbox_pt.right`, :attr:`textbox_pt.width`, :attr:`textbox_pt.height`,
567 :attr:`textbox_pt.depth`) is available without accessing the DVI output, as the
568 TeX interpreter is instructed by PyX to output it to stdout, which is read and
569 analysed at the typesetting step immediately.
571 Since TeX interpreters usually buffer the DVI output, the interpreter itself
572 needs to be terminated to get the DVI output. As :class:`MultiRunner` instances
573 can start a new interpreter when needed, this does not harm the functionality
574 and happens more or less unnoticable. Still it generates some penalty in terms
575 of execution speed, which can become huge for certain situations (alternation
576 between typesetting and marker access).
578 One of the effects of the ``texipc`` option available in almost all present TeX
579 interpreters is to flush the DVI output after each page. As PyX reads the DVI
580 output linearily, it can successfully read all output whithout stopping the TeX
581 interpreter. It is suggested to enable the ``texipc`` feature in the
582 system-wide configuration if available in the TeX interpreter being used.
585 .. _debug:
587 Debugging
588 ---------
590 PyX provides various functionality to collect details about the typesetting
591 process. First off all, PyX reads the output generated by the TeX interpreter
592 while it processes the text provided by the user. If the given
593 :class:`texmessage` parsers do not validate this output, an
594 :exc:`TexResultError` is raised immediately. The verbosity of this output can
595 be adjusted by the :class:`errordetail` setting of the :class:`SingleRunner`.
596 This might help in some cases to identify an error in the text passed for
597 typesetting, but for more complicated problems, other help is required.
599 One possibility is to output the actual code passed to the TeX interpreter. For
600 that you can pass a file name or a file handle to the ``copyinput`` argument of
601 the :class:`SingleRunner`. You can then process the text by the TeX interpreter
602 yourself to reproduce the issue outside of PyX.
604 Similarily you can also save the log output from the TeX interpreter. For that
605 you need to pass a log file name (with the suffix ``.log``) in the ``usefiles``
606 argument (which is a list of files) of the :class:`SingleRunner`. This list of
607 files are saved and restored in the temporary directory used by the TeX
608 interpreter. While originally it is meant to share, for example, a ``.aux``
609 file between several runs (for which the temporary directory is different and
610 removed after each run), it can do the same for the ``.log`` file (where the
611 restore feature is needless, but does not harm). PyX takes care of the proper
612 ``\jobname``, hence you can choose the filename arbitrarily with the exception
613 of the suffix, as the suffix is kept during the save and restore.
615 .. module:: pyx
616    :synopsis: The PyX package
618 Still, all this might not help to fully understand the problem you're facing.
619 For example there might be situations, where it is not clear which TeX
620 interpreter is actually used (when several executables are available and the
621 path setup within the Python interpreter differs from the one used on the
622 shell). In those situations it might help to enable some additional logging
623 output created by PyX. PyX uses the logging module from the standard library
624 and logs to a logger named ``"pyx"``. By default, various information about
625 executing external programms and locating files will not be echoed, as it is
626 written at info level, but PyX provides a simple convenience function to enable
627 the output of this logging level. Just call the :func:`pyxinfo` function
628 defined on the PyX package before actually start using the package in your
629 Python program:
631 .. autofunction:: pyxinfo
633 .. _chroot:
635 Typesetting insecure text
636 -------------------------
638 When typesetting text it is passed to a TeX interpreter unchanged\ [#]_. This
639 is a security problem if the text does not come from a trusted source. While
640 full access to all typesetting features is not considered a problem, you should
641 bear in mind that TeX code can be used to read data from any other file
642 accessible to the TeX process. To surely prevent this process from accessing
643 any other data unrelated to the TeX installation, you can setup a chroot
644 environment for the TeX interpreter and configure PyX to use it. This can be
645 achieved by setting the ``chroot`` option and adjusting the TeX interpreter
646 call and the ``filelocator`` configuration in the ``pyxrc``.
648 .. rubric:: Footnotes
650 .. [#] https://en.wikipedia.org/wiki/TeX
652 .. [#] https://en.wikipedia.org/wiki/Device_independent_file_format
654 .. [#] If you do not know what this is all about, you can just ignore this
655        paragraph. But be sure that the ``pyxgraphics`` keyword argument is
656        always set!
658 .. [#] The text is actually passed as an argument of a TeX command defined by
659        PyX, but this is a minor detail and has no effect regarding possible
660        attacks.