+++ /dev/null
- GNU LESSER GENERAL PUBLIC LICENSE
- Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL. It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
- This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it. You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations below.
-
- When we speak of free software, we are referring to freedom of use,
-not price. Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
- To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights. These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
- For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you. You must make sure that they, too, receive or can get the source
-code. If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it. And you must show them these terms so they know their rights.
-
- We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
- To protect each distributor, we want to make it very clear that
-there is no warranty for the free library. Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-\f
- Finally, software patents pose a constant threat to the existence of
-any free program. We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder. Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
- Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License. This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License. We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
- When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library. The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom. The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
- We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License. It also provides other free software developers Less
-of an advantage over competing non-free programs. These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries. However, the Lesser license provides advantages in certain
-special circumstances.
-
- For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it becomes
-a de-facto standard. To achieve this, non-free programs must be
-allowed to use the library. A more frequent case is that a free
-library does the same job as widely used non-free libraries. In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
- In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software. For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
- Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
- The precise terms and conditions for copying, distribution and
-modification follow. Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library". The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-\f
- GNU LESSER GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
- A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
- The "Library", below, refers to any such software library or work
-which has been distributed under these terms. A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language. (Hereinafter, translation is
-included without limitation in the term "modification".)
-
- "Source code" for a work means the preferred form of the work for
-making modifications to it. For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
- Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it). Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-
- 1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
- You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-\f
- 2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) The modified work must itself be a software library.
-
- b) You must cause the files modified to carry prominent notices
- stating that you changed the files and the date of any change.
-
- c) You must cause the whole of the work to be licensed at no
- charge to all third parties under the terms of this License.
-
- d) If a facility in the modified Library refers to a function or a
- table of data to be supplied by an application program that uses
- the facility, other than as an argument passed when the facility
- is invoked, then you must make a good faith effort to ensure that,
- in the event an application does not supply such function or
- table, the facility still operates, and performs whatever part of
- its purpose remains meaningful.
-
- (For example, a function in a library to compute square roots has
- a purpose that is entirely well-defined independent of the
- application. Therefore, Subsection 2d requires that any
- application-supplied function or table used by this function must
- be optional: if the application does not supply it, the square
- root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library. To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License. (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.) Do not make any other change in
-these notices.
-\f
- Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
- This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
- 4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
- If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library". Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
- However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library". The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
- When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library. The
-threshold for this to be true is not precisely defined by law.
-
- If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work. (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
- Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-\f
- 6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
- You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License. You must supply a copy of this License. If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License. Also, you must do one
-of these things:
-
- a) Accompany the work with the complete corresponding
- machine-readable source code for the Library including whatever
- changes were used in the work (which must be distributed under
- Sections 1 and 2 above); and, if the work is an executable linked
- with the Library, with the complete machine-readable "work that
- uses the Library", as object code and/or source code, so that the
- user can modify the Library and then relink to produce a modified
- executable containing the modified Library. (It is understood
- that the user who changes the contents of definitions files in the
- Library will not necessarily be able to recompile the application
- to use the modified definitions.)
-
- b) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (1) uses at run time a
- copy of the library already present on the user's computer system,
- rather than copying library functions into the executable, and (2)
- will operate properly with a modified version of the library, if
- the user installs one, as long as the modified version is
- interface-compatible with the version that the work was made with.
-
- c) Accompany the work with a written offer, valid for at
- least three years, to give the same user the materials
- specified in Subsection 6a, above, for a charge no more
- than the cost of performing this distribution.
-
- d) If distribution of the work is made by offering access to copy
- from a designated place, offer equivalent access to copy the above
- specified materials from the same place.
-
- e) Verify that the user has already received a copy of these
- materials or that you have already sent this user a copy.
-
- For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it. However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
- It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system. Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-\f
- 7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
- a) Accompany the combined library with a copy of the same work
- based on the Library, uncombined with any other library
- facilities. This must be distributed under the terms of the
- Sections above.
-
- b) Give prominent notice with the combined library of the fact
- that part of it is a work based on the Library, and explaining
- where to find the accompanying uncombined form of the same work.
-
- 8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License. Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License. However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
- 9. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Library or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
- 10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-\f
- 11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all. For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded. In such case, this License incorporates the limitation as if
-written in the body of this License.
-
- 13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation. If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-\f
- 14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission. For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this. Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
- NO WARRANTY
-
- 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
- END OF TERMS AND CONDITIONS
-\f
- How to Apply These Terms to Your New Libraries
-
- If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change. You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms of the
-ordinary General Public License).
-
- To apply these terms, attach the following notices to the library. It is
-safest to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
- <one line to give the library's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the library, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the
- library `Frob' (a library for tweaking knobs) written by James Random Hacker.
-
- <signature of Ty Coon>, 1 April 1990
- Ty Coon, President of Vice
-
-That's all there is to it!
-
-
--- /dev/null
+# The 3-clause BSD license
+
+Copyright (C) 2002-2023 Erik Max Francis
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--- /dev/null
+# The 3-clause BSD license
+
+%COPYRIGHT%
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--- /dev/null
+Metadata-Version: 2.1
+Name: empy
+Version: 4.0.1
+Summary: A templating system for Python.
+Home-page: http://www.alcyone.com/software/empy/
+Author: Erik Max Francis
+Author-email: software@alcyone.com
+License: BSD
+Platform: any
+Classifier: Development Status :: 6 - Mature
+Classifier: Environment :: Console
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Other Audience
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 3
+Classifier: Topic :: Software Development :: Interpreters
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Software Development :: Pre-processors
+Classifier: Topic :: Text Editors :: Text Processing
+Classifier: Topic :: Text Processing :: Filters
+Classifier: Topic :: Text Processing :: General
+Classifier: Topic :: Text Processing :: Markup
+Classifier: Topic :: Utilities
+License-File: LICENSE.md
+License-File: LICENSE.md.pre
+
+EmPy is a powerful, robust and mature
+templating system for inserting Python code in template text. EmPy
+takes a source document, processes it, and produces output. This is
+accomplished via expansions, which are signals to the EmPy system
+where to act and are indicated with markup. Markup is set off by a
+customizable prefix (by default the at sign, `@`). EmPy can expand
+arbitrary Python expressions, statements and control structures in
+this way, as well as a variety of additional special forms. The
+remaining textual data is sent to the output, allowing Python to be
+used in effect as a markup language.
+
+
+++ /dev/null
-Summary
-
- A powerful and robust templating system for Python.
-
-
-Overview
-
- EmPy is a system for embedding Python expressions and statements
- in template text; it takes an EmPy source file, processes it, and
- produces output. This is accomplished via expansions, which are
- special signals to the EmPy system and are set off by a special
- prefix (by default the at sign, '@'). EmPy can expand arbitrary
- Python expressions and statements in this way, as well as a
- variety of special forms. Textual data not explicitly delimited
- in this way is sent unaffected to the output, allowing Python to
- be used in effect as a markup language. Also supported are
- callbacks via hooks, recording and playback via diversions, and
- dynamic, chainable filters. The system is highly configurable via
- command line options and embedded commands.
-
- Expressions are embedded in text with the '@(...)' notation;
- variations include conditional expressions with '@(...?...!...)'
- and the ability to handle thrown exceptions with '@(...$...)'. As
- a shortcut, simple variables and expressions can be abbreviated as
- '@variable', '@object.attribute', '@function(arguments)',
- '@sequence' [index], and combinations. Full-fledged statements
- are embedded with '@{...}'. Control flow in terms of conditional
- or repeated expansion is available with '@[...]'. A '@' followed
- by a whitespace character (including a newline) expands to
- nothing, allowing string concatenations and line continuations.
- Comments are indicated with '@#' and consume the rest of the line,
- up to and including the trailing newline. '@%' indicate
- "significators," which are special forms of variable assignment
- intended to specify per-file identification information in a
- format which is easy to parse externally. Context name and line
- number changes can be done with '@?' and '@!' respectively.
- '@<...>' markups are customizeable by the user and can be used for
- any desired purpose. Escape sequences analogous to those in C can
- be specified with '@\...', and finally a '@@' sequence expands to
- a single literal at sign.
-
-
-Getting the software
-
- The current version of empy is 3.3.2.
-
- The latest version of the software is available in a tarball here:
- "http://www.alcyone.com/software/empy/empy-latest.tar.gz",
- http://www.alcyone.com/software/empy/empy-latest.tar.gz.
-
- The official URL for this Web site is
- "http://www.alcyone.com/software/empy/",
- http://www.alcyone.com/software/empy/.
-
-
-Requirements
-
- EmPy should work with any version of Python from 2.4 onward,
- including 3.x.
-
-
-License
-
- This code is released under the "LGPL",
- http://www.gnu.org/copyleft/lesser.html.
-
-
-Mailing lists
-
- There are two EmPy related mailing lists available. The first is
- a receive-only, very low volume list for important announcements
- (including releases). To subscribe, send an email to
- "empy-announce-list-subscribe@alcyone.com",
- mailto:empy-announce-list-subscribe@alcyone.com.
-
- The second is a general discussion list for topics related to
- EmPy, and is open for everyone to contribute; announcements
- related to EmPy will also be made on this list. The author of
- EmPy (and any future developers) will also be on the list, so it
- can be used not only to discuss EmPy features with other users,
- but also to ask questions of the author(s). To subscribe, send an
- email to "empy-list-subscribe@alcyone.com",
- mailto:empy-list-subscribe@alcyone.com.
-
-
-Basics
-
- EmPy is intended for embedding Python code in otherwise
- unprocessed text. Source files are processed, and the results are
- written to an output file. Normal text is sent to the output
- unchanged, but markups are processed, expanded to their results,
- and then written to the output file as strings (that is, with the
- 'str' function, not 'repr'). The act of processing EmPy source
- and handling markups is called "expansion."
-
- Code that is processed is executed exactly as if it were entered
- into the Python interpreter; that is, it is executed with the
- equivalent of 'eval' (for expressions) and 'exec' (for
- statements). EmPy is intended to be a very thin (though powerful)
- layer on top of a running Python system; Python and EmPy files can
- be mixed together (via command line options) without
- complications.
-
- By default the embedding prefix is the at sign ('@'), which
- appears neither in valid Python code nor commonly in arbitrary
- texts; it can be overridden with the -p option (or with the
- 'empy.setPrefix' function). The prefix indicates to the EmPy
- interpreter that a special sequence follows and should be
- processed rather than sent to the output untouched (to indicate a
- literal at sign, it can be doubled as in '@@').
-
- When the interpreter starts processing its target file, no modules
- are imported by default, save the 'empy' pseudomodule (see below),
- which is placed in the globals; the 'empy' pseudomodule is
- associated with a particular interpreter -- in fact, they are the
- same object -- and it is important that it not be removed from
- that interpreter's globals, nor that it be shared with other
- interpreters running concurrently (a name other than 'empy' can be
- specified with the -m option). The globals are not cleared or
- reset in any way. It is perfectly legal to set variables or
- explicitly import modules and then use them in later markups,
- *e.g.*, '@{import time} ... @time.time()'. Scoping rules are as
- in normal Python, although all defined variables and objects are
- taken to be in the global namespace.
-
- Indentation is significant in Python, and therefore is also
- significant in EmPy. EmPy statement markups ('@{...}'), when
- spanning multiple lines, must be flush with the left margin. This
- is because (multiline) statement markups are not treated specially
- in EmPy and are simply passed to the Python interpreter, where
- indentation is significant.
-
- Activities you would like to be done before any processing of the
- main EmPy file can be specified with the -I, -D, -E, -F, and -P
- options. -I imports modules, -D executes a Python variable
- assignment, -E executes an arbitrary Python (not EmPy) statement,
- -F executes a Python (not EmPy) file, and -P processes an EmPy
- (not Python) file. These operations are done in the order they
- appear on the command line; any number of each (including, of
- course, zero) can be used.
-
-
-Expansions
-
- The following markups are supported. For concreteness below, '@'
- is taken for the sake of argument to be the prefix character,
- although this can be changed.
-
- **'@# COMMENT NEWLINE'** -- A comment. Comments, including the
- trailing newline, are stripped out completely. Comments should
- only be present outside of expansions. The comment itself is
- not processed in any way: It is completely discarded. This
- allows '@#' comments to be used to disable markups. *Note:* As
- special support for "bangpaths" in Unix-like operating systems,
- if the first line of a file (or indeed any context) begins with
- '#!', and the interpreter has a 'processBangpaths' option set to
- true (default), it is treated as a '@#' comment. A '#!'
- sequence appearing anywhere else will be handled literally and
- unaltered in the expansion. Example::
-
- @# This line is a comment.
- @# This will NOT be expanded: @x.
-
- **'@? NAME NEWLINE'** -- Set the name of the current context to be
- the given string. Variables are not allowed here; the name is
- treated as a literal. (If you wish to use arbitrary
- expressions, use the 'empy.setContextName' function instead.)
- Example::
-
- @?NewName
- The context name is now @empy.identify()[0] (NewName).
-
- **'@! INTEGER NEWLINE'** -- Set the line number of the current
- context to be the given integer value; this is similar to the
- '#line' C preprocessor directive. This is done in such a way
- that the *next* line will have the specified numeric value, not
- the current one. Expressions are not allowed here; the number
- must be a literal integer. (If you wish to use arbitrary
- expressions, use the 'empy.setContextLine' function instead.)
- Example::
-
- @!100
- The context line is now @empy.identify()[1] (100).
-
- **'@ WHITESPACE'** -- A '@' followed by one whitespace character
- (a space, horizontal tab, vertical tab, carriage return, or
- newline) is expanded to nothing; it serves as a way to
- explicitly separate two elements which might otherwise be
- interpreted as being the same symbol (such as '@name@ s' to mean
- '@(name)s' -- see below). Also, since a newline qualifies as
- whitespace here, the lone '@' at the end of a line represents a
- line continuation, similar to the backslash in other languages.
- Coupled with statement expansion below, spurious newlines can be
- eliminated in statement expansions by use of the '@{...}@'
- construct. Example::
-
- This will appear as one word: salt@ water.
- This is a line continuation; @
- this text will appear on the same line.
-
- **'@\ ESCAPE_CODE'** -- An escape code. Escape codes in EmPy are
- similar to C-style escape codes, although they all begin with
- the prefix character. Valid escape codes include:
-
- '@\0' -- NUL, null
-
- '@\a' -- BEL, bell
-
- '@\b' -- BS, backspace
-
- '@\d' -- three-digital decimal code DDD
-
- '@\e' -- ESC, escape
-
- '@\f' -- FF, form feed
-
- '@\h' -- DEL, delete
-
- '@\n' -- LF, linefeed character, newline
-
- '@\oOOO' -- three-digit octal code OOO
-
- '@\qQQQQ' -- four-digit quaternary code QQQQ
-
- '@\r' -- CR, carriage return
-
- '@\s' -- SP, space
-
- '@\t' -- HT, horizontal tab
-
- '@\v' -- VT, vertical tab
-
- '@\xHH' -- two-digit hexadecimal code HH
-
- '@\z' -- EOT, end of transmission
-
- '@^X' -- the control character ^X
-
- Unlike in C-style escape codes, escape codes taking some number
- of digits afterward always take the same number to prevent
- ambiguities. Furthermore, unknown escape codes are treated as
- parse errors to discourage potential subtle mistakes. Note
- that, while '@\0' represents the NUL character, to represent an
- octal code, one must use '@\o...', in contrast to C. Example::
-
- This embeds a newline.@\nThis is on the following line.
- This beeps!@\a
- There is a tab here:@\tSee?
- This is the character with octal code 141: @\o141.
-
- **'@@'** -- A literal at sign ('@'). To embed two adjacent at
- signs, use '@@@@', and so on. Any literal at sign that you wish
- to appear in your text must be written this way, so that it will
- not be processed by the system. *Note:* If a prefix other than
- '@' has been chosen via the command line option, one expresses
- that literal prefix by doubling it, not by appending a '@'.
- Example::
-
- The prefix character is @@.
- To get the expansion of x you would write @@x.
-
- **'@)', '@]', '@}'** -- These expand to literal close parentheses,
- close brackets, and close braces, respectively; these are
- included for completeness and explicitness only. Example::
-
- This is a close parenthesis: @).
-
- **'@"..."', '@"""..."""', etc.** -- These string literals expand
- to the literals themselves, so '@"test"' expands to 'test'.
- Since they are inherently no-operations, the only reason for
- their use is to override their behavior with hooks.
-
- **'@( EXPRESSION )'** -- Evaluate an expression, and expand with
- the string (via a call to 'str') representation evaluation of
- that expression. Whitespace immediately inside the parentheses
- is ignored; '@( expression )' is equivalent to '@(expression)'.
- If the expression evaluates to 'None', nothing is expanded in
- its place; this allows function calls that depend on side
- effects (such as printing) to be called as expressions. (If you
- really *do* want a 'None' to appear in the output, then use the
- Python string '"None"'.) *Note:* If an expression prints
- something to 'sys.stdout' as a side effect, then that printing
- will be spooled to the output *before* the expression's return
- value is. Example::
-
- 2 + 2 is @(2 + 2).
- 4 squared is @(4**2).
- The value of the variable x is @(x).
- This will be blank: @(None).
-
- **'@( TEST ? THEN (! ELSE)_opt ($ EXCEPT)_opt )'** -- A special
- form of expression evaluation representing conditional and
- protected evaluation. Evaluate the "test" expression; if it
- evaluates to true (in the Pythonic sense), then evaluate the
- "then" section as an expression and expand with the 'str' of
- that result. If false, then the "else" section is evaluated and
- similarly expanded. The "else" section is optional and, if
- omitted, is equivalent to 'None' (that is, no expansion will
- take place). *Note*: For backward compatibility, the "else"
- section delimiter, '!', may be expressed as a ':'. This
- behavior is supported but deprecated.
-
- If the "except" section is present, then if any of the prior
- expressions raises an exception when evaluated, the expansion
- will be replaced with the evaluation of the except expression.
- (If the "except" expression itself raises, then that exception
- will be propagated normally.) The except section is optional
- and, if omitted, is equivalent to 'None' (that is, no expansion
- will take place). An exception (cough) to this is if one of
- these first expressions raises a SyntaxError; in that case the
- protected evaluation lets the error through without evaluating
- the "except" expression. The intent of this construct is to
- except runtime errors, and if there is actually a syntax error
- in the "try" code, that is a problem that should probably be
- diagnosed rather than hidden. Example::
-
- What is x? x is @(x ? "true" ! "false").
- Pluralization: How many words? @x word@(x != 1 ? 's').
- The value of foo is @(foo $ "undefined").
- Division by zero is @(x/0 $ "illegal").
-
- **'@ SIMPLE_EXPRESSION'** -- As a shortcut for the '@(...)'
- notation, the parentheses can be omitted if it is followed by a
- "simple expression." A simple expression consists of a name
- followed by a series of function applications, array
- subscriptions, or attribute resolutions, with no intervening
- whitespace. For example:
-
- - a name, possibly with qualifying attributes (*e.g.*,
- '@value', '@os.environ').
-
- - a straightforward function call (*e.g.*, '@min(2, 3)',
- '@time.ctime()'), with no space between the function name
- and the open parenthesis.
-
- - an array subscription (*e.g.*, '@array[index]',
- '@os.environ[name]', with no space between the name and
- the open bracket.
-
- - any combination of the above (*e.g.*,
- '@function(args).attr[sub].other[i](foo)').
-
- In essence, simple expressions are expressions that can be
- written ambiguously from text, without intervening space. Note
- that trailing dots are not considered part of the expansion
- (*e.g.*, '@x.' is equivalent to '@(x).', not '@(x.)', which
- would be illegal anyway). Also, whitespace is allowed within
- parentheses or brackets since it is unambiguous, but not between
- identifiers and parentheses, brackets, or dots. Explicit
- '@(...)' notation can be used instead of the abbreviation when
- concatenation is what one really wants (*e.g.*, '@(word)s' for
- simple pluralization of the contents of the variable 'word').
- As above, if the expression evaluates to the 'None' object,
- nothing is expanded. Note that since a curly appearing where
- EmPy would expect an open parenthesis or bracket in is
- meaningless in Python, it is treated as a parse error (*e.g.*,
- '@x{1, 2}' results in an error). Example::
-
- The value of x is @x.
- The ith value of a is @a[i].
- The result of calling f with q is @f(q).
- The attribute a of x is @x.a.
- The current time is @time.ctime(time.time()).
- The current year is @time.localtime(time.time())[0].
- These are the same: @min(2,3) and @min(2, 3).
- But these are not the same: @min(2, 3) vs. @min (2, 3).
- The plural of @name is @(name)s, or @name@ s.
-
- **'@` EXPRESSION `'** -- Evaluate a expression, and expand with
- the 'repr' (instead of the 'str' which is the default) of the
- evaluation of that expression. This expansion is primarily
- intended for debugging and is unlikely to be useful in actual
- practice. That is, a '@`...`' is identical to '@(repr(...))'.
- Example::
-
- The repr of the value of x is @`x`.
- This print the Python repr of a module: @`time`.
- This actually does print None: @`None`.
-
- **'@: EXPRESSION : DUMMY :'** -- Evaluate an expression and then
- expand to a '@:', the original expression, a ':', the evaluation
- of the expression, and then a ':'. The current contents of the
- dummy area are ignored in the new expansion. In this sense it
- is self-evaluating; the syntax is available for use in
- situations where the same text will be sent through the EmPy
- processor multiple times. Example::
-
- This construct allows self-evaluation:
- @:2 + 2:this will get replaced with 4:
-
- **'@{ STATEMENTS }'** -- Execute a (potentially compound)
- statement; statements have no return value, so the expansion is
- not replaced with anything. Multiple statements can either be
- separated on different lines, or with semicolons; indentation is
- significant, just as in normal Python code. Statements,
- however, can have side effects, including printing; output to
- 'sys.stdout' (explicitly or via a 'print' statement) is
- collected by the interpreter and sent to the output (unless this
- behavior is suppressed with the -n option). The usual Python
- indentation rules must be followed, although if the statement
- consists of only one statement, leading and trailing whitespace
- is ignored (*e.g.*, '@{ print time.time() }' is equivalent to
- '@{print time.time()}'). Example::
-
- @{x = 123}
- @{a = 1; b = 2}
- @{print time.time()}
- @# Note that extra newlines will appear above because of the
- @# newlines trailing the close braces. To suppress them
- @# use a @ before the newline:
- @{
- for i in range(10):
- print "i is %d" % i
- }@
- @{print "Welcome to EmPy."}@
-
- **'@% KEY (WHITESPACE VALUE)_opt NEWLINE'** -- Declare a
- significator. Significators consume the whole line (including
- the trailing newline), and consist of a key string containing no
- whitespace, and than optional value prefixed by whitespace. The
- key may not start with or contain internal whitespace, but the
- value may; preceding or following whitespace in the value is
- stripped. Significators are totally optional, and are intended
- to be used for easy external (that is, outside of EmPy)
- identification when used in large scale environments with many
- EmPy files to be processed. The purpose of significators is to
- provide identification information about each file in a special,
- easy-to-parse form so that external programs can process the
- significators and build databases, independently of EmPy.
- Inside of EmPy, when a significator is encountered, its key,
- value pair is translated into a simple assignment of the form
- '__KEY__ = VALUE' , where "__KEY__" is the key string with two
- underscores on either side and "VALUE" is a Python expression.
- Example::
-
- @%title "Gravitation"
- @%author "Misner", "Thorne", "Wheeler"
- @%publisher "W.H. Freeman and Company"
- @%pages 1279
- @%keywords 'physics', 'gravity', 'Einstein', 'relativity'
- @%copyright 1970, 1971
-
- **'@< CONTENTS >'** -- Invoke a custom markup. The custom markup
- is a special markup reserved for use by the user; it has no
- prescribed meaning on its own. If 'contents' is a string
- representing what appears in between the angle brackets, then
- expanding this markup is equivalent to
- 'empy.invokeCallback(contents)'. See the "Custom markup"
- section for more information.
-
-
-Control
-
- EmPy version 3 and above includes the ability to direct
- conditional and repeated expansion of blocks of EmPy code with
- control markups (the obsolescent "substitution" markups are
- unavailable as of version 3.0). Control markups have analogs to
- control flow structures in Python such as 'if/elif/else', 'for', and
- 'while'. Control markups are set off with the '@[...]' notation.
-
- Control markups are designed to be used in precisely the same way
- that their internal Python analogues are used, except that the
- control markups are intended to be used where there is much more
- markup than control structure.
-
- Some control markups are considered "primary," (*e.g.*, 'if',
- 'for', 'while') as they begin a control markup. Others are
- considered "secondary," since they can only appear inside control
- flow markups delineated by primary markups (*e.g.*, 'elif',
- 'else', 'continue', 'break').
-
- Since EmPy, unlike Python, cannot use indentation to determine
- where control structures begin and end, all primary control
- markups *must* be followed by a corresponding terminating control
- markup::
-
- @[PRIMARY ...]...@[end PRIMARY]
-
- (where 'PRIMARY' represents one of the primary keywords). The end
- markup is mandatory, as is the space between the 'end' and the
- starting keyword. For instance::
-
- @# If `person' is alive, show their age.
- @person.name is @
- @[if person.isAlive]@person.age@[else]dead@[end if].
-
- All primary markups must be terminated in this way, and the
- keyword appearing in the appropriate 'end' markup must match the
- primary markup it corresponds to; if either of these conditions
- are not satisfied, the result is a parse error. Everything
- between the starting control flow marker ('@[PRIMARY ...]') and
- the ending marker ('@[end PRIMARY]') -- including other markups,
- even control markups -- is considered part of the markup. Control
- markups can be nested::
-
- @# Print all non-false elements on separate lines.
- @[for elem in elements]@[if elem]@elem@\n@[end if]@[end for]
-
- Three major types of primary control markups are available:
- conditional (*e.g.*, 'if', 'try'), looping (*e.g.*, 'for',
- 'while'), and definitional (*e.g.*, 'def', discussed below).
- Conditional control markups conditionally expand their contents,
- whereas looping control markups repeatedly expand their contents.
- The third type, definitional markups, will define new objects in
- the globals relating to their contents. Conditional and looping
- markups also differ in one substantial respect: Looping constructs
- support '@[continue]' and '@[break]' markups which, like their
- Python equivalents, continue with the next iteration or break out
- of the innermost looping construct, respectively ('@[continue]'
- and '@[break]' markups have no meaning inside conditional markups
- and are an error). Also like their Python equivalents,
- '@[continue]' and '@[break]' may appear inside nested markups, so
- long as they ultimately are contained by at least one looping
- control markup::
-
- @# Walk a long a linked list, printing each element.
- @[while 1]@
- @node
- @{node = node.next}@
- @[if not node]@[break]@[end if]@
- @[end while]
-
- The provided markups are designed to mimic the internal Python
- control structures as closely as possible. The supported control
- markups are (the phrases in all uppercase are intended to signify
- user-selectable patterns)::
-
- @[if CONDITION1]...@[elif CONDITION2]...@[else]...@[end if]
- @[try]...@[except ...]...@[except ...]...@[end try]
- @[try]...@[finally]...@[end try]
- @[for VARIABLE in SEQUENCE]...@[else]...@[end for]
- @[while CONDITION]...@[else]...@[end while]
- @[def SIGNATURE]...@[end def]
-
- All recognizable forms behave like their Python equivalents; 'if'
- can contain multiple 'elif' secondary markups within it; the
- 'else' markups are optional (but must appear at the end), the
- 'try' form with the 'except' clause can contain multiple ones
- which are handled in sequence, the 'try' form can either contain
- one or more 'except' clauses or one 'finally' clause (but not
- both), and the 'for' and 'while' structures can contain 'continue'
- or 'break' clauses internally (even if contained within other
- markups).
-
- The third type of primary control markup is "definitional," in
- that they create objects in the globals for later use (*e.g.*,
- 'def'). This allows the definition of a callable object which,
- when called, will expand the contained markup (which can in turn,
- of course, contain further markups). The argument to the markup
- can be any legal Python function signature::
-
- @[def f(x, y, z=2, *args, **keywords)]...@[end def]
-
- would define a function in the globals named 'f' that takes the
- given arguments. A macro markup of the form '@[def
- SIGNATURE]CODE@[end def]' is equivalent to the Python code::
-
- def SIGNATURE:
- r"""CODE""" # so it is a doc string
- empy.expand(r"""CODE""", locals())
-
- That is, it creates a Python function with the same name and
- function arguments, whose docstring is the contents of the EmPy
- markup that will be expanded when called. And, when called, it
- will expand those contents, with the locals passed in.
-
-
-Unicode support
-
- EmPy version 3.1 and above includes intrinsic Unicode support.
- EmPy's Unicode support defers to Python's internal Unicode
- support, available in Python 2.0 and up, in order to allow
- seamless and transparent translation of different encodings to the
- native Python Unicode format.
-
- Knowledge of Python's Unicode support is expected, although not
- completely required, to gain full benefit of EmPy's Unicode
- features. To enable Unicode support, start EmPy with the
- -u/--unicode option. EmPy will then transparently encode from the
- input stream, process markups internally with native Unicode, and
- then decode transparently to the output stream.
-
- By default, Python sets 'sys.stdin' and 'sys.stdout' with a
- default encoding which is accessible via
- 'sys.getdefaultencoding()'; encodings are represented by string
- names. These streams have encodings set by the system and
- *cannot* be changed.
-
- However, encodings for newly created files (files to be read when
- specified on the command line, and/or files to be written when
- used with the -o and -a arguments) can be specified for EmPy via
- command line options. The --unicode-encoding option
- simultaneously indicates the encoding to be used for both input
- and output, whereas the --unicode-input-encoding and
- --unicode-output-encoding options can each be used to specify
- different encodings for both input and output. (If an encoding is
- not explicitly indicated, it resorts to the system default in
- 'sys.getdefaultencoding()', which is locale dependent.)
-
- Python's Unicode implementation has the concept of error handlers,
- registered with the 'codecs' module, which can be specified to
- determine what action should take place if input cannot be decoded
- into Unicode, or Unicode cannot be encoded into output. EmPy uses
- these same "errors," as they are called, and can be specified via
- command line options. The three most common error handlers are:
- 'ignore', where invalid sequences are simply ignored; 'replace',
- where invalid sequences are replaced with an encoding-specific
- indicator, usually a question mark; and 'strict', where invalid
- sequences raise an error. The --unicode-errors command line
- option specifies the same error handler to be used for both input
- and output, and the --unicode-input-errors and
- --unicode-output-errors options can specify different error
- handlers for input and output. If an error handler is not
- explicitly specified, the 'strict' handler (which will raise
- errors) is used.
-
- Remember, to specify input encodings or errors that will take
- effect, one cannot take input from 'sys.stdin' and must explicitly
- specify an EmPy file to process on the command line. Similarly,
- for output encodings or errors, 'sys.stdout' cannot be used and an
- explicit output file must be specified with the -o or -a options.
- It is perfectly valid to enable the Unicode subsystem (-u option)
- while using 'sys.stdin' and 'sys.stdout', but the encodings and
- errors of these preexisting streams cannot be changed.
-
- Combined with the --no-prefix option, which disables all markup
- processing, EmPy can act merely as an encoding translator, relying
- on Python's Unicode facilities::
-
- em.py --no-prefix \
- --unicode-input-encoding=utf-8 \
- --unicode-output-encoding=latin-1 \
- -o filename.Latin-1 filename.UTF-8
-
-
-Significators
-
- Significators, introduced in EmPy version 1.2, are intended to
- represent special assignment in a form that is easy to externally
- parse. For instance, if one has a system that contains many EmPy
- files, each of which has its own title, one could use a 'title'
- significator in each file and use a simple regular expression to
- find this significator in each file and organize a database of the
- EmPy files to be built. This is an easier proposition than, for
- instance, attempting to grep for a normal Python assignment
- (inside a '@{...}' expansion) of the desired variable.
-
- Significators look like the following::
-
- @%KEY VALUE
-
- including the trailing newline, where "key" is a name and "value"
- is a Python expression, and are separated by any whitespace. This
- is equivalent to the following Python code::
-
- __KEY__ = VALUE
-
- That is to say, a significator key translates to a Python variable
- consisting of that key surrounded by double underscores on either
- side. The value may contain spaces, but the key may not. So::
-
- @%title "All Roads Lead to Rome"
-
- translates to the Python code::
-
- __title__ = "All Roads Lead to Rome"
-
- but obviously in a way that easier to detect externally than if
- this Python code were to appear somewhere in an expansion. Since
- significator keys are surrounded by double underscores,
- significator keys can be any sequence of alphanumeric and
- underscore characters; choosing '123' is perfectly valid for a
- significator (although straight), since it maps to the name
- '__123__' which is a legal Python identifier.
-
- Note the value can be any Python expression. The value can be
- omitted; if missing, it is treated as 'None'.
-
- Significators are completely optional; it is completely legal for
- a EmPy file or files to be processed without containing any
- significators. Significators can appear anywhere within a file
- outside of other markups, but typically they are placed near the
- top of the file to make them easy to spot and edit by humans.
-
- A regular expression string designed to match significators (with
- the default prefix) is available as 'empy.SIGNIFICATOR_RE_STRING',
- and also is a toplevel definition in the 'em' module itself.
-
-
-
-Diversions
-
- EmPy supports an extended form of diversions, which are a
- mechanism for deferring and recalling output on demand, similar to
- the functionality included in m4. Multiple "streams" of output
- can be diverted (deferred) and undiverted (recalled) in this
- manner. A diversion is identified with a name, which is any
- immutable object such an integer or string. When recalled,
- diverted code is *not* resent through the EmPy interpreter
- (although a filter could be set up to do this).
-
- By default, no diversions take place. When no diversion is in
- effect, processing output goes directly to the specified output
- file. This state can be explicitly requested at any time by
- calling the 'empy.stopDiverting' function. It is always legal to
- call this function.
-
- When diverted, however, output goes to a deferred location which
- can then be recalled later. Output is diverted with the
- 'empy.startDiversion' function, which takes an argument that is
- the name of the diversion. If there is no diversion by that name,
- a new diversion is created and output will be sent to that
- diversion; if the diversion already exists, output will be
- appended to that preexisting diversion.
-
- Output send to diversions can be recalled in two ways. The first
- is through the 'empy.playDiversion' function, which takes the
- name of the diversion as an argument. This recalls the named
- diversion, sends it to the output, and then erases that
- diversion. A variant of this behavior is the
- 'empy.replayDiversion', which recalls the named diversion but does
- not eliminate it afterwards; 'empy.replayDiversion' can be
- repeatedly called with the same diversion name, and will replay
- that diversion repeatedly. 'empy.createDiversion' create a
- diversion without actually diverting to it, for cases where you
- want to make sure a diversion exists but do not yet want to send
- anything to it.
-
- The diversion object itself can be retrieved with
- 'empy.retrieveDiversion'. Diversions act as writable
- file-objects, supporting the usual 'write', 'writelines', 'flush',
- and 'close' methods. The data that has been diverted to them can
- be retrieved in one of two ways; either through the 'asString'
- method, which returns the entire contents of the diversion as a
- single strong, or through the 'asFile' method, which returns the
- contents of the diversion as a readable (not writable) file-like
- object.
-
- Diversions can also be explicitly deleted without recalling them
- with the 'empy.purgeDiversion' function, which takes the desired
- diversion name as an argument.
-
- Additionally there are three functions which will apply the above
- operations to all existing diversions: 'empy.playAllDiversions',
- 'empy.replayAllDiversions', and 'empy.purgeAllDiversions'. All
- three will do the equivalent of a 'empy.stopDiverting' call before
- they do their thing.
-
- The name of the current diversion can be requested with the
- 'empy.getCurrentDiversion' function; also, the names of all
- existing diversions (in sorted order) can be retrieved with
- 'empy.getAllDiversions'.
-
- When all processing is finished, the equivalent of a call to
- 'empy.playAllDiversions' is done.
-
-
-Filters
-
- EmPy also supports dynamic filters, introduced in version 1.3.
- Filters are put in place right "before" the final output file, and
- so are only invoked after all other processing has taken place
- (including interpreting and diverting). Filters take input, remap
- it, and then send it to the output.
-
- The current filter can be retrieved with the 'empy.getFilter'
- function. The filter can be cleared (reset to no filter) with
- 'empy.resetFilter' and a special "null filter" which does not send
- any output at all can be installed with 'empy.nullFilter'. A
- custom filter can be set with the 'empy.setFilter' function; for
- convenience, specialized shortcuts for filters preexist and can be
- used in lieu of actual 'empy.Filter' instances for the
- 'empy.setFilter' or 'empy.attachFilter' argument:
-
- - 'None' is a special filter meaning "no filter"; when installed,
- no filtering whatsoever will take place. 'empy.setFilter(None)'
- is equivalent to 'empy.resetFilter()'.
-
- - '0' (or any other numeric constant equal to zero) is another
- special filter that represents the null filter; when installed,
- no output will ever be sent to the filter's sink.
-
- - A filter specified as a function (or lambda) is expected to take
- one string argument and return one string argument; this filter
- will execute the function on any input and use the return value
- as output.
-
- - A filter that is a string is a 256-character table is
- substituted with the result of a call to 'string.translate'
- using that table.
-
- - A filter can be an instance of a subclass of 'empy.Filter'.
- This is the most general form of filter. (In actuality, it can
- be any object that exhibits a 'Filter' interface, which would
- include the normal file-like 'write', 'flush', and 'close'
- methods, as well as 'next', 'attach', and 'detach' methods for
- filter-specific behavior.)
-
- - Finally, the argument to 'empy.setFilter' can be a Python list
- consisting of one or more of the above objects. In that case,
- those filters are chained together in the order they appear in
- the list. An empty list is the equivalent of 'None'; all
- filters will be uninstalled.
-
- Filters are, at their core, simply file-like objects (minimally
- supporting 'write', 'flush', and 'close' methods that behave in
- the usual way) which, after performing whatever processing they
- need to do, send their work to the next file-like object or filter
- in line, called that filter's "sink." That is to say, filters can
- be "chained" together; the action of each filter takes place in
- sequence, with the output of one filter being the input of the
- next. Additionally, filters support a '_flush' method (note the
- leading underscore) which will always flush the filter's
- underlying sink; this method should be not overridden.
-
- Filters also support three additional methods, not part of the
- traditional file interface: 'attach', which takes as an argument a
- file-like object (perhaps another filter) and sets that as the
- filter's "sink" -- that is, the next filter/file-like object in
- line. 'detach' (which takes no arguments) is another method which
- flushes the filter and removes its sink, leaving it isolated.
- Finally, 'next' is an accessor method which returns the filter's
- sink -- or 'None', if the filter does not yet have a sink
- attached.
-
- To create your own filter, you can create an object which supports
- the above described interface, or simply derive from the
- 'empy.Filter' class and override its 'write' and possibly 'flush'
- methods. You can chain filters together by passing them as
- elements in a list to the 'empy.setFilter' function, or you can
- chain them together manually with the 'attach' method::
-
- firstFilter.attach(secondFilter)
- empy.setFilter(firstFilter)
-
- or just let EmPy do the chaining for you::
-
- empy.setFilter([firstFilter, secondFilter])
-
- In either case, EmPy will walk the filter chain and find the end
- and then hook that into the appropriate interpreter stream; you
- need not do this manually. The function 'empy.attachFilter' can
- be used to attach a single filter (or shortcut, as above) to the
- end of a currently existing chain. Note that unlike its cousin
- 'empy.setFilter', one cannot pass a sequence of filters (or filter
- shortcuts) to 'empy.attachFilter'. (If there is no existing
- filter chain installed, 'empy.attachFilter' will behave the same
- as 'empy.setFilter'.)
-
- Subclasses of 'empy.Filter' are already provided with the above
- null, function, and string functionality described above; they are
- 'NullFilter', 'FunctionFilter', and 'StringFilter', respectively.
- In addition, a filter which supports buffering, 'BufferedFilter',
- is provided. Several variants are included: 'SizeBufferedFilter',
- a filter which buffers into fixed-sized chunks,
- 'LineBufferedFilter', a filter which buffers by lines, and
- 'MaximallyBufferedFilter', a filter which completely buffers its
- input.
-
-
-Hooks
-
- The EmPy system allows for the registry of hooks with a running
- EmPy interpreter. Originally introduced in version 2.0 and much
- improved in 3.2, hooks are objects, registered with an
- interpreter, whose methods represent specific callbacks. Any
- number of hook objects can be registered with an interpreter, and
- when a callback is invoked, the associated method on each one of
- those hook objects will be called by the interpreter in sequence.
-
- Hooks are simply instances, nominally derived from the 'empy.Hook'
- class. The 'empy.Hook' class itself defines a series of methods,
- with the expected arguments, which would be called by a running
- EmPy interpreter. This scenario, much improved from the prior
- implementation in 2.0, allows hooks to keep state and have more
- direct access to the interpreter they are running in (the
- 'empy.Hook' instance contains an 'interpreter' attribute).
-
- To use a hook, derive a class from 'empy.Hook' and override the
- desired methods (with the same signatures as they appear in the
- base class). Create an instance of that subclass, and then
- register it with a running interpreter with the 'empy.addHook'
- function. (This same hook instance can be removed with the
- 'empy.removeHook' function.)
-
- More than one hook instance can be registered with an interpreter;
- in such a case, the appropriate methods are invoked on each
- instance in the order in which they were registered. To adjust
- this behavior, an optional 'prepend' argument to the
- 'empy.addHook' function can be used dictate that the new hook
- should placed at the *beginning* of the sequence of hooks, rather
- than at the end (which is the default).
-
- All hooks can be enabled and disabled entirely for a given
- interpreter; this is done with the 'empy.enableHooks' and
- 'empy.disableHooks' functions. By default hooks are enabled, but
- obviously if no hooks have been registered no hook callbacks will
- be made. Whether hooks are enabled or disabled can be determined
- by calling 'empy.areHooksEnabled'. To get a (copy of) the list of
- registered hooks, call 'empy.getHooks'. Finally, to invoke a hook
- manually, use 'empy.invokeHook'.
-
- For a list of supported hook callbacks, see the 'empy.Hook' class
- definition.
-
- As a practical example, this sample Python code would print a
- pound sign followed by the name of every file that is included
- with 'empy.include'::
-
- class IncludeHook(empy.Hook):
- def beforeInclude(self, name, file, locals):
- print "# %s" % name
-
- empy.addHook(IncludeHook())
-
-
-Custom markup
-
- Since version 3.2.1, the markup '@<...>' is reserved for
- user-defined use. Unlike the other markups, this markup has no
- specified meaning on its own, and can be provided a meaning by the
- user. This meaning is provided with the use of a "custom
- callback," or just "callback," which can be set, queried, or reset
- using the pseudomodule function.
-
- The custom callback is a callable object which, when invoked, is
- passed a single argument: a string representing the contents of
- what was found inside the custom markup '@<...>'.
-
- To register a callback, call 'empy.registerCallback'. To remove
- one, call 'empy.deregisterCallback'. To retrieve the callback (if
- any) registered with the interpreter, use 'empy.getCallback'.
- Finally, to invoke the callback just as if the custom markup were
- encountered, call 'empy.invokeCallback'. For instance, '@<This
- text>' would be equivalent to the call '@empy.invokeCallback("This
- text")'.
-
- By default, to invoke a callback (either explicitly with
- 'empy.invokeCallback' or by processing a '@<...>' custom markup)
- when no callback has been registered is an error. This behavior
- can be changed with the 'CALLBACK_OPT' option, or the
- --no-callback-error command line option.
-
-
-Pseudomodule
-
- The 'empy' pseudomodule is available only in an operating EmPy
- system. (The name of the module, by default 'empy', can be
- changed with the -m option or the 'EMPY_PSEUDO' environment
- variable). It is called a pseudomodule because it is not actually
- a module, but rather exports a module-like interface. In fact,
- the pseudmodule is actually the same internal object as the
- interpreter itself.
-
- The pseudomodule contains the following functions and objects (and
- their signatures, with a suffixed 'opt' indicating an optional
- argument):
-
- First, basic identification:
-
- **'VERSION'** -- A constant variable which contains a
- string representation of the EmPy version.
-
- **'SIGNIFICATOR_RE_STRING'** -- A constant variable representing a
- regular expression string (using the default prefix) that can be
- used to find significators in EmPy code.
-
- **'SIGNIFICATOR_RE_SUFFIX'** -- The portion of the significator
- regular expression string excluding the prefix, so that those
- using non-standard prefix can build their own custom regular
- expression string with 'myPrefix + empy.SIGNIFICATOR_RE_SUFFIX'.
-
- **'interpreter'** -- The instance of the interpreter that is
- currently being used to perform execution. *Note:* This is now
- obsolete; the pseudomodule is itself the interpreter. Instead
- of using 'empy.interpreter', simply use 'empy'.
-
- **'argv'** -- A list consisting of the name of the primary EmPy
- script and its command line arguments, in analogue to the
- 'sys.argv' list.
-
- **'args'** -- A list of the command line arguments following the
- primary EmPy script; this is equivalent to 'empy.argv[1:]'.
-
- **'identify() -> string, integer'** -- Retrieve identification
- information about the current parsing context. Returns a
- 2-tuple consisting of a filename and a line number; if the file
- is something other than from a physical file (*e.g.*, an
- explicit expansion with 'empy.expand', a file-like object within
- Python, or via the -E or -F command line options), a string
- representation is presented surrounded by angle brackets. Note
- that the context only applies to the *EmPy* context, not the
- Python context.
-
- **'atExit(callable)'** -- Register a callable object (such as a
- function) taking no arguments which will be called at the end of
- a normal shutdown. Callable objects registered in this way are
- called in the reverse order in which they are added, so the
- first callable registered with 'empy.atExit' is the last one to
- be called. Note that although the functionality is related to
- hooks, 'empy.atExit' does no work via the hook mechanism, and
- you are guaranteed that the interpreter and stdout will be in a
- consistent state when the callable is invoked.
-
- Context manipulation:
-
- **'pushContext(name_opt, line_opt)'** -- Create a new context with
- the given name and line and push it on the stack.
-
- **'popContext()'** -- Pop the top context and dispose of it.
-
- **'setContextName(name)'** -- Manually set the name of the current
- context.
-
- **'setContextLine(line)'** -- Manually set the line number of the
- current context; line must be a numeric value. Note that
- afterward the line number will increment by one for each newline
- that is encountered, as before.
-
- Globals manipulation:
-
- **'getGlobals()'** -- Retrieve the globals dictionary for this
- interpreter. Unlike when calling 'globals()' in Python, this
- dictionary *can* be manipulated and you *can* expect changes you
- make to it to be reflected in the interpreter that holds it.
-
- **'setGlobals(globals)'** -- Reseat the globals dictionary
- associated with this interpreter to the provided mapping type.
-
- **'updateGlobals(globals)'** -- Merge the given dictionary into
- this interpreter's globals.
-
- **'clearGlobals(globals_opt)'** -- Clear out the globals
- (restoring, of course, the 'empy' pseudomodule). Optionally,
- instead of starting with a refresh dictionary, use the
- dictionary provided.
-
- **'saveGlobals(deep=True)'** -- Save a copy of the globals onto an
- internal history stack from which it can be restored later. The
- optional 'deep' argument indicates whether or not the copying
- should be a deep copy (default) or a shallow one. Copying is
- done with 'copy.deepcopy' or 'copy.copy', respectively.
-
- **'restoreGlobals(destructive=True)'** -- Restore the most
- recently saved globals from the history stack to as the current
- globals for this instance. The optional 'destructive' argument
- indicates whether or not the restore should remove the restored
- globals from the history stack (default), or whether it should
- be left there for subsequent restores.
-
- Types:
-
- **'Interpreter'** -- The actual interpreter class.
-
- The following functions allow direct execution; optional 'locals'
- arguments, if specified, are treated as the locals dictionary in
- evaluation and execution:
-
- **'defined(name, locals_opt)'** -- Return true if the given name
- is defined either in the (optional) locals or the interpreter
- globals; return false otherwise.
-
- **'evaluate(expression, locals_opt)'** -- Evaluate the given
- expression.
-
- **'serialize(expression, locals_opt)'** -- Serialize the
- expression, just as the interpreter would: If it is not None,
- convert it to a string with the 'str' builtin function, and then
- write out the result. If it evaluates to None, do nothing.
-
- **'execute(statements, locals_opt)'** -- Execute the given
- statement(s).
-
- **'single(source, locals_opt)'** -- Interpret the "single" source
- code, just as the Python interactive interpreter would.
-
- **'import_(name, locals_opt)'** -- Import a module.
-
- **'atomic(name, value, locals_opt)'** -- Perform a single, atomic
- assignment. In this case name is the string denoating the name
- of the (single) variable to be assigned to, and value is a
- Python object which the name is to be bound to.
-
- **'assign(name, value, locals_opt)'** -- Perform general
- assignment. This decays to atomic assignment (above) in the
- normal case, but supports "tuple unpacking" in the sense that if
- name string contains commas, it is treated as a sequence of
- names and memberwise assignment with each member of the value
- (still a Python object, but which must be a sequence). This
- function will raise a 'TypeError' or 'ValueError' just like
- Python would if tuple unpacking is not possible (that is, if the
- value is not a sequence or is of an incompatible length,
- respectively). This only supports the assignment of Python
- identifiers, not arbitrary Python lvalues.
-
- **'significate(key, value_opt, locals_opt)'** -- Do a manual
- signification. If 'value' is not specified, it is treated as
- 'None'.
-
- The following functions relate to source manipulation:
-
- **'include(file_or_filename, locals_opt)'** -- Include another
- EmPy file, by processing it in place. The argument can either
- be a filename (which is then opened with 'open' in text mode) or
- a file object, which is used as is. Once the included file is
- processed, processing of the current file continues. Includes
- can be nested. The call also takes an optional locals
- dictionary which will be passed into the evaluation function.
-
- **'expand(string, locals_opt)' -> string** -- Explicitly invoke
- the EmPy parsing system to process the given string and return
- its expansion. This allows multiple levels of expansion,
- *e.g.*, '@(empy.expand("@(2 + 2)"))'. The call also takes an
- optional locals dictionary which will be passed into the
- evaluation function. This is necessary when text is being
- expanded inside a function definition and it is desired that the
- function arguments (or just plain local variables) are available
- to be referenced within the expansion.
-
- **'quote(string) -> string'** -- The inverse process of
- 'empy.expand', this will take a string and return a new string
- that, when expanded, would expand to the original string. In
- practice, this means that appearances of the prefix character
- are doubled, except when they appear inside a string literal.
-
- **'escape(string, more_opt) -> string'** -- Given a string, quote
- the nonprintable characters contained within it with EmPy
- escapes. The optional 'more' argument specifies additional
- characters that should be escaped.
-
- **'flush()'** -- Do an explicit flush on the underlying stream.
-
- **'string(string, name_opt, locals_opt)'** -- Explicitly process a
- string-like object. This differs from 'empy.expand' in that the
- string is directly processed into the EmPy system, rather than
- being evaluated in an isolated context and then returned as a
- string.
-
- Changing the behavior of the pseudomodule itself:
-
- **'flatten(keys_opt)'** -- Perform the equivalent of 'from empy
- import ...' in code (which is not directly possible because
- 'empy' is a pseudomodule). If keys is omitted, it is taken as
- being everything in the 'empy' pseudomodule. Each of the
- elements of this pseudomodule is flattened into the globals
- namespace; after a call to 'empy.flatten', they can be referred
- to simple as globals, *e.g.*, '@divert(3)' instead of
- '@empy.divert(3)'. If any preexisting variables are bound to
- these names, they are silently overridden. Doing this is
- tantamount to declaring an 'from ... import ...' which is often
- considered bad form in Python.
-
- Prefix-related functions:
-
- **'getPrefix() -> char'** -- Return the current prefix.
-
- **'setPrefix(char)'** -- Set a new prefix. Immediately after this
- call finishes, the prefix will be changed. Changing the prefix
- affects only the current interpreter; any other created
- interpreters are unaffected. Setting the prefix to None or the
- null string means that no further markups will be processed,
- equivalent to specifying the --no-prefix command line argument.
-
- Diversions:
-
- **'stopDiverting()'** -- Any diversions that are currently taking
- place are stopped; thereafter, output will go directly to the
- output file as normal. It is never illegal to call this
- function.
-
- **'createDiversion(name)'** -- Create a diversion, but do not
- begin diverting to it. This is the equivalent of starting a
- diversion and then immediately stopping diversion; it is used in
- cases where you want to make sure that a diversion will exist
- for future replaying but may be empty.
-
- **'startDiversion(name)'** -- Start diverting to the specified
- diversion name. If such a diversion does not already exist, it
- is created; if it does, then additional material will be
- appended to the preexisting diversions.
-
- **'playDiversion(name)'** -- Recall the specified diversion and
- then purge it. The provided diversion name must exist.
-
- **'replayDiversion(name)'** -- Recall the specified diversion
- without purging it. The provided diversion name must exist.
-
- **'purgeDiversion(name)'** -- Purge the specified diversion
- without recalling it. The provided diversion name must exist.
-
- **'playAllDiversions()'** -- Play (and purge) all existing
- diversions in the sorted order of their names. This call does
- an implicit 'empy.stopDiverting' before executing.
-
- **'replayAllDiversions()'** -- Replay (without purging) all
- existing diversions in the sorted order of their names. This
- call does an implicit 'empy.stopDiverting' before executing.
-
- **'purgeAllDiversions()'** -- Purge all existing diversions
- without recalling them. This call does an implicit
- 'empy.stopDiverting' before executing.
-
- **'getCurrentDiversion() -> diversion'** -- Return the name of the
- current diversion.
-
- **'getAllDiversions() -> sequence'** -- Return a sorted list of
- all existing diversions.
-
- Filters:
-
- **'getFilter() -> filter'** -- Retrieve the current filter.
- 'None' indicates no filter is installed.
-
- **'resetFilter()'** -- Reset the filter so that no filtering is
- done.
-
- **'nullFilter()'** -- Install a special null filter, one which
- consumes all text and never sends any text to the output.
-
- **'setFilter(shortcut)'** -- Install a new filter. A filter is
- 'None' or an empty sequence representing no filter, or '0' for a
- null filter, a function for a function filter, a string for a
- string filter, or an instance of 'empy.Filter' (or a workalike
- object). If filter is a list of the above things, they will be
- chained together manually; if it is only one, it will be
- presumed to be solitary or to have already been manually chained
- together. See the "Filters" section for more information.
-
- **'attachFilter(shortcut)'** -- Attach a single filter (sequences
- are not allowed here) to the end of a currently existing filter
- chain, or if there is no current chain, install it as
- 'empy.setFilter' would. As with 'empy.setFilter', the shortcut
- versions of filters are also allowed here.
-
- Hooks:
-
- **'areHooksEnabled()'** -- Return whether or not hooks are
- presently enabled.
-
- **'enableHooks()'** -- Enable invocation of hooks. By default
- hooks are enabled.
-
- **'disableHooks()'** -- Disable invocation of hooks. Hooks can
- still be added, removed, and queried, but invocation of hooks
- will not occur (even explicit invocation with
- 'empy.invokeHook').
-
- **'getHooks()'** -- Get a (copy of the) list of the hooks
- currently registered.
-
- **'clearHooks()'** -- Clear all the hooks registered with this
- interpreter.
-
- **'addHook(hook, prepend_opt)'** -- Add this hook to the hooks
- associated with this interpreter. By default, the hook is
- appended to the end of the existing hooks, if any; if the
- optional insert argument is present and true, it will be
- prepended to the list instead.
-
- **'removeHook(hook)'** -- Remove this hook from the hooks
- associated with this interpreter.
-
- **'invokeHook(_name, ...)'** -- Manually invoke a hook method.
- The remaining arguments are treated as keyword arguments and the
- resulting dictionary is passed in as the second argument to the
- hooks.
-
- Custom markup callback:
-
- **'getCallback() -> callback'** -- Retrieve the current callback
- associated with this interpreter, or 'None' if it does not yet
- have one.
-
- **'registerCallback(callback)'** -- Register a callback to be
- called whenever a custom markup ('@<...>') is encountered. When
- encountered, 'invokeCallback' is called.
-
- **'deregisterCallback()'** -- Clear any callback previously
- registered with the interpreter for being called when a custom
- markup is encountered.
-
- **'invokeCallback(contents)'** -- Invoke a custom callback. This
- function is called whenever a custom markup ('@<...>') is
- encountered. It in turn calls the registered callback, with a
- single argument, 'contents', which is a string representing of
- the contents of the custom markup.
-
-
-Invocation
-
- Basic invocation involves running the interpreter on an EmPy file
- and some optional arguments. If no file are specified, or the
- file is named '-', EmPy takes its input from stdin. One can
- suppress option evaluation (to, say, specify a file that begins
- with a dash) by using the canonical '--' option.
-
- **'-h'/'--help'** -- Print usage and exit.
-
- **'-H'/'--extended-help'** -- Print extended usage and exit.
- Extended usage includes a rundown of all the legal expansions,
- escape sequences, pseudomodule contents, used hooks, and
- supported environment variables.
-
- **'-v'/'--verbose'** -- The EmPy system will print all manner of
- details about what it is doing and what it is processing to
- stderr.
-
- **'-V'/'--version'** -- Print version and exit.
-
- **'-a'/'--append' (filename)** -- Open the specified file for
- append instead of using stdout.
-
- **'-b'/'--buffered-output'** -- Fully buffer processing output,
- including the file open itself. This is helpful when, should an
- error occur, you wish that no output file be generated at all
- (for instance, when using EmPy in conjunction with make). When
- specified, either the -o or -a options must be specified, and
- the -b option must precede them. This can also be specified
- through the existence of the 'EMPY_BUFFERED_OUTPUT' environment
- variable.
-
- **'-f'/'--flatten'** -- Before processing, move the contents of
- the 'empy' pseudomodule into the globals, just as if
- 'empy.flatten()' were executed immediately after starting the
- interpreter. That is, *e.g.*, 'empy.include' can be referred to
- simply as 'include' when this flag is specified on the command
- line. This can also be specified through the existence of the
- 'EMPY_FLATTEN' environment variable.
-
- **'-i'/'--interactive'** -- After the main EmPy file has been
- processed, the state of the interpreter is left intact and
- further processing is done from stdin. This is analogous to the
- Python interpreter's -i option, which allows interactive
- inspection of the state of the system after a main module is
- executed. This behaves as expected when the main file is stdin
- itself. This can also be specified through the existence of the
- 'EMPY_INTERACTIVE' environment variable.
-
- **'-k'/'--suppress-errors'** -- Normally when an error is
- encountered, information about its location is printed and the
- EmPy interpreter exits. With this option, when an error is
- encountered (except for keyboard interrupts), processing stops
- and the interpreter enters interactive mode, so the state of
- affairs can be assessed. This is also helpful, for instance,
- when experimenting with EmPy in an interactive manner. -k
- implies -i.
-
- **'-n'/'--no-override-stdout'** -- Do not override 'sys.stdout'
- with a proxy object which the EmPy system interacts with. If
- suppressed, this means that side effect printing will not be
- captured and routed through the EmPy system. However, if this
- option is specified, EmPy can support multithreading.
-
- **'-o'/'--output' (filename)** -- Open the specified file for
- output instead of using stdout. If a file with that name
- already exists it is overwritten.
-
- **'-p'/'--prefix' (prefix)** -- Change the prefix used to detect
- expansions. The argument is the one-character string that will
- be used as the prefix. Note that whatever it is changed to, the
- way to represent the prefix literally is to double it, so if '$'
- is the prefix, a literal dollar sign is represented with '$$'.
- Note that if the prefix is changed to one of the secondary
- characters (those that immediately follow the prefix to indicate
- the type of action EmPy should take), it will not be possible to
- represent literal prefix characters by doubling them (*e.g.*, if
- the prefix were inadvisedly changed to '#' then '##' would
- already have to represent a comment, so '##' could not represent
- a literal '#'). This can also be specified through the
- 'EMPY_PREFIX' environment variable.
-
- **'-r'/'--raw-errors'** -- Normally, EmPy catches Python
- exceptions and prints them alongside an error notation
- indicating the EmPy context in which it occurred. This option
- causes EmPy to display the full Python traceback; this is
- sometimes helpful for debugging. This can also be specified
- through the existence of the 'EMPY_RAW_ERRORS' environment
- variable.
-
- **'-u'/'--unicode'** -- Enable the Unicode subsystem. This option
- only need be present if you wish to enable the Unicode subsystem
- with the defaults; any other Unicode-related option (starting
- with --unicode...) will also enable the Unicode subsystem.
-
- **'-D'/'--define' (assignment)** -- Execute a Python assignment of
- the form 'variable = expression'. If only a variable name is
- provided (*i.e.*, the statement does not contain an '=' sign),
- then it is taken as being assigned to None. The -D option is
- simply a specialized -E option that special cases the lack of an
- assignment operator. Multiple -D options can be specified.
-
- **'-E'/'--execute' (statement)** -- Execute the Python (not EmPy)
- statement before processing any files. Multiple -E options can
- be specified.
-
- **'-F'/'--execute-file' (filename)** -- Execute the Python (not
- EmPy) file before processing any files. This is equivalent to
- '-E execfile("filename")' but provides a more readable context.
- Multiple -F options can be specified.
-
- **'-I'/'--import' (module)** -- Imports the specified module name
- before processing any files. Multiple modules can be specified
- by separating them by commas, or by specifying multiple -I
- options.
-
- **'-P'/'--preprocess' (filename)** -- Process the EmPy file before
- processing the primary EmPy file on the command line.
-
- **'--binary'** -- Treat the file as a binary file, and read in
- chunks rather than line by line. In this mode, the "line"
- indicator represents the number of bytes read, not the number of
- lines processed.
-
- **'--no-prefix'** -- Disable the prefixing system entirely; when
- specified, EmPy will not expand any markups. This allows EmPy
- to merely act as a Unicode encoding translator..
-
- **'--pause-at-end'** -- If present, then 'raw_input' will be
- called at the end of processing. Useful in systems where the
- output window would otherwise be closed by the operating
- system/window manager immediately after EmPy exited.
-
- **'--relative-path'** -- When present, the path the EmPy script
- being invoked is contained in will be prepended to 'sys.path'.
- This is analogous to Python's internal handling of 'sys.path'
- and scripts. If input is from stdin ('-' for a filename or no
- filename is specified), then nothing is added to the path.
-
- **'--no-callback-error'** -- Do not consider it an error if the
- custom markup is invoked '@<...>' and there is no callback
- function registered for it.
-
- **'--chunk-size' (chunk)** -- Use the specific binary chunk size
- rather than the default; implies --binary.
-
- **'--unicode-encoding' (encoding)** -- Specify the Unicode
- encoding to be used for both input and output.
-
- **'--unicode-input-encoding' (encoding)** -- Specify the Unicode
- encoding to be used for input.
-
- **'--unicode-output-encoding' (encoding)** -- Specify the Unicode
- encoding to be used for output.
-
- **'--unicode-input-errors (errors)** -- Specify the Unicode error
- handling to be used for input.
-
- **'--unicode-errors (errors)** -- Specify the Unicode error
- handling to be used for both input and output.
-
- **'--unicode-output-errors (errors)** -- Specify the Unicode error
- handling to be used for output.
-
-
-Environment variables
-
- EmPy also supports a few environment variables to predefine
- certain behaviors. The settings chosen by environment variables
- can be overridden via command line arguments. The following
- environment variables have meaning to EmPy:
-
- **'EMPY_OPTIONS'** -- If present, the contents of this environment
- variable will be treated as options, just as if they were
- entered on the command line, *before* the actual command line
- arguments are processed. Note that these arguments are *not*
- processed by the shell, so quoting, filename globbing, and the
- like, will not work.
-
- **'EMPY_PREFIX'** -- If present, the value of this environment
- variable represents the prefix that will be used; this is
- equivalent to the -p command line option.
-
- **'EMPY_PSEUDO'** -- If present, the value of this environment
- variable represents the name of the pseudomodule that will be
- incorporated into every running EmPy system; this is equivalent
- to the -m command line option.
-
- **'EMPY_FLATTEN'** -- If defined, this is equivalent to including
- -f on the command line.
-
- **'EMPY_RAW_ERRORS'** -- If defined, this is equivalent to
- including -r on the command line.
-
- **'EMPY_INTERACTIVE'** -- If defined, this is equivalent to
- including -i on the command line.
-
- **'EMPY_BUFFERED_OUTPUT'** -- If defined, this is equivalent to
- including -b on the command line.
-
- **'EMPY_UNICODE'** -- If defined, this is equivalent to including
- -u on the command line.
-
- **'EMPY_UNICODE_INPUT_ENCODING'** -- If present, the value of this
- environment variable indicates the name of the Unicode input
- encoding to be used. This is equivalent to the
- --unicode-input-encoding command line option.
-
- **'EMPY_UNICODE_OUTPUT_ENCODING'** -- If present, the value of
- this environment variable indicates the name of the Unicode
- output encoding to be used. This is equivalent to the
- --unicode-output-encoding command line option.
-
- **'EMPY_UNICODE_INPUT_ERRORS'** -- If present, the value of this
- environment variable indicates the name of the error handler to
- be used for input. This is equivalent to the
- --unicode-input-errors command line option.
-
- **'EMPY_UNICODE_OUTPUT_ERRORS'** -- If present, the value of this
- environment variable indicates the name of the error handler to
- be used for output. This is equivalent to the
- --unicode-output-errors command line option.
-
-
-Examples and testing EmPy
-
- See the sample EmPy file 'sample.em' which is included with the
- distribution. Run EmPy on it by typing something like::
-
- ./em.py sample.em
-
- and compare the results and the sample source file side by side.
- The sample content is intended to be self-documenting, and even an
- introduction to the basic features of EmPy while simultaneously
- exercising them.
-
- The file 'sample.bench' is the benchmark output of the sample.
- Running the EmPy interpreter on the provided 'sample.em' file
- should produce precisely the same results. You can run the
- provided test script to see if your EmPy environment is behaving
- as expected (presuming a Unix-like operating system)::
-
- ./test.sh
-
- By default this will test with the first Python interpreter
- available in the path; if you want to test with another
- interpreter, you can provide it as the first argument on the
- command line, *e.g.*::
-
- ./test.sh python2.1
- ./test.sh /usr/bin/python1.5
- ./test.sh jython
-
- A more comprehensive test suite and set of real-world examples is
- planned for a future version.
-
-
-Embedding EmPy
-
- For atomic applications, the 'expand' function is provided (the
- extra keyword arguments passed in are treated as locals)::
-
- import em
- print em.expand("@x + @y is @(x + y).", x=2, y=3)
-
- One can specify a globals dictionary and all the other interpreter
- options (below) as well. One can specify a globals dictionary
- that will be used if one wants persistence::
-
- import em
- g = {}
- em.expand("@{x = 10}", g)
- print em.expand("x is @x.", g)
-
- The standalone 'expand' function, however, creates and destroys an
- 'Interpreter' instance each time it is called. For repeated
- expansions, this can be expensive. Instead, you will probably
- want to use the full-fledged features of embedding. An EmPy
- interpreter can be created with as code as simple as::
-
- import em
- interpreter = em.Interpreter()
- # The following prints the results to stdout:
- interpreter.string("@{x = 123}@x\n")
- # This expands to the same thing, but puts the results as a
- # string in the variable result:
- result = interpreter.expand("@{x = 123}@x\n")
- # This just prints the value of x directly:
- print interpreter.globals['x']
- # Process an actual file (and output to stdout):
- interpreter.file(open('/path/to/some/file'))
- interpreter.shutdown() # this is important; see below
-
- One can capture the output of a run in something other than stdout
- by specifying the *output* parameter::
-
- import em, StringIO
- output = StringIO.StringIO()
- interpreter = em.Interpreter(output=output)
- # Do something.
- interpreter.file(open('/path/to/some/file'))
- interpreter.shutdown() # again, this is important; see below
- print output.getvalue() # this is the result from the session
-
- When you are finished with your interpreter, it is important to
- call its shutdown method::
-
- interpreter.shutdown()
-
- This will ensure that the interpreter cleans up all its overhead,
- entries in the 'sys.stdout' proxy, and so forth. It is usually
- advisable that this be used in a try...finally clause::
-
- interpreter = em.Interpreter(...)
- try:
- ...
- finally:
- interpreter.shutdown()
-
- The 'em.Interpreter' constructor takes the following arguments;
- all are optional. Since options may be added in the future, it is
- highly recommended that the constructor be invoked via keyword
- arguments, rather than assuming their order. The arguments are:
-
- *output* -- The output file which the interpreter will be sending
- all its processed data to. This need only be a file-like object;
- it need not be an actual file. If omitted, 'sys.__stdout__' is
- used.
-
- *argv* -- An argument list analogous to 'sys.argv', consisting of
- the script name and zero or more arguments. These are available
- to executing interpreters via 'empy.argv' and 'empy.args'. If
- omitted, a non-descript script name is used with no arguments.
-
- *prefix* -- The prefix (a single-character string). Defaults to
- '@'. It is an error for this to be anything other than one
- character.
-
- *pseudo* -- The name (string) of the pseudmodule. Defaults to
- 'empy'.
-
- *options* -- A dictionary of options that can override the default
- behavior of the interpreter. The names of the options are
- constant names ending in '_OPT' and their defaults are given in
- 'Interpreter.DEFAULT_OPTIONS'.
-
- *globals* -- By default, interpreters begin with a pristine
- dictionary of globals (except, of course, for the 'empy'
- pseudomodule). Specifying this argument will allow the globals
- to start with more.
-
- *hooks* -- A sequence of hooks (or 'None' for none) to register
- with the interpreter at startup. Hooks can, of course, be added
- after the fact, but this allows the hooks to intercept the
- 'atStartup' event (otherwise, the startup event would already
- have occurred by the time new hooks could be registered)..
-
- Many things can be done with EmPy interpreters; for the full
- developer documentation, see the generated documentation for the
- 'em' module.
-
-
-Interpreter options
-
- The following options (passed in as part of the options dictionary
- to the Interpreter constructor) have the following meanings. The
- defaults are shown below and are also indicated in an
- 'Interpreter.DEFAULT_OPTIONS' dictionary.
-
- **'BANGPATH_OPT'** -- Should a bangpath ('#!') as the first line
- of an EmPy file be treated as if it were an EmPy comment? Note
- that '#!' sequences starting lines or appearing anywhere else in
- the file are untouched regardless of the value of this option.
- Default: true.
-
- **'BUFFERED_OPT'** -- Should an 'abort' method be called upon
- failure? This relates to the fully-buffered option, where all
- output can be buffered including the file open; this option only
- relates to the interpreter's behavior *after* that proxy file
- object has been created. Default: false.
-
- **'RAW_OPT'** -- Should errors be displayed as raw Python errors
- (that is, the exception is allowed to propagate through to the
- toplevel so that the user gets a standard Python traceback)?
- Default: false.
-
- **'EXIT_OPT'** -- Upon an error, should execution continue
- (although the interpreter stacks will be purged)? Note that
- even in the event this is set, the interpreter will halt upon
- receiving a 'KeyboardInterrupt'. Default: true.
-
- **'FLATTEN_OPT'** -- Upon initial startup, should the 'empy'
- pseudomodule namespace be flattened, *i.e.*, should
- 'empy.flatten' be called? Note this option only has an effect
- when the interpreter is first created; thereafter it is
- ignored. Default: false.
-
- **'OVERRIDE_OPT'** -- Should the 'sys.stdout' object be overridden
- with a proxy object? If not, side effect output cannot be
- captured by the EmPy system, but EmPy will support
- multithreading. Default: true.
-
- **'CALLBACK_OPT'** -- If a callback is invoked when none has yet
- been registered, should an error be raised or should the
- situation be ignored? Default: true.
-
-
-Data flow
-
- **input -> interpreter -> diversions -> filters -> output**
-
- Here, in summary, is how data flows through a working EmPy system:
-
- 1. Input comes from a source, such an .em file on the command
- line, or via an 'empy.include' statement.
-
- 2. The interpreter processes this material as it comes in,
- expanding EmPy expansions as it goes.
-
- 3. After interpretation, data is then sent through the diversion
- layer, which may allow it directly through (if no diversion is
- in progress) or defer it temporarily. Diversions that are
- recalled initiate from this point.
-
- 4. Any filters in place are then used to filter the data and
- produce filtered data as output.
-
- 5. Finally, any material surviving this far is sent to the output
- stream. That stream is stdout by default, but can be changed
- with the -o or -a options, or may be fully buffered with the -b
- option (that is, the output file would not even be opened until
- the entire system is finished).
-
-
-Author's notes
-
- I originally conceived EmPy as a replacement for my "Web
- templating system", http://www.alcyone.com/max/info/m4.html which
- uses "m4", http://www.seindal.dk/rene/gnu/ (a general
- macroprocessing system for Unix).
-
- Most of my Web sites include a variety of m4 files, some of which
- are dynamically generated from databases, which are then scanned
- by a cataloging tool to organize them hierarchically (so that,
- say, a particular m4 file can understand where it is in the
- hierarchy, or what the titles of files related to it are without
- duplicating information); the results of the catalog are then
- written in database form as an m4 file (which every other m4 file
- implicitly includes), and then GNU make converts each m4 to an
- HTML file by processing it.
-
- As the Web sites got more complicated, the use of m4 (which I had
- originally enjoyed for the challenge and abstractness) really
- started to become an impediment to serious work; while I am very
- knowledgeable about m4 -- having used it for for so many years --
- getting even simple things done with it is awkward and difficult.
- Worse yet, as I started to use Python more and more over the
- years, the cataloging programs which scanned the m4 and built m4
- databases were migrated to Python and made almost trivial, but
- writing out huge awkward tables of m4 definitions simply to make
- them accessible in other m4 scripts started to become almost
- farcical -- especially when coupled with the difficulty in getting
- simple things done in m4.
-
- It occurred to me what I really wanted was an all-Python solution.
- But replacing what used to be the m4 files with standalone Python
- programs would result in somewhat awkward programs normally
- consisting mostly of unprocessed text punctuated by small portions
- where variables and small amounts of code need to be substituted.
- Thus the idea was a sort of inverse of a Python interpreter: a
- program that normally would just pass text through unmolested, but
- when it found a special signifier would execute Python code in a
- normal environment. I looked at existing Python templating
- systems, and didn't find anything that appealed to me -- I wanted
- something where the desired markups were simple and unobtrusive.
- After considering between choices of signifiers, I settled on '@'
- and EmPy was born.
-
- As I developed the tool, I realized it could have general appeal,
- even to those with widely varying problems to solve, provided the
- core tool they needed was an interpreter that could embed Python
- code inside templated text. As I continue to use the tool, I have
- been adding features as unintrusively as possible as I see areas
- that can be improved.
-
- A design goal of EmPy is that its feature set should work on
- several levels; at each level, if the user does not wish or need
- to use features from another level, they are under no obligation
- to do so. If you have no need of diversions, for instance, you
- are under no obligation to use them. If significators will not
- help you organize a set of EmPy scripts globally, then you need
- not use them. New features that are being added are whenever
- possible transparently backward compatible; if you do not need
- them, their introduction should not affect you in any way. The
- use of unknown prefix sequences results in errors, guaranteeing
- that they are reserved for future use.
-
-
-Glossary
-
- **control** -- A control markup, used to direct high-level control
- flow within an EmPy session. Control markups are expressed with
- the '@[...]' notation.
-
- **diversion** -- A process by which output is deferred, and can be
- recalled later on demand, multiple times if necessary.
-
- **document** -- The abstraction of an EmPy document as used by a
- processor.
-
- **escape** -- A markup designed to expand to a single (usually
- non-printable) character, similar to escape sequences in C or
- other languages.
-
- **expansion** -- The process of processing EmPy markups and
- producing output.
-
- **expression** -- An expression markup represents a Python
- expression to be evaluated, and replaced with the 'str' of its
- value. Expression markups are expressed with the '@(...)'
- notation.
-
- **filter** -- A file-like object which can be chained to other
- objects (primarily the final stream) and can buffer, alter, or
- manipulate in any way the data sent. Filters can also be
- chained together in arbitrary order.
-
- **globals** -- The dictionary (or dictionary-like object) which
- resides inside the interpreter and holds the currently-defined
- variables.
-
- **hook** -- A callable object that can be registered in a
- dictionary, and which will be invoked before, during, or after
- certain internal operations, identified by name with a string.
-
- **interpreter** -- The application (or class instance) which
- processes EmPy markup.
-
- **markup** -- EmPy substitutions set off with a prefix and
- appropriate delimeters.
-
- **output** -- The final destination of the result of processing an
- EmPy file.
-
- **prefix** -- The ASCII character used to set off an expansions.
- By default, '@'.
-
- **processor** -- An extensible system which processes a group of
- EmPy files, usually arranged in a filesystem, and scans them for
- significators.
-
- **pseudomodule** -- The module-like object named 'empy' which is
- exposed internally inside every EmPy system.
-
- **shortcut** -- A special object which takes the place of an
- instance of the 'Filter' class, to represent a special form of
- filter. These include 0 for a null filter, a callable (function
- or lambda) to represent a callable filter, or a 256-character
- string which represents a translation filter.
-
- **significator** -- A special form of an assignment markup in EmPy
- which can be easily parsed externally, primarily designed for
- representing uniform assignment across a collection of files.
- Significators are indicated with the '@%' markup.
-
- **statement** -- A line of code that needs to be executed;
- statements do not have return values. In EmPy, statements are
- set off with '@{...}'.
-
-
-Acknowledgements
-
- Questions, suggestions, bug reports, evangelism, and even
- complaints from many people have helped make EmPy what it is
- today. Some, but by no means all, of these people are (in
- alphabetical order by surname):
-
- - Biswapesh Chattopadhyay
-
- - Beni Cherniavsky
-
- - Dr. S. Candelaria de Ram
-
- - Eric Eide
-
- - Dinu Gherman
-
- - Grzegorz Adam Hankiewicz
-
- - Bohdan Kushnir
-
- - Robert Kroeger
-
- - Kouichi Takahashi
-
- - Ville Vainio
-
-
-Known issues and caveats
-
- - EmPy was primarily intended for static processing of documents,
- rather than dynamic use, and hence speed of processing was not
- the primary consideration in its design.
-
- - EmPy is not threadsafe by default. This is because of the need
- for EmPy to override the 'sys.stdout' file with a proxy object
- which can capture effects of 'print' and other spooling to
- stdout. This proxy can be suppressed with the -n option, which
- will result in EmPy being unable to do anything meaningful with
- this output, but will allow EmPy to be threadsafe.
-
- - To function properly, EmPy must override 'sys.stdout' with a
- proxy file object, so that it can capture output of side effects
- and support diversions for each interpreter instance. It is
- important that code executed in an environment *not* rebind
- 'sys.stdout', although it is perfectly legal to invoke it
- explicitly (*e.g.*, '@sys.stdout.write("Hello world\n")'). If
- one really needs to access the "true" stdout, then use
- 'sys.__stdout__' instead (which should also not be rebound).
- EmPy uses the standard Python error handlers when exceptions are
- raised in EmPy code, which print to 'sys.stderr'.
-
- - Due to Python's curious handling of the 'print' statement --
- particularly the form with a trailing comma to suppress the
- final newline -- mixing statement expansions using prints inline
- with unexpanded text will often result in surprising behavior,
- such as extraneous (sometimes even deferred!) spaces. This is a
- Python "feature," and occurs in non-EmPy applications as well;
- for finer control over output formatting, use 'sys.stdout.write'
- or 'empy.interpreter.write' directly.
-
- - The 'empy' "module" exposed through the EmPy interface (*e.g.*,
- '@empy') is an artificial module. It cannot be imported with
- the 'import' statement (and shouldn't -- it is an artifact of
- the EmPy processing system and does not correspond to any
- accessible .py file).
-
- - For an EmPy statement expansion all alone on a line, *e.g.*,
- '@{a = 1}', note that this will expand to a blank line due to
- the newline following the closing curly brace. To suppress this
- blank line, use the symmetric convention '@{a = 1}@'.
-
- - When using EmPy with make, note that partial output may be
- created before an error occurs; this is a standard caveat when
- using make. To avoid this, write to a temporary file and move
- when complete, delete the file in case of an error, use the -b
- option to fully buffer output (including the open), or (with GNU
- make) define a '.DELETE_ON_ERROR' target.
-
- - 'empy.identify' tracks the context of executed *EmPy* code, not
- Python code. This means that blocks of code delimited with '@{'
- and '}' will identify themselves as appearing on the line at
- which the '}' appears, and that pure Python code executed via
- the -D, -E and -F command line arguments will show up as all taking
- place on line 1. If you're tracking errors and want more
- information about the location of the errors from the Python
- code, use the -r command line option, which will provide you
- with the full Python traceback.
-
- - The conditional form of expression expansion '@(...?...!...)'
- allows the use of a colon instead of an exclamation point,
- *e.g.*, '@(...?...:...)'. This behavior is supported for
- backward compatibility, but is deprecated. Due to an oversight,
- the colon was a poor choice since colons can appear legally in
- expressions (*e.g.*, dictionary literals or lambda expressions).
-
- - The '@[try]' construct only works with Python exceptions derived
- from 'Exception'. It is not able to catch string exceptions.
-
- - The '@[for]' variable specification supports tuples for tuple
- unpacking, even recursive tuples. However, it is limited in
- that the names included may only be valid Python identifiers,
- not arbitrary Python lvalues. Since the internal Python
- mechanism is very rarely used for this purpose (*e.g.*, 'for (x,
- l[0], q.a) in sequence'), it is not thought to be a significant
- limitation.
-
-
-Wish list
-
- Here are some random ideas for future revisions of EmPy. If any
- of these are of particular interest to you, your input would be
- appreciated.
-
- - Some real-world examples should really be included for
- demonstrating the power and expressiveness of EmPy first-hand.
-
- - More extensive help (rather than a ridiculously long README),
- probably inherently using the EmPy system itself for building to
- HTML and other formats, thereby acting as a help facility and a
- demonstration of the working system.
-
- - A "trivial" mode, where all the EmPy system does is scan for
- simple symbols to replace them with evaluations/executions,
- rather than having to do the contextual scanning it does now.
- This has the down side of being much less configurable and
- powerful but the upside of being extremely efficient.
-
- - A "debug" mode, where EmPy prints the contents of everything
- it's about to evaluate (probably to stderr) before it does?
-
- - The ability to funnel all code through a configurable 'RExec'
- for user-controlled security control. This would probably
- involve abstracting the execution functionality outside of the
- interpreter. [This suggestion is on hold until the
- rexec/Bastion exploits are worked out.]
-
- - Optimized handling of processing would be nice for the
- possibility of an Apache module devoted to EmPy processing.
-
- - An EmPy emacs mode.
-
- - An optimization of offloading diversions to files when they
- become truly huge. (This is made possible by the abstraction of
- the 'Diversion' class.)
-
- - Support for mapping filters (specified by dictionaries).
-
- - Support for some sort of batch processing, where several EmPy
- files can be listed at once and all of them evaluated with the
- same initial (presumably expensive) environment.
- 'empy.saveGlobals' and 'empy.restoreGlobals' have been
- introduced as a partial solution, but they need to be made more
- robust.
-
- - A more elaborate interactive mode, perhaps with a prompt and
- readline support.
-
- - A StructuredText and/or reStructuredText filter would be quite
- useful, as would SGML/HTML/XML/XHTML, s-expression, Python,
- etc. auto-indenter filters.
-
- - An indexing filter, which can process text and pick out
- predefined keywords and thereby setup links to them.
-
- - The ability to rerun diverted material back through the
- interpreter. (This can be done, awkwardly, by manually creating
- a filter which itself contains an interpreter, but it might be
- helpful if this was an all-in-one operation.)
-
- - A caching system that stores off the compilations of repeated
- evaluations and executions so that in a persistent environment
- the same code does not have to be repeatedly evaluated/executed.
- This would probably be a necessity in an Apache module-based
- solution. Perhaps caching even to the point of generating pure
- PyWM bytecode?
-
- - An option to change the format of the standard EmPy errors in a
- traceback.
-
- - Support for some manner of implicitly processed /etc/empyrc
- and/or ~/.empyrc file, and of course an option to inhibit its
- processing. This can already be accomplished (and with greater
- control) via use of EMPY_OPTIONS, though.
-
- - More uniform handling of the preprocessing directives (-I, -D,
- -E, -F, and -P), probably mapping directly to methods in the
- 'Interpreter' class.
-
- - Support for integration with mod_python.
-
- - In simple expressions, a '{...}' suffix has no meaning in Python
- (*e.g.*, in Python, '@x(...)' is a call, '@x[...]' is
- subscription, but '@x{...}' is illegal). This could be
- exploited by having a '{...}' suffix in a simple expression
- representing an encapsulation of an expanded string; *e.g.*,
- '@bullet{There are @count people here}' would be equivalent to
- '@bullet(empy.expand("There are @count people here",
- locals()))}'.
-
- - A tool to collect significator information from a hierarchy of
- .em files and put them in a database form available for
- individual scripts would be extremely useful -- this tool should
- be extensible so that users can use it to, say, build ordered
- hierarchies of their EmPy files by detecting contextual
- information like application-specific links to other EmPy
- documents.
-
- - Extensions of the basic EmPy concepts to projects for other
- interpreted languages, such as Java, Lua, Ruby, and/or Perl.
-
- - Ignore 'SystemExit' when doing error handling, letting the
- exception progagate up? So far no one seems to worry about
- this; deliberately exiting early in a template seems to be an
- unlikely occurrence. (Furthermore, there are the 'os.abort' and
- 'os._exit' facilities for terminating without exception
- propagation.)
-
- - A new markup which is the equivalent of '$...:...$' in source
- control systems, where the left-hand portion represents a
- keyword and the right-hand portion represents its value which is
- substituted in by the EmPy system.
-
- - The ability to obtain the filename (if relevant) and mode of the
- primary output file.
-
- - The ability to redirect multiple streams of output; not
- diversions, but rather the ability to write to one file and then
- another. Since output would be under the EmPy script's control,
- this would imply a useful --no-output option, where by default
- no output is written. This would also suggest the usefulness of
- all the output file delegates (diversions, filters, abstract
- files, etc.) passing unrecognized method calls all the way down
- to underlying file object.
-
- - In addition to the em.py script, an additional support library
- (non-executable) should be included which includes ancillary
- functionality for more advanced features, but which is not
- necessary to use EmPy in its basic form as a standalone
- executable. Such features would include things like
- significator processing, metadata scanning, and advanced
- prompting systems.
-
-
-Release history
-
- - 3.3.2; 2014 Jan 24. Additional fix for source compatibility
- between 2.x and 3.0.
-
- - 3.3.1; 2014 Jan 22. Source compatibility for 2.x and 3.0;
- 1.x and Jython compatibility dropped.
-
- - 3.3; 2003 Oct 27. Custom markup '@<...>'; remove separate
- pseudomodule instance for greater transparency; deprecate
- 'interpreter' attribute of pseudomodule; deprecate auxiliary
- class name attributes associated with pseudomodule in
- preparation for separate support library in 4.0; add
- --no-callback-error and --no-bangpath-processing command line
- options; add 'atToken' hook.
-
- - 3.2; 2003 Oct 7. Reengineer hooks support to use hook
- instances; add -v option; add --relative-path option; reversed
- PEP 317 style; modify Unicode support to give less confusing
- errors in the case of unknown encodings and error handlers;
- relicensed under LGPL.
-
- - 3.1.1; 2003 Sep 20. Add literal '@"..."' markup; add
- --pause-at-end command line option; fix improper globals
- collision error via the 'sys.stdout' proxy.
-
- - 3.1; 2003 Aug 8. Unicode support (Python 2.0 and above); add
- Document and Processor helper classes for processing
- significators; add --no-prefix option for suppressing all
- markups.
-
- - 3.0.4; 2003 Aug 7. Implement somewhat more robust lvalue
- parsing for '@[for]' construct (thanks to Beni Cherniavsky for
- inspiration).
-
- - 3.0.3; 2003 Jul 9. Fix bug regarding recursive tuple unpacking
- using '@[for]'; add 'empy.saveGlobals', 'empy.restoreGlobals',
- and 'empy.defined' functions.
-
- - 3.0.2; 2003 Jun 19. '@?' and '@!' markups for changing the
- current context name and line, respectively; add 'update' method
- to interpreter; new and renamed context operations,
- 'empy.setContextName', 'empy.setContextLine',
- 'empy.pushContext', 'empy.popContext'.
-
- - 3.0.1; 2003 Jun 9. Fix simple bug preventing command line
- preprocessing directives (-I, -D, -E, -F, -P) from executing
- properly; defensive PEP 317 compliance [defunct].
-
- - 3.0; 2003 Jun 1. Control markups with '@[...]'; remove
- substitutions (use control markups instead); support
- '@(...?...!...)' for conditional expressions in addition to the
- now-deprecated '@(...?...:...)' variety; add acknowledgements
- and glossary sections to documentation; rename buffering option
- back to -b; add -m option and 'EMPY_PSEUDO' environment variable
- for changing the pseudomodule name; add -n option and
- 'EMPY_NO_OVERRIDE' environment variable for suppressing
- 'sys.stdout' proxy; rename main error class to 'Error'; add
- standalone 'expand' function; add --binary and --chunk-size
- options; reengineer parsing system to use Tokens for easy
- extensibility; safeguard curly braces in simple expressions
- (meaningless in Python and thus likely a typographical error) by
- making them a parse error; fix bug involving custom Interpreter
- instances ignoring globals argument; distutils support.
-
- - 2.3; 2003 Feb 20. Proper and full support for concurrent and
- recursive interpreters; protection from closing the true stdout
- file object; detect edge cases of interpreter globals or
- 'sys.stdout' proxy collisions; add globals manipulation
- functions 'empy.getGlobals', 'empy.setGlobals', and
- 'empy.updateGlobals' which properly preserve the 'empy'
- pseudomodule; separate usage info out into easily accessible
- lists for easier presentation; have -h option show simple usage
- and -H show extened usage; add 'NullFile' utility class.
-
- - 2.2.6; 2003 Jan 30. Fix a bug in the 'Filter.detach' method
- (which would not normally be called anyway).
-
- - 2.2.5; 2003 Jan 9. Strip carriage returns out of executed code
- blocks for DOS/Windows compatibility.
-
- - 2.2.4; 2002 Dec 23. Abstract Filter interface to use methods
- only; add '@[noop: ...]' substitution for completeness and block
- commenting [defunct].
-
- - 2.2.3; 2002 Dec 16. Support compatibility with Jython by
- working around a minor difference between CPython and Jython in
- string splitting.
-
- - 2.2.2; 2002 Dec 14. Include better docstrings for pseudomodule
- functions; segue to a dictionary-based options system for
- interpreters; add 'empy.clearAllHooks' and 'empy.clearGlobals';
- include a short documentation section on embedding interpreters;
- fix a bug in significator regular expression.
-
- - 2.2.1; 2002 Nov 30. Tweak test script to avoid writing
- unnecessary temporary file; add 'Interpreter.single' method;
- expose 'evaluate', 'execute', 'substitute' [defunct], and
- 'single' methods to the pseudomodule; add (rather obvious)
- 'EMPY_OPTIONS' environment variable support; add
- 'empy.enableHooks' and 'empy.disableHooks'; include optimization
- to transparently disable hooks until they are actually used.
-
- - 2.2; 2002 Nov 21. Switched to -V option for version
- information; 'empy.createDiversion' for creating initially empty
- diversion; direct access to diversion objects with
- 'empy.retrieveDiversion'; environment variable support; removed
- --raw long argument (use --raw-errors instead); added quaternary
- escape code (well, why not).
-
- - 2.1; 2002 Oct 18. 'empy.atExit' registry separate from hooks to
- allow for normal interpreter support; include a benchmark sample
- and test.sh verification script; expose 'empy.string' directly;
- -D option for explicit defines on command line; remove
- ill-conceived support for '@else:' separator in '@[if ...]'
- substitution [defunct] ; handle nested substitutions properly
- [defunct] ; '@[macro ...]' substitution for creating recallable
- expansions [defunct].
-
- - 2.0.1; 2002 Oct 8. Fix missing usage information; fix
- after_evaluate hook not getting called; add 'empy.atExit' call
- to register values.
-
- - 2.0; 2002 Sep 30. Parsing system completely revamped and
- simplified, eliminating a whole class of context-related bugs;
- builtin support for buffered filters; support for registering
- hooks; support for command line arguments; interactive mode with
- -i; significator value extended to be any valid Python
- expression.
-
- - 1.5.1; 2002 Sep 24. Allow '@]' to represent unbalanced close
- brackets in '@[...]' markups [defunct].
-
- - 1.5; 2002 Sep 18. Escape codes ('@\...'); conditional and
- repeated expansion substitutions [defunct] ; replaced with control
- markups]; fix a few bugs involving files which do not end in
- newlines.
-
- - 1.4; 2002 Sep 7. Fix bug with triple quotes; collapse
- conditional and protected expression syntaxes into the single
- generalized '@(...)' notation; 'empy.setName' and 'empy.setLine'
- functions [deprecated] ; true support for multiple concurrent
- interpreters with improved sys.stdout proxy; proper support for
- 'empy.expand' to return a string evaluated in a subinterpreter
- as intended; merged Context and Parser classes together, and
- separated out Scanner functionality.
-
- - 1.3; 2002 Aug 24. Pseudomodule as true instance; move toward
- more verbose (and clear) pseudomodule functions; fleshed out
- diversion model; filters; conditional expressions; protected
- expressions; preprocessing with -P (in preparation for
- possible support for command line arguments).
-
- - 1.2; 2002 Aug 16. Treat bangpaths as comments; 'empy.quote' for
- the opposite process of 'empy.expand'; significators ('@%...'
- sequences); -I option; -f option; much improved documentation.
-
- - 1.1.5; 2002 Aug 15. Add a separate 'invoke' function that can be
- called multiple times with arguments to simulate multiple runs.
-
- - 1.1.4; 2002 Aug 12. Handle strings thrown as exceptions
- properly; use getopt to process command line arguments; cleanup
- file buffering with AbstractFile; very slight documentation and
- code cleanup.
-
- - 1.1.3; 2002 Aug 9. Support for changing the prefix from within
- the 'empy' pseudomodule.
-
- - 1.1.2; 2002 Aug 5. Renamed buffering option [defunct], added -F
- option for interpreting Python files from the command line,
- fixed improper handling of exceptions from command line options
- (-E, -F).
-
- - 1.1.1; 2002 Aug 4. Typo bugfixes; documentation clarification.
-
- - 1.1; 2002 Aug 4. Added option for fully buffering output
- (including file opens), executing commands through the command
- line; some documentation errors fixed.
-
- - 1.0; 2002 Jul 23. Renamed project to EmPy. Documentation and
- sample tweaks; added 'empy.flatten'. Added -a option.
-
- - 0.3; 2002 Apr 14. Extended "simple expression" syntax,
- interpreter abstraction, proper context handling, better error
- handling, explicit file inclusion, extended samples.
-
- - 0.2; 2002 Apr 13. Bugfixes, support non-expansion of Nones,
- allow choice of alternate prefix.
-
- - 0.1.1; 2002 Apr 12. Bugfixes, support for Python 1.5.x, add -r
- option.
-
- - 0.1; 2002 Apr 12. Initial early access release.
-
-
-Author
-
- This module was written by "Erik Max Francis",
- http://www.alcyone.com/max/. If you use this software, have
- suggestions for future releases, or bug reports, "I'd love to hear
- about it", mailto:software@alcyone.com.
-
- Even if you try out EmPy for a project and find it unsuitable, I'd
- like to know what stumbling blocks you ran into so they can
- potentially be addressed in a future version.
-
-
-Version
-
- Version 3.3.2 $Date: 2014-01-24 13:39:38 -0800 (Fri, 24 Jan 2014) $ $Author: max $
--- /dev/null
+# User's guide
+
+## Introduction: Welcome to EmPy!
+
+[EmPy](http://www.alcyone.com/software/empy/) is a powerful, robust and mature
+templating system for inserting Python code in template text. EmPy
+takes a source document, processes it, and produces output. This is
+accomplished via expansions, which are signals to the EmPy system
+where to act and are indicated with markup. Markup is set off by a
+customizable prefix (by default the at sign, `@`). EmPy can expand
+arbitrary Python expressions, statements and control structures in
+this way, as well as a variety of additional special forms. The
+remaining textual data is sent to the output, allowing Python to be
+used in effect as a markup language.
+
+EmPy also supports hooks, which can intercept and modify the behavior
+of a running interpreter; diversions, which allow recording and
+playback; filters, which are dynamic and can be chained together; and
+a dedicated user-customizable callback markup. The system is highly
+configurable via command line options, configuration files, and
+environment variables. An extensive API is also available for
+embedding EmPy functionality in your own Python programs.
+
+EmPy also has a supplemental library for additional non-essential
+features (`emlib`), a documentation building library used to create
+this documentation (`emdoc`), and an extensive help system (`emhelp`)
+which can be queried from the command line with the main executable
+`em.py` (`-h`/`--help`, `-H`/`--topics=TOPICS`). The base EmPy
+interpreter can function with only the `em.py`/`em` file/module
+available.
+
+EmPy can be used in a variety of roles, including as a templating
+system, a text processing system (preprocessing and/or
+postprocessing), a simple macro processor, a frontend for a content
+management system, annotating documents, for literate programming, as
+a souped-up text encoding converter, a text beautifier (with macros
+and filters), and many other purposes.
+
+
+### Markup overview
+
+Expressions are embedded in text with the `@(...)` notation;
+variations include conditional expressions with `@(...?...!...)` and
+the ability to handle thrown exceptions with `@(...$...)`. As a
+shortcut, simple variables and expressions can be abbreviated as
+`@variable`, `@object.attribute`, `@sequence[index]`,
+`@function(arguments...)`, `@function{markup}{...}` and
+combinations. Full-fledged statements are embedded with `@{...}`.
+Control flow in terms of conditional or repeated expansion is
+available with `@[...]`. A `@` followed by any whitespace character
+(including a newline) expands to nothing, allowing string
+concatenations and line continuations. Line comments are indicated
+with `@#...` including the trailing newline. `@*...*` allows inline
+comments. Escapes are indicated with `@\...`; diacritics with
+`@^...`; icons with `@|...`; and emoji with `@:...:`. `@%...` and
+`@%%...` indicate "significators," which are distinctive forms of
+variable assignment intended to specify per-document identification
+information in a format easy to parse externally, _e.g._, to indicate
+metadata. In-place expressions are specified with `@$...$...$`.
+Context name and line number changes can be made with `@?...` and
+`@!...`, respectively. `@<...>` markup is customizable by the user
+and can be used for any desired purpose. `` @`...` `` allows literal
+escaping of any EmPy markup. And finally, a `@@` sequence (the
+prefix repeated once) expands to a single literal at sign.
+
+The prefix (which defaults to `@`) can be changed
+with `-p`/`--prefix=CHAR` (_environment variable:_ `EMPY_PREFIX`, _configuration variable:_ `prefix`).
+
+
+### Getting the software
+
+The current version of EmPy is 4.0.1.
+
+The official URL for this Web site is <http://www.alcyone.com/software/empy/>.
+
+The latest version of the software is available in a tarball here:
+<http://www.alcyone.com/software/empy/empy-latest.tar.gz>.
+
+The software can be installed through PIP via this shell command:
+
+<pre class="shell"><b><i>% python3 -m pip install empy</i></b>
+<i>...</i></pre>
+
+
+For information about upgrading from 3._x_ to 4.0, see
+<http://www.alcyone.com/software/empy/ANNOUNCE.html#changes>.
+
+
+### Requirements
+
+EmPy works with any modern version of Python. Python version 3._x_ is
+expected to be the default and all source file references to the
+Python interpreter (_e.g._, the bangpath of the .py scripts) use
+`python3`. EmPy also has legacy support for versions of Python going
+back all the way to 2.3, with special emphasis on 2.7 regardless of
+its end-of-life status. It has no dependency requirements on any
+third-party modules and can run directly off of a stock Python
+interpreter.
+
+EmPy will run on any operating system with a full-featured Python
+interpreter; this includes, but is probably not limited to, Linux,
+Windows, and macOS (Darwin). Using EmPy requires knowledge of the
+[Python language](https://www.python.org/).
+
+EmPy is also compatible with several different Python implementations:
+
+| Implementation | Supported versions | Description |
+| --- | --- | --- |
+| CPython | 2.3 to 2.7; 3.0 and up | Standard implementation in C |
+| PyPy | 2.7; 3.2 and up | Implementation with just-in-time compiler |
+| IronPython | 2.7; 3.4 and up | Implementation for .NET CLR and Mono |
+| Jython | 2.7 (and up?) | Implementation for JVM |
+
+It's probable that EmPy is compatible with earlier versions than those
+listed here (potentially going all the way back to 2.3), but this has
+not been tested.
+
+Only a few .py module file(s) are needed to use EmPy; they can be
+installed system-wide through a distribution package, a third-party
+module/executable, or just dropped into any desired directory in the
+`PYTHONPATH`. A minimal installation need only install the em.py
+file, either as an importable module and an executable, or both,
+depending on the user's needs.
+
+EmPy also has optional support for several [third-party
+modules](#third-party-emoji-modules); see [Emoji
+markup](#emoji-markup) for details.
+
+The testing system included (the test.sh script and the tests and
+suites directories) is intended to run on Unix-like systems with a
+Bourne-like shell (_e.g._, sh, bash, zsh, etc.). EmPy is routinely
+tested with all supported versions of all available interpreters.
+
+If you find an incompatibility with your Python interpreter or
+operating system, [let me know](#reporting-bugs).
+
+
+### License
+
+This software is licensed under
+[BSD (3-Clause)](https://opensource.org/licenses/bsd-3-clause/).
+
+
+## Getting started
+
+This section serves as a quick introduction to the EmPy system. For
+more details and a reference, see the sections below.
+
+:::{hint}
+
+As an introduction to the terminology, the following names are used
+throughout:
+
+| Name | Description |
+| --- | --- |
+| `EmPy` | The name of the software |
+| `em.py` | The name of the executable and main source file |
+| `em` | The name of the main module |
+| `empy` | The name of the [pseudomodule](#pseudomodule-and-interpreter), as well as the PyPI package |
+| `.em` | The conventional filename extension for EmPy documents |
+
+:::
+
+
+### Starting EmPy
+
+After installing EmPy (see [Getting the
+software](#getting-the-software)), EmPy is easily invoked by executing
+the EmPy interpreter, `em.py`. If it is invoked without arguments, it
+will accept input from `sys.stdin`. You can use this as an
+interactive session to familiarize yourself with EmPy when starting
+out:
+
+<pre class="shell"><b><i>% em.py</i></b>
+<i>... accepts input from stdin with results written to stdout ...</i></pre>
+
+If an EmPy document is specified (which by convention has the
+extension .em, though this is not enforced), then that document is
+used as input:
+
+<pre class="shell"><b><i>% em.py document.em</i></b>
+<i>... document.em is processed and results written to stdout ...</i></pre>
+
+:::{warning}
+
+If your document filename begins with a `-`, it will be interpreted as
+a command line argument and cause command line option processing
+errors. Either precede it with a relative path (_e.g._, `em.py
+./-weirdname.em`) or the GNU-style `--` option which indicates there
+are no further options (_e.g._, `em.py -- -weirdname.em`).
+
+:::
+
+Any number of command line arguments (beginning with a `-`) can
+precede the document name. For instance, this command writes its
+output to document.out:
+
+<pre class="shell"><b><i>% em.py -o document.out document.em</i></b>
+<i>... document.em is processed and results written to document.out ...</i></pre>
+
+Many options are available to change the behavior of the EmPy system.
+This command will open the input file as UTF-8, write the output file
+as Latin-1, show raw errors if they occur, and delete the output file
+if an error occurs:
+
+<pre class="shell"><b><i>% em.py --input-encoding=utf-8 --output-encoding=latin-1 -r -d -o document.out document.em</i></b>
+<i>... you get the idea ...</i></pre>
+
+EmPy documents can also take arguments, which are an arbitrary
+sequence of strings that follow after the document, and are analogous
+to the Python interpreter arguments `sys.argv`:
+
+<pre class="shell"><b><i>% em.py document.em run test</i></b>
+<i>... empy.argv is ['document.em', 'run', 'test'] ...</i></pre>
+
+:::{tip}
+
+You can create executable EmPy scripts by using a bangpath:
+
+```shell
+#!/usr/bin/env em.py
+
+... EmPy code here ...
+```
+
+By default, bangpaths are treated as EmPy comments unless
+`--no-ignore-bangpaths` is specified.
+
+:::
+
+:::{tip}
+
+If you wish to run EmPy under Python 2._x_ for some reason on a system
+that also has Python 3 installed, explicitly invoke the Python 2
+interpreter before running it (`python2 em.py ...`). If you wish to
+make this more streamlined, edit the first line ("bangpath") of em.py
+and change it to read `#!/usr/bin/env python2` (or whatever your
+Python 2._x_ interpreter is named).
+
+:::
+
+:::{note}
+
+In some distribution packages, the EmPy interpreter may be named
+`empy` rather than `em.py`. In the [official release
+tarballs](#getting-the-software), and throughout this documentation,
+it is `em.py`. This is to distinguish it from the pseudomodule
+`empy`.
+
+:::
+
+:::{seealso}
+
+See the [Command line options section](#command-line-options) for a
+list of command line options that EmPy supports.
+
+:::
+
+
+### The prefix and markup expansion
+
+EmPy markup is indicated with a configurable prefix, which is by
+default the at sign (`@`). The character (Unicode code point)
+following the prefix indicates what type of markup it is. There are a
+wide variety of markups available, from comments to expression
+evaluation to statement execution, and from prefixes, literals and
+escapes to diacritics, icons and emojis. Here is a long EmPy code
+sample illustrating some of the more essential markups in EmPy, though
+there are several not shown here:
+
+:::{admonition} Example 1: Markup sample
+
+
+_Source_:
+``````
+Comments:
+The line below will not render.
+@# This is a line comment, up to and including the newline.
+If a line comment appears in the middle of a line, @# this is a comment!
+the line will be continued.
+Inline comments can be @*placed inline* (this phrase did not render,
+but note the double space due to the spaces before and after it).
+@**
+ * Or it can span multiple lines.
+ **@
+Whitespace markup consumes the following space.
+So two@ words becomes one word.
+And this @
+is a line continuation.
+@* Inline comments can be used as a line comment. *@
+Note the use of the trailing prefix to consume the final newline; this
+is a common idiom.
+
+Literals:
+Double the prefix to render it: @@.
+String literals can be used to render escaped Python strings: @
+@"A is also \N{LATIN CAPITAL LETTER A}".
+Escape markup can render arbitrary characters:
+These are all Latin capital letter A: @
+A, @\B{1000001}, @\q1001, @\o101, @\x41, @\u0041, @\U00000041, @\N{LATIN CAPITAL LETTER A}.
+Backquotes can be used to escape EmPy markup.
+This is not evaluated: @`@(!@#$%^&*()`.
+
+Expressions:
+Python expressions can be evaluated like this: 1 + 2 = @(1 + 2).
+Expressions can be arbitrary complex: @
+This is Python @('.'.join(str(x) for x in __import__('sys').version_info[:3])).
+Expressions can contain builtin ternary operators:
+Seven is an @(7 % 2 == 0 ? 'even' ! 'odd') number.
+They can even handle exceptions: @
+Division by zero is @(1/0 $ 'illegal').
+
+Statements:
+@{
+print("Hello, world!")
+x = 123
+}@
+x is now @(x), which can be simplified to @x.
+Statements can execute arbitrarily complex Python code,
+including defining functions and classes.
+
+Back to expressions, they can be simplified:
+@{
+# Define some variables.
+class Person:
+
+ def __init__(self, name):
+ self.name = name
+
+a = [4, 5, 6]
+p = Person('Fred')
+}@
+x is @x.
+a[1] is @a[1].
+The name of p is @p.name.
+You can even call functions this way:
+p's name when shouted is @p.name.upper().
+Note that the parser does not try to evaluate end-of-sentence punctuation.
+
+Control structures:
+Iterate over some numbers and classify them, but stop after 5:
+@[for n in range(-1, 10)]@
+@[ if n > 5]@
+And done.
+@[ break]@
+@[ end if]@
+@n is @
+@[ if n < 0]@
+negative@
+@[ elif n == 0]@
+zero@
+@[ elif n % 2 == 0]@
+even@
+@[ else # odd]@
+odd@
+@[ end if]@
+.
+@[end for]@
+Note the use of indentation inside control markup and end-of-line
+whitespace markup (a prefix with trailing whitespace is consumed) to
+make things more clear.
+
+You can even define your own EmPy functions:
+@[def officer(name, species, rank, role)]@
+@# The definition is EmPy, not Python!
+@name (@species, @rank, @role)@
+@[end def]@
+Some of the bridge crew of the USS Enterprise (NCC-1701):
+- @officer("James T. Kirk", "Human", "captain", "commanding officer")
+- @officer("Spock", "Vulcan-Human hybrid", "commander", "science officer")
+- @officer("Montgomery Scott", "Human", "commander", "chief engineer")
+- @officer("Nyota Uhura", "Human", "lieutenant commander", "communications officer")
+- @officer("Hikaru Sulu", "Human", "commander", "astrosciences/helmsman")
+
+Diacritics: Libert@^e', égalit@^e', fraternit@^e'!
+Icons for curly quotes: @|"(these are curly quotes.@|")
+This is an emoji: @:pile of poo:. (Of course I would choose that one.)
+``````
+
+_Output_:
+``````
+Comments:
+The line below will not render.
+If a line comment appears in the middle of a line, the line will be continued.
+Inline comments can be (this phrase did not render,
+but note the double space due to the spaces before and after it).
+Whitespace markup consumes the following space.
+So twowords becomes one word.
+And this is a line continuation.
+Note the use of the trailing prefix to consume the final newline; this
+is a common idiom.
+
+Literals:
+Double the prefix to render it: @.
+String literals can be used to render escaped Python strings: A is also A.
+Escape markup can render arbitrary characters:
+These are all Latin capital letter A: A, A, A, A, A, A, A, A.
+Backquotes can be used to escape EmPy markup.
+This is not evaluated: @(!@#$%^&*().
+
+Expressions:
+Python expressions can be evaluated like this: 1 + 2 = 3.
+Expressions can be arbitrary complex: This is Python 3.10.12.
+Expressions can contain builtin ternary operators:
+Seven is an odd number.
+They can even handle exceptions: Division by zero is illegal.
+
+Statements:
+Hello, world!
+x is now 123, which can be simplified to 123.
+Statements can execute arbitrarily complex Python code,
+including defining functions and classes.
+
+Back to expressions, they can be simplified:
+x is 123.
+a[1] is 5.
+The name of p is Fred.
+You can even call functions this way:
+p's name when shouted is FRED.
+Note that the parser does not try to evaluate end-of-sentence punctuation.
+
+Control structures:
+Iterate over some numbers and classify them, but stop after 5:
+-1 is negative.
+0 is zero.
+1 is odd.
+2 is even.
+3 is odd.
+4 is even.
+5 is odd.
+And done.
+Note the use of indentation inside control markup and end-of-line
+whitespace markup (a prefix with trailing whitespace is consumed) to
+make things more clear.
+
+You can even define your own EmPy functions:
+Some of the bridge crew of the USS Enterprise (NCC-1701):
+- James T. Kirk (Human, captain, commanding officer)
+- Spock (Vulcan-Human hybrid, commander, science officer)
+- Montgomery Scott (Human, commander, chief engineer)
+- Nyota Uhura (Human, lieutenant commander, communications officer)
+- Hikaru Sulu (Human, commander, astrosciences/helmsman)
+
+Diacritics: Liberté, égalité, fraternité!
+Icons for curly quotes: “these are curly quotes.”
+This is an emoji: 💩. (Of course I would choose that one.)
+``````
+:::
+
+
+:::{tip}
+
+If you wish to change the prefix, use `-p`/`--prefix=CHAR` (_environment variable:_ `EMPY_PREFIX`, _configuration variable:_ `prefix`).
+
+:::
+
+:::{seealso}
+
+See the [Markup section](#markup) for detailed specifications on all
+support EmPy markup.
+
+:::
+
+
+### Pseudomodule and interpreter
+
+The interpreter instance is available to a running EmPy system through
+the globals; by default, it is named
+`empy`. When it is referenced this
+way, it is called a pseudomodule (since it acts like a module but it
+is not actually a module you can import):
+
+:::{admonition} Example 2: Pseudomodule sample
+
+
+_Source_:
+``````
+This version of EmPy is @empy.version.
+The prefix in this interpreter is @empy.getPrefix() @
+and the pseudomodule name is @empy.config.pseudomoduleName.
+Do an explicit write: @empy.write("Hello, world!").
+The context is currently @empy.getContext().
+Adding a new global in a weird way: @empy.updateGlobals({'q': 789})@
+Now q is @q!
+You can do explicit expansions: @empy.expand("1 + 1 = @(1 + 1)").
+q is @(empy.defined('q') ? 'defined' ! 'undefined').
+``````
+
+_Output_:
+``````
+This version of EmPy is 4.0.1.
+The prefix in this interpreter is @ and the pseudomodule name is empy.
+Do an explicit write: Hello, world!.
+The context is currently <example 2>:5:26.
+Adding a new global in a weird way: Now q is 789!
+You can do explicit expansions: 1 + 1 = 2.
+q is defined.
+``````
+:::
+
+
+:::{seealso}
+
+See the [Pseudomodule/interpreter section](#pseudomodule-interpreter)
+for details on the pseudomodule/interpreter.
+
+:::
+
+
+### Diversions, filters & hooks
+
+Diversions can defer and replay output at a desired time:
+
+:::{admonition} Example 3: Diversions sample
+
+
+_Source_:
+``````
+This text is output normally.
+@empy.startDiversion('A')@
+(This text was diverted!)
+@empy.stopDiverting()@
+This text is back to being output normally.
+Now playing the diversion:
+@empy.playDiversion('A')@
+And now back to normal output.
+``````
+
+_Output_:
+``````
+This text is output normally.
+This text is back to being output normally.
+Now playing the diversion:
+(This text was diverted!)
+And now back to normal output.
+``````
+:::
+
+
+Filters can modify output before sending it to the final stream:
+
+:::{admonition} Example 4: Filters sample
+
+
+_Source_:
+``````
+@{
+# For access to the filter classes.
+import emlib
+}@
+This text is normal.
+@empy.appendFilter(emlib.FunctionFilter(lambda x: x.upper()))@
+This text is in all uppercase!
+@empy.appendFilter(emlib.FunctionFilter(lambda x: '[' + x + ']'))@
+Now it's also surrounded by brackets!
+(Note the brackets are around output as it is sent,
+not at the beginning and end of each line.)
+@empy.resetFilter()@
+Now it's back to normal.
+``````
+
+_Output_:
+``````
+This text is normal.
+THIS TEXT IS IN ALL UPPERCASE!
+[NOW IT'S ALSO SURROUNDED BY BRACKETS!
+(NOTE THE BRACKETS ARE AROUND OUTPUT AS IT IS SENT,
+NOT AT THE BEGINNING AND END OF EACH LINE.)
+]Now it's back to normal.
+``````
+:::
+
+
+Hooks can intercept and even alter the behavior of a running system:
+
+:::{admonition} Example 5: Hooks sample
+
+
+_Source_:
+``````
+@# Modify the backquote markup to prepend and append backquotes
+@# (say, for a document rendering system, cough cough).
+@{
+import emlib
+
+class BackquoteHook(emlib.Hook):
+
+ def __init__(self, interp):
+ self.interp = interp
+
+ def preBackquote(self, literal):
+ self.interp.write('`' + literal + '`')
+ return True # return true to skip the standard behavior
+
+empy.addHook(BackquoteHook(empy))
+}@
+Now backquote markup will render with backquotes: @
+@`this is now in backquotes`!
+``````
+
+_Output_:
+``````
+Now backquote markup will render with backquotes: `this is now in backquotes`!
+``````
+:::
+
+
+:::{seealso}
+
+See the [Diversions section](#diversions), [Filters
+section](#filters), or the [Hooks section](#hooks) for more
+information.
+
+:::
+
+
+### Embedding
+
+EmPy is modular and can be embedded in your Python programmers, rather
+than running it standalone. Simply import the `em` module and create
+an `Interpreter`:
+
+```python
+import sys
+
+import em
+
+config = em.Configuration(...)
+output = sys.stdout
+with em.Interpreter(config=config, output=output) as interp:
+ ... do things with interp ...
+```
+
+An exception which occurs during processing will be handled by the
+interpreter's error handler.
+
+For one-off uses, you can use the global, standalone `expand` function:
+
+```python
+import em
+
+result = em.expand(source)
+```
+
+When calling this function, an ephemeral interpreter is dynamically
+created, used, and shutdown to perform the expansion. If an exception
+occurs during this processing, it will be raised to the caller, rather
+than handled by the ephemeral interpreter.
+
+:::
+
+:::{important}
+
+When you create an interpreter, you must call its `shutdown` method
+when you are done. This is required to remove the proxy on
+`sys.stdout` that EmPy requires for proper operation and restore your
+Python environment to the state it was before creating the
+interpreter. This can be accomplished by creating the interpreter in
+a `with` statement -- interpreters are also context managers -- or by
+creating it and shutting it down in a `try`/`finally` statement.
+
+This is not needed when calling the `expand` global function; it
+creates and shuts down an ephemeral interpreter automatically.
+
+:::
+
+:::{seealso}
+
+See the [Embedding EmPy section](#embedding-empy) section for more
+details on embedding EmPy in your Python programs.
+
+:::
+
+
+### Getting help
+
+For basic help, use the `-h`/`--help` option:
+
+<pre class="shell"><b><i>% em.py -h # or: --help</i></b>
+Welcome to EmPy version 4.0.1.
+
+USAGE:
+./em.py [<options>] [<filename, or `-` for stdin> [<argument>...]]
+ - Options begin with `-` or `--`
+ - Specify a filename (and arguments) to process that file as input
+ - Specify `-` (and arguments) to process stdin with standard buffering
+ - Specify no filename to enter interactive mode with line buffering
+ - Specify `--` to stop processing options
+
+...</pre>
+
+For more help, repeat the `-h`/`--help` option (up to three times
+for the full help). For help on a particular topic, use the
+`-H`/`--topics=TOPICS` option, where `TOPICS` is a comma-separated list of
+topics. The list of available topics can be shown by using the topic
+`topics`:
+
+<pre class="shell"><b><i>% em.py -H topics # or: --topics=topics</i></b>
+Welcome to EmPy version 4.0.1.
+
+TOPICS:
+Need more help? Add more -h options (-hh, -hhh) for more help. Use -H <topic>
+for help on a specific topic, or specify a comma-separated list of topics. Try
+`default` (-h) for default help, `more` (-hh) for more common topics, `all`
+(-hhh) for all help topics, or `topics` for this list. Use -V for version
+information, -W for version and system information, or -Z for all debug
+details. Available topics:
+ usage Basic command line usage
+ options Command line options
+ markup Markup syntax
+ escapes Escape sequences
+ environ Environment variables
+ pseudo Pseudomodule attributes and functions
+ constructor Keyword arguments for the Interpreter constructor
+ variables Configuration variable attributes
+ methods Configuration methods
+ hooks Hook methods
+ named Named escapes
+ diacritics Diacritic combiners
+ icons Icons
+ hints Usage hints
+ topics This list of topics</pre>
+
+:::{tip}
+
+Repeating the help option once (`-hh`) is the same as requesting the
+`more` topic (`-H more`). Repeating it three times (`-hhh`) is the
+same as requesting the `all` topic (`-H all`).
+
+:::
+
+:::{warning}
+
+The builtin help system requires the presence of the `emhelp` module.
+If you have a minimal EmPy installation, this module may not be
+available. You can get it from the [release
+tarball](#getting-the-software).
+
+:::
+
+:::{seealso}
+
+See the rest of this document for details and specifications on all
+the markup and features, and see the [Help topics
+section](http://www.alcyone.com/software/empy/HELP.html) for the output of all the
+builtin help topics.
+
+:::
+
+
+## Markup
+
+EmPy markup always begins with the EmPy prefix, which defaults to
+`@`. The character (Unicode code point) following the prefix
+indicates what type of markup it is, and the different types of markup
+are parsed differently.
+
+It is legal to set the EmPy prefix to `None`; then, no markup will be
+parsed or expanded and EmPy will merely process filters and encoding
+conversions. This can be done from the command line with the
+`--no-prefix` option, or by indicating a prefix that is an
+empty string (`''`) or the word `none`.
+
+Using a non-default prefix that is also the first character of an
+existing markup will swap that markup character with the default. For
+example, setting the prefix to `$` would otherwise collide with the
+in-place token (`@$...$...$` with a default prefix). On startup
+it will be adjusted so that with a `$` prefix the in-place markup can
+be accessed as `$@...@...@`.
+
+The following subsections list the types of markup supported by EmPy
+and in which version they were introduced, organized by category.
+
+:::{important}
+
+All of the following code snippets and examples below assume that the
+prefix is the default, `@`. It can be changed with
+`-p`/`--prefix=CHAR` (_environment variable:_ `EMPY_PREFIX`, _configuration variable:_ `prefix`).
+
+:::
+
+| Markup | Syntax | Description | Ver. |
+| --- | --- | --- | --- |
+| [Line comment](#line-comment-markup) | `@#... NL` | Consumes text up to and including newline | 1.0 |
+| [Inline comment](#inline-comment-markup) | `@*...*` | Consumes text up to and including the final asterisk(s) | 4.0 |
+| [Whitespace](#whitespace-markup) | `@ WS` | Consumes the following whitespace character | 1.0 |
+| [Prefix](#prefix-markup) | `@@` | Produces the prefix character | 1.0 |
+| [String](#string-markup) | `@'...'`, `@"..."`, `@'''...'''`, `@"""..."""` | Produces a string from a literal | 3.1.1 |
+| [Backquote](#backquote-markup) | `` @`...` `` | Quotes contained markup up to final backquote(s) | 4.0 |
+| [Escape](#escape-markup) | `@\...` | Render an escape character | 1.5 |
+| [Named escape](#named-escape-markup) | `@\^{...}` | Render an escape control character by name | 4.0 |
+| [Expression](#expression-markup) | `@(...)` | Evaluates an expression | 1.0 |
+| [Simple expression](#simple-expression-markup) | `@variable`, `@object.attribute`, `@array[index]`, `@function(args...)`, etc. | Evaluates a simple expression | 1.0 |
+| [Functional expression](#functional-expression-markup) | `@function{markup}{...}` | Evaluates a functional expression | 4.0 |
+| [Extended expression](#extended-expression-markup) | `@(...?...!...$...)` | Expression evaluation with if-else-finally | 3.0 |
+| [In-place expression](#in-place-expression-markup) | `@$...$...$` | Copies and evaluates an expression | 1.4 |
+| [Statement](#statement-markup) | `@{...}` | Executes a statement or statements | 1.0 |
+| [If control](#if-control-markup) | `@[if C]`…`@[elif C]`…`@[else]`…`@[end if]` | Branching control structure | 3.0 |
+| [Break control](#break-and-continue-control-markup) | `@[break]` | Break out of repeating control structure | 3.0 |
+| [Continue control](#break-and-continue-control-markup) | `@[continue]` | Continue with next iteration of repeating structure | 3.0 |
+| [For control](#for-control-markup) | `@[for N in E]`…`@[else]`…`@[end for]` | Iterating control structure | 3.0 |
+| [While control](#while-control-markup) | `@[while E]`…`@[else]`…`@[end while]` | Looping control structure | 3.0 |
+| [Dowhile control](#dowhile-control-markup) | `@[dowhile E]`…`@[else]`…`@[end dowhile]` | Do/while analog control structure from C, C++ | 4.0 |
+| [Try control](#try-control-markup) | `@[try]`…`@[except E as N]`…`@[else]`…`@[finally]`…`@[end try]` | Exception handling control markup | 3.0 |
+| [With control](#with-control-markup) | `@[with E as N]`…`@[end with]` | Handle a context manager | 4.0 |
+| [Defined control](#defined-control-markup) | `@[defined N]`…`@[else]`…`@[end defined]` | Branch on whether a variable is defined | 4.0 |
+| [Def control](#def-control-markup) | `@[def F(...)]`…`@[end def]` | Define an EmPy function | 3.0 |
+| [Diacritic](#diacritic-markup) | `@^...` | Normalize and render a diacritic | 4.0 |
+| [Icon](#icon-markup) | `@\|...` | Render a customizable icon | 4.0 |
+| [Emoji](#emoji-markup) | `@:...:` | Render a customizable emoji | 4.0 |
+| [Significator](#significator-markup) | `@%[!]... NL`, `@%%[!]...%% NL` | Declare a significator | 1.2 |
+| [Context name](#context-name-markup) | `@?... NL` | Set the context filename | 3.0.2 |
+| [Context line](#context-line-markup) | `@!... NL` | Set the context line | 3.0.2 |
+| [Custom](#custom-markup) | `@<...>` | Fully-customizable markup with no set definition | 3.3 |
+
+:::{seealso}
+
+The list of supported markup is available in the `markup` help topic
+and is summarized [here](http://www.alcyone.com/software/empy/HELP.html#markup-summary).
+
+:::
+
+
+### Comments
+
+Comment markup consumes its contents and performs no output. A few
+variants of comment markup are available.
+
+
+#### Line comment markup: `@#... NL`
+
+**Line comment markup** consists of a starting `@#` and consumes up
+until (and including) the following newline. Note that if the markup
+appears in the middle of a line, that line will be continued since it
+consumes the ending newline.
+
+:::{admonition} Example 6: Line comments
+
+
+_Source_:
+``````
+@# This is a comment. It will not render in the output.
+@# Even would-be EmPy markup is consumed by a comment: @(!@#$%^&*()
+Welcome to EmPy!
+Here's some text @# This will consume the rest of the line
+on the same line.
+``````
+
+_Output_:
+``````
+Welcome to EmPy!
+Here's some text on the same line.
+``````
+:::
+
+
+:::{note}
+
+Line comment markup was introduced in EmPy version 1.0.
+
+:::
+
+
+#### Inline comment markup: `@*...*`
+
+**Inline comment markup** (`@*...*`) is a form of comment markup
+that can appear anywhere in text and can even span multiple lines. It
+consumes everything up to and including the final asterisk(s).
+
+:::{admonition} Example 7: Inline comments, basic
+
+
+_Source_:
+``````
+This is text. @* This is a comment in the text. * This is continuing text.
+(Note the extra spaces around where the comment was.)
+@* A trailing whitespace markup consumes the whole line. *@
+There is no extraneous blank line here.
+``````
+
+_Output_:
+``````
+This is text. This is continuing text.
+(Note the extra spaces around where the comment was.)
+There is no extraneous blank line here.
+``````
+:::
+
+
+Multiple asterisks can be used as long as they are matched with the
+end of the markup. This allows asterisks to appear in the comment:
+
+:::{admonition} Example 8: Inline comments, advanced
+
+
+_Source_:
+``````
+@** Here's an asterisk inside the comment: * **@
+@*** There can * be any number of asterisks ** as
+ long as it's * less than ** the delimiters. ***@
+@**
+ * This is a multiline inline comment.
+ **@
+@*************************************
+ * This comment thinks it's so cool. *
+ *************************************@
+So many comments!
+``````
+
+_Output_:
+``````
+So many comments!
+``````
+:::
+
+
+:::{attention}
+
+Note that when markup which has starting and ending delimiters appears
+alone on a line, the trailing newline will be rendered in the output.
+To avoid these extra newlines, use a trailing `@` to turn it into
+whitespace markup which consumes that trailing newline, so _e.g._
+`@{...}` followed by a newline becomes `@{...}@` followed by a
+newline. This is idiomatic for suppressing unwanted newlines. See
+[here](#idiom) for more details.
+
+:::
+
+:::{note}
+
+Inline comment markup was introduced in EmPy version 4.0.
+
+:::
+
+
+#### Whitespace markup: `@ WS`
+
+While not quite a comment, **whitespace markup** is sufficiently
+common and useful that it warrants introduction early on. The
+interpreter prefix followed by any whitespace character, including a
+newline, is consumed. This allows a way to concatenate two strings,
+create a line continuation, or create a line separator:
+
+:::{admonition} Example 9: Whitespace, basic
+
+
+_Source_:
+``````
+This was two@ words. Now it is one.
+Note that this consumes the newline @
+so that this is on the same line.
+@
+Note there is no blank line above.
+``````
+
+_Output_:
+``````
+This was twowords. Now it is one.
+Note that this consumes the newline so that this is on the same line.
+Note there is no blank line above.
+``````
+:::
+
+
+::::{tip}
+
+{#idiom}
+A trailing prefix after markup which has beginning and ending
+delimiters -- for instance, inline comment (`@*...*`), expression
+(`@(...)`), statement (`@{...}`), control (`@[...]`), and
+custom (`@<...>`) -- is idiomatic for suppressing the newline when
+there is nothing at the end of the line after the markup. The
+trailing prefix will consume the final newline, eliminating unwanted
+newlines.
+
+For example, using a statement markup (see below) on a whole line will
+result in a seemingly spurious newline:
+
+:::{admonition} Example 10: Whitespace, idiom
+
+
+_Source_:
+``````
+Statement markup:
+@{x = 123}
+Note there's an extra newline above from the EmPy code after the
+statement markup. The markup itself doesn't print anything; it's from
+the trailing newline after the markup.
+
+To suppress the extra newline:
+@{x = 456}@
+The trailing prefix above consumes the trailing newline, eliminating it.
+``````
+
+_Output_:
+``````
+Statement markup:
+
+Note there's an extra newline above from the EmPy code after the
+statement markup. The markup itself doesn't print anything; it's from
+the trailing newline after the markup.
+
+To suppress the extra newline:
+The trailing prefix above consumes the trailing newline, eliminating it.
+``````
+:::
+
+
+::::
+
+:::{note}
+
+Whitespace markup was introduced in EmPy version 1.0.
+
+:::
+
+### Literals
+
+**Literals** are a category of markup that evaluate to some form of
+themselves.
+
+
+#### Prefix markup: `@@`
+
+To render the **prefix** character literally in the output, duplicate
+it. For the default, `@`, it will be `@@`:
+
+:::{admonition} Example 11: Prefix literals
+
+
+_Source_:
+``````
+This becomes a single at sign: @@.
+``````
+
+_Output_:
+``````
+This becomes a single at sign: @.
+``````
+:::
+
+
+:::{tip}
+
+The prefix markup is not indicated by the prefix followed by an at
+sign, but rather the prefix repeated twice. So if the prefix has been
+changed to `$`, the prefix markup is `$$`, not `$@`.
+
+:::
+
+:::{note}
+
+Prefix markup was introduced in EmPy version 1.0.
+
+:::
+
+#### String markup: `@'...'`, `@"..."`, `@'''...'''`, `@"""..."""`
+
+The interpreter prefix followed by a Python **string** literal
+(_e.g._, `@'...'`) evaluates the Python string literal and expands
+it. All variants of string literals with single and double quotes, as
+well as triple quoted string literals (with both variants) are
+supported. This can be useful when you want to use Python string
+escapes (not EmPy escapes) in a compact form:
+
+:::{admonition} Example 12: String
+
+
+_Source_:
+``````
+This is a string: @'A single-quoted string'.
+This is also a string: @"A double-quoted string".
+This is another string: @'''A triple single-quoted string'''.
+This is yet another string: @"""A triple double-quoted string""".
+This is a multiline string: @"""Triple quotes containing newlines
+will be preserved."""
+This is a string using escapes: @
+@'Welcome to \U0001d53c\U0001d55e\u2119\U0001d56a!'.
+``````
+
+_Output_:
+``````
+This is a string: A single-quoted string.
+This is also a string: A double-quoted string.
+This is another string: A triple single-quoted string.
+This is yet another string: A triple double-quoted string.
+This is a multiline string: Triple quotes containing newlines
+will be preserved.
+This is a string using escapes: Welcome to 𝔼𝕞ℙ𝕪!.
+``````
+:::
+
+
+:::{note}
+
+String markup was introduced in EmPy version 3.1.1.
+
+:::
+
+
+#### Backquote markup: `` @`...` ``
+
+**Backquote** markup (`` @`...` ``) can be used to escape any text,
+including EmPy markup. Multiple opening backquotes can be used as
+long as they are matched by an equal number in order to allow quoting
+text which itself has backquotes in it:
+
+:::{admonition} Example 13: Backquote
+
+
+_Source_:
+``````
+This is literal text: @`some text`.
+This is a prefix: @`@`.
+This would be expanded if it were not backquoted: @`@(1 + 1)`.
+This would be an error if expanded: @`@(!@#$%^&*())`.
+This contains backquotes: @```here's one: ` and here's two: `` ```.
+``````
+
+_Output_:
+``````
+This is literal text: some text.
+This is a prefix: @.
+This would be expanded if it were not backquoted: @(1 + 1).
+This would be an error if expanded: @(!@#$%^&*()).
+This contains backquotes: here's one: ` and here's two: `` .
+``````
+:::
+
+
+:::{warning}
+
+To use the backquote markup with content containing backquotes which
+are adjacent to the start or end markup, you need to pad it with
+spaces. So when quoting a single backquote, it needs to be written as
+```@`` ` `` ```. This also means you cannot use backquote markup to
+specify a completely empty string. It must always contain at least
+one non-backquote character, e.g., `` @` ` ``. If you really need
+backquotes without whitespace padding, you can use a [hook](#hooks) to
+intercept the backquote markup and strip it out.
+
+:::
+
+:::{attention}
+
+Note that when markup which has starting and ending delimiters appears
+alone on a line, the trailing newline will be rendered in the output.
+To avoid these extra newlines, use a trailing `@` to turn it into
+whitespace markup which consumes that trailing newline, so _e.g._
+`@{...}` followed by a newline becomes `@{...}@` followed by a
+newline. This is idiomatic for suppressing unwanted newlines. See
+[here](#idiom) for more details.
+
+:::
+
+:::{note}
+
+Backquote markup was introduced in EmPy version 4.0.
+
+:::
+
+
+### Escape markup: `@\...`
+
+**Escape markup** allows specifying individual non-printable
+characters with a special readable syntax: `@\...`. It is inspired
+by and extends the string literal escape codes from languages such as
+C/C++ and Python.
+
+:::{admonition} Example 14: Escapes
+
+
+_Source_:
+``````
+@# These are all a Latin uppercase A:
+Binary: @\B{1000001}
+Quaternary: @\q1001, @\Q{1001}
+Octal: @\o101, @\O{101}
+Hexadecimal (variable bytes): @\X{41}
+Hexadecimal (one-byte): @\x41
+Hexadecimal (two-byte): @\u0041
+Hexadecimal (eight-byte): @\U00000041
+By Unicode name: @\N{LATIN CAPITAL LETTER A}
+``````
+
+_Output_:
+``````
+Binary: A
+Quaternary: A, A
+Octal: A, A
+Hexadecimal (variable bytes): A
+Hexadecimal (one-byte): A
+Hexadecimal (two-byte): A
+Hexadecimal (eight-byte): A
+By Unicode name: A
+``````
+:::
+
+
+The escape sequence type is indicated by the first character and then
+consumes zero or more characters afterward, depending on the escape
+sequence. Some sequence sequences support a variable number of
+characters, delimited by curly braces (`{...}`).
+
+:::{seealso}
+
+The list of all valid escape sequences is available in the `escapes`
+help topic and is summarized
+[here](http://www.alcyone.com/software/empy/HELP.html#escape-sequences-summary).
+
+:::
+
+:::{note}
+
+Escape markup was introduced in EmPy version 1.5, and then reworked in
+EmPy version 4.0.
+
+:::
+
+
+#### Named escape markup: `@\^{...}`
+
+The escape markup for controls `@\^...` has an extended usage where
+the character can be specified by a control code name. The resulting
+**named escape markup** takes the form of `@\^{...}` with the escape
+code name between the curly braces. The name of the escape code used
+in the markup is case insensitive.
+
+The mapping of escape names to characters is specified in the
+configuration variable `controls`. The keys of this
+dictionary must be in uppercase and the values can be integers
+(Unicode code point values), lists of integers, or strings. They can
+also take the form of a 2-tuple, where the first element is one of the
+above values and the second element is a description string used for
+displaying in help topics.
+
+:::{admonition} Example 15: Named escapes
+
+
+_Source_:
+``````
+Normal space: [ ]
+Normal space by name: [@\^{SP}]
+No-break space: [@\^{NBSP}]
+Thin space: [@\^{THSP}]
+En space: [@\^{ENSP}]
+Em space: [@\^{EMSP}]
+(Well, these would look right if it this were in a proportional font.)
+``````
+
+_Output_:
+``````
+Normal space: [ ]
+Normal space by name: [ ]
+No-break space: [ ]
+Thin space: [ ]
+En space: [ ]
+Em space: [ ]
+(Well, these would look right if it this were in a proportional font.)
+``````
+:::
+
+
+:::{seealso}
+
+The list of all valid control code names is available in the
+`named` help topic and is summarized
+[here](http://www.alcyone.com/software/empy/HELP.html#named-escapes-summary).
+
+:::
+
+:::{note}
+
+Named escape markup was introduced in EmPy version 4.0.
+
+:::
+
+
+### Expression markup: `@(...)`
+
+EmPy mainly processes markups by evaluating expressions and executing
+statements. Expressions are bits of Python code that return a value;
+that value is then rendered into the output stream. Simple examples
+of Python expressions are `1 + 2`, `abs(-2)`, or `"test"*3`.
+
+In EmPy, expressions are evaluated and expanded with the **expression
+markup** `@(...)`. By default, an expression that evaluates to
+`None` does not print anything to the underlying output stream; it is
+equivalent to it having returned `''`.
+
+:::{tip}
+
+If you want to change this behavior, specify your preferred value with
+`--none-symbol` (_configuration variable:_ `noneSymbol`).
+
+:::
+
+:::{admonition} Example 16: Expressions
+
+
+_Source_:
+``````
+The sum of 1 and 2 is @(1 + 2).
+The square of 3 is @(3**2).
+The absolute value of -12 is @(abs(-12)).
+This prints "test" but does not print None: @(print("test", end='')).
+This, however, does: @(repr(None)).
+``````
+
+_Output_:
+``````
+The sum of 1 and 2 is 3.
+The square of 3 is 9.
+The absolute value of -12 is 12.
+This prints "test" but does not print None: test.
+This, however, does: None.
+``````
+:::
+
+
+:::{attention}
+
+Note that when markup which has starting and ending delimiters appears
+alone on a line, the trailing newline will be rendered in the output.
+To avoid these extra newlines, use a trailing `@` to turn it into
+whitespace markup which consumes that trailing newline, so _e.g._
+`@{...}` followed by a newline becomes `@{...}@` followed by a
+newline. This is idiomatic for suppressing unwanted newlines. See
+[here](#idiom) for more details.
+
+:::
+
+:::{note}
+
+Expression markup was introduced in EmPy version 1.0.
+
+:::
+
+### Additional expression markup
+
+Several expression markup variants are available.
+
+#### Simple expression markup: `@x`, `@x.a`, `@x[i]`, `@x(args...)`, _etc._
+
+Often expressions are "simple" and unambiguous enough that needing to
+use the full `@(...)` syntax is unnecessary. In cases where a
+single variable is being referenced unambiguously, the parentheses can
+be left off to create **simple expression markup**:
+
+:::{admonition} Example 17: Simple expressions, basic
+
+
+_Source_:
+``````
+@# Set a variable to use.
+@{x = 16309}@
+The value of x is @x.
+``````
+
+_Output_:
+``````
+The value of x is 16309.
+``````
+:::
+
+
+`@x` is precisely the same thing as `@(x)`.
+
+This markup can be extended further. Attribute references (`@x.a`),
+indexing (`@x[i]`), and function calls (`@x(args...)`) can also be
+simplified in this way. They can also be chained together
+arbitrarily, so `@object.attribute.subattribute`,
+`@object.method(arguments...)`, `@object[index1][index2]`,
+`@object[index].attribute`, `@object[index].method(arguments...)`,
+etc. are all valid examples of simple expression markup. These simple
+expressions can be extended arbitrarily.
+
+:::{admonition} Example 18: Simple expressions, chaining
+
+
+_Source_:
+``````
+@# Define some variables to use.
+@{
+import time
+
+def mean(seq): # a function
+ return sum(seq)/len(seq)
+
+class Person: # a class
+
+ def __init__(self, name, birth, scores):
+ self.name = name
+ self.birth = birth
+ self.scores = scores
+
+ def age(self):
+ current = time.localtime(time.time()).tm_year
+ return current - self.birth
+
+person = Person("Fred", 1984, [80, 100, 70, 90]) # an instance of that class
+}@
+The name of person is @(person.name), or more simply @person.name.
+The first letter is @(person.name[0]), or more simply @person.name[0].
+He has @(len(person.scores)) scores, or more simply @len(person.scores).
+His first score is @(person.scores[0]), or more simply @person.scores[0].
+His average score is @(mean(person.scores)), or more simply @mean(person.scores).
+His age is @(person.age()), or more simply @person.age().
+``````
+
+_Output_:
+``````
+The name of person is Fred, or more simply Fred.
+The first letter is F, or more simply F.
+He has 4 scores, or more simply 4.
+His first score is 80, or more simply 80.
+His average score is 85.0, or more simply 85.0.
+His age is 39, or more simply 39.
+``````
+:::
+
+
+:::{note}
+
+Final punctuation, including a period (`.`), is not interpreted as an
+attribute reference and thus does not result in a parse error. Thus
+you can use end-of-sentence punctuation naturally after a simple
+expression markup.
+
+:::
+
+If you wish to concatenate an expression with immediately following
+text so that it will not be parsed incorrectly, either use whitespace
+markup or just fall back to a full expression markup:
+
+:::{admonition} Example 19: Simple expressions, concatenation
+
+
+_Source_:
+``````
+@# Define a variable for use.
+@{thing = 'cat'}@
+@# Referencing `@things` to pluralize `@thing` will not work. But:
+The plural of @thing is @thing@ s.
+Or: The plural of @thing is @(thing)s.
+``````
+
+_Output_:
+``````
+The plural of cat is cats.
+Or: The plural of cat is cats.
+``````
+:::
+
+
+:::{note}
+
+Simple expression markup was introduced in EmPy version 1.0.
+
+:::
+
+
+##### Functional expression markup: `@function{markup}{...}`
+
+Arguments to function calls in EmPy expression markups use Python
+expressions, not EmPy markup (_e.g._, `@f(x)` calls the function `f`
+with the variable `x`). To specify EmPy markup which is expanded and
+then passed in to the function, there is **functional expression
+markup** as an extension of simple expression markup. Since each
+argument to the function is expanded, the arguments are always
+strings:
+
+:::{admonition} Example 20: Functional expressions, one argument
+
+
+_Source_:
+``````
+@{
+def f(x):
+ return '[' + x + ']'
+}@
+@# Note that the argument is expanded before being passed to the function:
+This will be in brackets: @f{1 + 1 is @(1 + 1)}.
+``````
+
+_Output_:
+``````
+This will be in brackets: [1 + 1 is 2].
+``````
+:::
+
+
+Functional expressions support the application of multiple arguments
+by repeating the `{...}` suffix for as many arguments as is desired:
+
+:::{admonition} Example 21: Functional expressions, multiple arguments
+
+
+_Source_:
+``````
+@{
+def f(x, y, z):
+ return x.lower() + ', ' + y.upper() + ', ' + z.capitalize()
+}@
+@# Multiple arguments are possible by repeating the pattern:
+These expansions are separated by commas: @
+@f{lowercase: @(1)}{uppercase: @(1 + 1)}{capitalized: @(1 + 1 + 1)}.
+``````
+
+_Output_:
+``````
+These expansions are separated by commas: lowercase: 1, UPPERCASE: 2, Capitalized: 3.
+``````
+:::
+
+
+:::{warning}
+
+Functional expression markup is an extension of simple expression
+markup so cannot be surrounded in parentheses. Further, it cannot be
+seemlessly combined with normal function call, so `@f(1){a}{b}` is
+equivalent to `@(f(1)('a', 'b'))`, not `@(f(1, 'a', 'b'))`.
+Functional argument calls will end simple expression, so
+`@f{a}{b}(3)` is the same as `@(f('a', 'b'))(3)`, not `@f('a', 'b',
+3)`; that is, trailing function calls are not applied.
+
+:::
+
+:::{note}
+
+Functional expression markup was introduced in EmPy version 4.0.
+
+:::
+
+
+#### Extended expression markup: `@(...?...!...$...)`
+
+Expression markup has an **extended expression markup** form which
+allows more powerful manipulation of expressions.
+
+The first form allows for a compact form of an `@[if]` statement with
+a ternary operator, similar to C/C++'s `?` and `:` operators. In
+EmPy, however, these are represented with `?` and `!`, respectively.
+
+:::{note}
+
+C/C++'s use of `:` was changed to `!` for EmPy since `:` already has
+special meaning in Python. This syntax was originally added before
+Python supported the `if/else` ternary expression, although EmPy's
+syntax is more general and powerful.
+
+:::
+
+If a `?` is present in the expression, then the Python (not EmPy)
+expression before the `?` is tested; if it is true, then the Python
+expression following it is evaluated. If a `!` is present afterward
+and the originally expression was false, then the Python expression
+following it is expanded (otherwise, nothing is). It thus acts as an
+if-then-else construct:
+
+:::{admonition} Example 22: Extended expressions, if-else
+
+
+_Source_:
+``````
+Four is an @(4 % 2 == 0 ? 'even' ! 'odd') number.
+Seven is an @(7 % 2 == 0 ? 'even' ! 'odd') number.
+@# Whitespace is not required:
+Eleven is an @(11 % 2 == 0?'even'!'odd') number.
+``````
+
+_Output_:
+``````
+Four is an even number.
+Seven is an odd number.
+Eleven is an odd number.
+``````
+:::
+
+
+These `?` and `!` sequences can be repeated indefinitely, forming an
+if-else if-else chain, with a `!` expression serving as the
+conditional test for the next `?`:
+
+:::{admonition} Example 23: Extended expressions, chained if-else
+
+
+_Source_:
+``````
+@# Define a variable for use.
+@{x = 3}@
+x is @(x == 1 ? 'one' ! x == 2 ? 'two' ! x == 3 ? 'three' ! 'unknown').
+``````
+
+_Output_:
+``````
+x is three.
+``````
+:::
+
+
+Finally, a `$` present at the end of any if-else chain represents an
+except expression: If the main expression throws an exception,
+suppress it and evaluate the Python (not EmPy) except expression
+instead. This can be combined with the chained if-else notation:
+
+:::{admonition} Example 24: Extended expressions, except
+
+
+_Source_:
+``````
+No exception: 2 + 2 = @(2 + 2 $ 'oops').
+Division by zero is @(1/0 $ 'illegal').
+Two divided by zero is @(2/0 % 2 == 0 ? 'even' ! 'odd' $ 'also illegal').
+``````
+
+_Output_:
+``````
+No exception: 2 + 2 = 4.
+Division by zero is illegal.
+Two divided by zero is also illegal.
+``````
+:::
+
+
+:::{attention}
+
+Note that when markup which has starting and ending delimiters appears
+alone on a line, the trailing newline will be rendered in the output.
+To avoid these extra newlines, use a trailing `@` to turn it into
+whitespace markup which consumes that trailing newline, so _e.g._
+`@{...}` followed by a newline becomes `@{...}@` followed by a
+newline. This is idiomatic for suppressing unwanted newlines. See
+[here](#idiom) for more details.
+
+:::
+
+:::{note}
+
+Extended expression markup was introduced in EmPy version 3.0, and was
+expanded to support if-else chaining in 4.0.
+
+:::
+
+
+### In-place expression markup: `@$...$...$`
+
+Occasionally it's desirable to designate an expression that will be
+evaluated alongside its evaluation which may change, but which will be
+re-evaluated with subsequent updates, or identify exactly what is
+being evaluated at the same time. This is similar to the notion of
+CVS or SVN keywords such as `$Date ...$`. For this, there is
+**in-place expression markup** (`@$...$...$`). They consist of two
+segments: first, the Python (not EmPy) expression to evaluate, and the
+second, the result of that evaluation. When evaluating the markup,
+the second (result) section is ignored and replaced with the
+evaluation of the first and a new in-place markup is rendered. For
+example:
+
+:::{admonition} Example 25: In-place expressions
+
+
+_Source_:
+``````
+This could be a code comment indicating the version of EmPy:
+# @$empy.version$this text is replaced with the result$
+Arbitrary Python expressions can be evaluated:
+# @$__import__('time').asctime()$$
+``````
+
+_Output_:
+``````
+This could be a code comment indicating the version of EmPy:
+# @$empy.version$4.0.1$
+Arbitrary Python expressions can be evaluated:
+# @$__import__('time').asctime()$Sun Dec 24 17:05:00 2023$
+``````
+:::
+
+
+:::{note}
+
+The `$` character is a common choice for an alternate prefix. If it
+is chosen instead of the default `@`, the in-place expression markup
+will be remapped to have the form `$@...@...@`; that is, the `@`
+and `$` are swapped. (This is done automatically for any prefix
+collision with a markup indicator.)
+
+:::
+
+:::{note}
+
+In-place markup was introduced in EmPy version 1.4.
+
+:::
+
+
+### Statement markup: `@{...}`
+
+Again, EmPy mainly processes markups by evaluating expressions and
+executing statements. Statements include assignments, control
+structures (`if`, `for`, function and class definitions, etc.)
+Statements do not yield a value; they are used for side effects,
+whether that's changing the state of the interpreter (setting or
+changing variables, defining objects, calling functions, etc.) or
+printing output. Statements can also consist of expressions, so an
+expression (such as `print("Hello, world!")`) can be used solely for
+its side effects with the statement markup. **Statement markup** sets
+off a series of statements to be executed inside the `@{...}`
+markup. Since statements do not yield a value, they are executed but
+the markup itself does not implicitly write anything. Since the
+executed statements are Python, multiline statements must be formatted
+and indented according to Python's parsing rules:
+
+:::{admonition} Example 26: Statements
+
+
+_Source_:
+``````
+@# Note the use of whitespace markup below to consume trailing newlines.
+@{x = 16309}@
+x is now @x.
+@{
+if x > 0:
+ category = 'positive'
+else:
+ category = 'non-positive'
+}@
+x is @category.
+@{
+# Since statement markup does not write anything itself, this
+# statement has no effect.
+x + 123
+}@
+``````
+
+_Output_:
+``````
+x is now 16309.
+x is positive.
+``````
+:::
+
+
+:::{attention}
+
+Note that when markup which has starting and ending delimiters appears
+alone on a line, the trailing newline will be rendered in the output.
+To avoid these extra newlines, use a trailing `@` to turn it into
+whitespace markup which consumes that trailing newline, so _e.g._
+`@{...}` followed by a newline becomes `@{...}@` followed by a
+newline. This is idiomatic for suppressing unwanted newlines. See
+[here](#idiom) for more details.
+
+:::
+
+:::{note}
+
+Simple expression markup was introduced in EmPy version 1.0.
+
+:::
+
+
+### Control markup: `@[...]`
+
+EmPy supports a variety of control structures, analogous to the
+builtin Python control structures (`if`, `while`, `for`, etc.), with
+some additional markups for convenience. This is done with **control
+markup** indicated by `@[...]`.
+
+Since EmPy cannot rely on source indentation to delimit control
+structure syntax, all primary control markups must end with an
+explicit `end` markup (_e.g._, `@[if ...]...@[end if]`). The clauses
+surrounded by control markup are EmPy (Python) markup and are expanded
+according to the logic of each control markup; see below.
+
+Unlike the Python control structures, the code that is expanded within
+each subclause is EmPy code, not Python code. Thus, control markups
+can be nested arbitrarily (_e.g._, `@[while ...]@[for ...]@[if ...]...@[end
+if]@[end for]@[end while]`).
+
+::::{attention}
+
+To use nested control markup that spans multiple lines and is more
+readable, you can rely on whitespace markup to consume the newline
+immediately following the control markup. As an example:
+
+:::{admonition} Example 27: Controls, idiom
+
+
+_Source_:
+``````
+@# Note the user of whitespace markup to consume the trailing newlines.
+Counting:
+@[for i, x in enumerate(range(0, 5))]@
+@x is @
+@[ if x % 2 == 0]@
+even@
+@[ else]@
+odd@
+@[ end if]@
+.
+@[end for]@
+``````
+
+_Output_:
+``````
+Counting:
+0 is even.
+1 is odd.
+2 is even.
+3 is odd.
+4 is even.
+``````
+:::
+
+
+This method of writing organizing control markup with `@[...]@` all
+on a single line for clarity is idiomatic EmPy. (This applies to all
+markup with starting and ending delimiters.) See [here](#idiom) for
+more details.
+
+::::
+
+:::{hint}
+
+Whitespace before the control keyword is ignored, so you can add
+whitespace inside the markup to simulate Python indentation for
+clarity, as the above example demonstrates.
+
+:::
+
+:::{tip}
+
+Simple ("clean") control markup which does not contain arbitrary
+Python expressions -- `@[try]`, `@[else]`, `@[except ...]`,
+`@[finally]`, `@[continue]`, `@[break]` and `@[end ...]` -- can
+include a Python-style comment for clarity:
+
+``````
+@[if test condition]@
+... many lines of EmPy code here ...
+... imagine this was so long that the context could be confusing ...
+... so as a reminder of which `if` control is being ended:
+@[end if # test condition]@
+``````
+
+
+:::
+
+:::{note}
+
+Control markups were introduced in EmPy version 3.0 unless otherwise
+noted below.
+
+:::
+
+
+#### If control markup: `@[if E]...@[end if]`
+
+The simplest control markup is the **if control markup**. It
+precisely mimics the Python `if` branching control structure. The
+test expressions are Python expressions. Like the native Python
+control structure, it takes on the following forms:
+
+- `@[if E]...@[end if]`
+- `@[if E]...@[else]...@[end if]`
+- `@[if E]...@[elif E2]...@[end if]`
+- `@[if E]...@[elif E2]...@[else]...@[end if]`
+- `@[if E]...@[elif E2]... ... @[else]...@[end if]`
+
+Thus, as with the builtin Python `if` control structure, zero or more
+`@[elif]` clauses can be used and the `@[else]` clause (only valid
+at the end of the chain) is optional. If there is no `@[else]`
+clause and all the test expressions are false, nothing will be
+expanded.
+
+:::{admonition} Example 28: If controls
+
+
+_Source_:
+``````
+@{
+def even(x):
+ return x % 2 == 0
+}@
+0 is @[if even(0)]even@[end if].
+1 is @[if even(1)]even@[else]odd@[end if].
+2 is @[if even(2)]even@[else]odd@[end if].
+3 is @[if even(3)]even@[elif not even(3)]not even@[end if].
+4 is @[if 0 == 1]wrong@[elif 1 == 2]wrong@[else]fine@[end if].
+``````
+
+_Output_:
+``````
+0 is even.
+1 is odd.
+2 is even.
+3 is not even.
+4 is fine.
+``````
+:::
+
+
+
+##### Break and continue control markup: `@[break]`, `@[continue]`
+
+The looping control markup structures below (`@[for]`, `@[while]`,
+and `@[dowhile]`) all support **break** and **continue control
+markup**. These markups follow the native Python forms; `@[break]`
+will exit out of the innermost looping control structure, and
+`@[continue]` will restart the innermost looping control structure.
+
+They take the following forms:
+
+- `@[break]`
+- `@[continue]`
+
+The following is an example using a `@[while]` loop:
+
+:::{admonition} Example 29: Continue controls
+
+
+_Source_:
+``````
+@# Print even numbers.
+@[for n in range(10)]@
+@[ if n % 2 != 0]@
+@[ continue]@
+@[ end if]@
+@n is even.
+@[end for]@
+``````
+
+_Output_:
+``````
+0 is even.
+2 is even.
+4 is even.
+6 is even.
+8 is even.
+``````
+:::
+
+
+:::{admonition} Example 30: Break controls
+
+
+_Source_:
+``````
+@# Print numbers up to (but not including) 5.
+@[for n in range(10)]@
+@[ if n >= 5]@
+@[ break]@
+@[ end if]@
+@n is less than 5.
+@[end for]@
+``````
+
+_Output_:
+``````
+0 is less than 5.
+1 is less than 5.
+2 is less than 5.
+3 is less than 5.
+4 is less than 5.
+``````
+:::
+
+
+
+#### For control markup: `@[for N in E]...@[end for]`
+
+A basic iteration markup is the **for control markup**. It precisely
+mimics the Python `for` looping control structure. The iterator
+expression is a Python expression. Like the native Python control
+structure, it takes on the following forms:
+
+- `@[for N in E]...@[end for]`
+- `@[for N in E]...@[else]...@[end for]`
+
+As with the native Python control structure, an `@[else]` clause is
+supported; this is expanded if the loop exits without an intervening
+break.
+
+:::{admonition} Example 31: For controls
+
+
+_Source_:
+``````
+@[for x in range(1, 6)]@
+@x squared is @(x*x).
+@[else]@
+... and done.
+@[end for]@
+``````
+
+_Output_:
+``````
+1 squared is 1.
+2 squared is 4.
+3 squared is 9.
+4 squared is 16.
+5 squared is 25.
+... and done.
+``````
+:::
+
+
+
+#### While control markup: `@[while E]...@[end while]`
+
+The most general looping markup is the **while control markup**. It
+precisely mimics the Python `while` looping control structure. The
+test expression is a python expression. Like the native Python
+control structure, it takes on the following forms:
+
+- `@[while E]...@[end while]`
+- `@[while E]...@[else]...@[end while]`
+
+As with the native Python control structure, an `@[else]` clause is
+supported; this is invoked if the loop exits without an intervening
+break.
+
+:::{admonition} Example 32: While controls
+
+
+_Source_:
+``````
+@{a = 1}@
+@[while a <= 5]@
+@a pound signs: @('#'*a).
+@{a += 1}@
+@[else]@
+... and done.
+@[end while]@
+``````
+
+_Output_:
+``````
+1 pound signs: #.
+2 pound signs: ##.
+3 pound signs: ###.
+4 pound signs: ####.
+5 pound signs: #####.
+... and done.
+``````
+:::
+
+
+
+#### Dowhile control markup: `@[dowhile E]...@[end dowhile]`
+
+An alternate `while` control structure is provided by EmPy: **dowhile
+control markup**. This differs from the standard `while` markup only
+in that the loop is always entered at least once; that is, the test
+expression is not checked before the first iteration. In this way, it
+is similar to the `do ... while` control structure from C/C++. It
+takes the following forms:
+
+- `@[dowhile E]...@[end dowhile]`
+- `@[dowhile E]...@[else]...@[end dowhile]`
+
+Like the native Python `while` control structure, an `@[else]` clause
+is supported; this is invoked if the loop exits without an intervening
+break.
+
+:::{admonition} Example 33: Dowhile controls
+
+
+_Source_:
+``````
+@# Stop when divisible by 5, but include 0 since it's the first iteration:
+@{n = 0}@
+@[dowhile n % 5 != 0]@
+@n works@[if n % 5 == 0] (even though it's divisible by 5)@[end if].
+@{n += 1}@
+@[else]@
+... and done.
+@[end dowhile]@
+``````
+
+_Output_:
+``````
+0 works (even though it's divisible by 5).
+1 works.
+2 works.
+3 works.
+4 works.
+... and done.
+``````
+:::
+
+
+:::{note}
+
+Dowhile control markup was introduced in EmPy version 4.0.
+
+:::
+
+
+#### Try control markup: `@[try]...@[end try]`
+
+**Try control markup** is the EmPy equivalent of a `try` statement.
+As with the native Python statement, this markup can take on the
+widest variety of forms. They are:
+
+- `@[try]...@[except]...@[end try]`
+- `@[try]...@[except C]...@[end try]`
+- `@[try]...@[except C as N]...@[end try]`
+- `@[try]...@[except C, N]...@[end try]`
+- `@[try]...@[except (C1, C2, ...) as N]...@[end try]`
+- `@[try]...@[except C1]...@[except C2]...@[end try]`
+- `@[try]...@[except C1]...@[except C2]... ... @[end try]`
+- `@[try]...@[finally]...@[end try]`
+- `@[try]...@[except ...]...@[finally]...@[end try]`
+- `@[try]...@[except ...]...@[else]...@[end try]`
+- `@[try]...@[except ...]...@[else]...@[finally]...@[end try]`
+
+Its behavior mirrors in every way the native Python `try` statement.
+The try clause will be expanded, and if an exception is thrown, the
+first `@[except]` clause that matches the thrown exception (if there
+are any) will be expanded. If a `@[finally]` clause is present, that
+will be expanded after any possible exception handling, regardless of
+whether an exception was in fact thrown. Finally, if there is at
+least one `@[except]` clause, an `@[else]` may be present which will
+be expanded in the event that no exception is thrown (but before any
+`@[finally]` clause).
+
+The argument to the `@[except]` markup indicates which type(s) of
+exception should be handled and with what name, if any. No argument
+indicates that it will handle any exception. A simple expression will
+indicate an exception class, or a tuple of exception classes, that
+will be handled. The variable name of the thrown exception can be
+captured and passed to the expansion with the `as` keyword, or a comma
+(this latter notation is invalid in modern Python versions but is
+still supported in EmPy regardless of the underlying Python version).
+
+For example:
+
+:::{admonition} Example 34: Try controls
+
+
+_Source_:
+``````
+Garbage is @[try]@hugalugah@[except NameError]not defined@[end try].
+Division by zero is @[try]@(1/0)@[except ZeroDivisionError]illegal@[end try].
+An index error is @[try]@([][3])@[except IndexError as e]@e.__class__.__name__@[end try].
+And finally: @[try]@(nonexistent)@[except]oops, @[finally]something happened@[end try].
+``````
+
+_Output_:
+``````
+Garbage is not defined.
+Division by zero is illegal.
+An index error is IndexError.
+And finally: oops, something happened.
+``````
+:::
+
+
+:::{note}
+
+Try control markup was introduced in EmPy version 3.0, and was
+expanded in 4.0 to include all modern valid uses of `@[else]` and
+`@[finally]`.
+
+:::
+
+
+#### With control markup: `@[with E as N]...@[end with]`
+
+EmPy supports a version of the `with` statement, which was introduced
+in Python 2.5. In EmPy, the **with control markup** is written as
+`@[with]` and mirrors the behavior of the native `with` statement.
+It takes the following forms:
+
+- `@[with E as N]...@[end with]`
+- `@[with N]...@[end with]`
+- `@[with E]...@[end with]`
+
+All forms use context managers, just as with the native statement.
+Context managers are objects which have `__enter__` and `__exit__`
+methods, and the `@[with]` markup ensures that the former is called
+before the markup's contents are expanded and that the latter is
+always called afterward, whether or not an exception has been thrown.
+
+The three forms of the `@[with]` markup mirror the uses of the `with`
+keyword: The user can specify an expression and a variable name with
+the `as` keyword, or just a variable name, or just an expression (it
+will be entered and exited, but the name of the resulting object will
+not be available). For example:
+
+:::{admonition} Example 35: With controls
+
+
+_Source_:
+``````
+@{
+import os, sys
+
+with open('/tmp/with.txt', 'w') as f:
+ print("Hello, world!", file=f)
+}@
+@[with open('/tmp/with.txt') as f]@f.read()@[end with]@
+``````
+
+_Output_:
+``````
+Hello, world!
+``````
+:::
+
+
+:::{note}
+
+Although the `with` keyword was only introduced in Python 2.5, the
+`@[with]` markup will work in any supported version of Python.
+
+:::
+
+:::{note}
+
+With control markup was introduced in EmPy version 4.0.
+
+:::
+
+#### Defined control markup: `@[defined N]...@[end defined]`
+
+Sometimes it's useful to know whether a name is defined in either the
+locals or globals dictionaries. EmPy provides a dedicated markup for
+this purpose: **defined control markup**. It takes the following
+forms:
+
+- `@[defined N]...@[end defined]`
+- `@[defined N]...@[else]...@[end defined]`
+
+When provided a name, it will expand the contained markup if that name
+is defined in either the locals or globals. `@[defined NAME]...@[end
+defined]` is equivalent to `@[if 'NAME' in globals() or 'NAME' in
+locals()]...@[end if]`. An `@[else]` clause is also supported; if
+present, this will be expanded if the name does _not_ appear in the
+locals or globals. If no `@[else]` clause is present and the name is
+not defined, nothing will be expanded.
+
+:::{admonition} Example 36: Defined controls
+
+
+_Source_:
+``````
+@{cat = 'Boots'}@
+Cat is @[defined cat]@cat@[else]not defined@[end defined].
+Dog is @[defined dog]@dog@[else]not defined@[end defined].
+``````
+
+_Output_:
+``````
+Cat is Boots.
+Dog is not defined.
+``````
+:::
+
+
+:::{note}
+
+Defined control markup was introduced in EmPy version 4.0.
+
+:::
+
+#### Def control markup: `@[def F(...)]...@[end def]`
+
+EmPy supports defining functions which expand EmPy code, not Python
+code as with the standard `def` Python statement. This is called
+**def control markup**. It takes on the following form:
+
+- `@[def F(...)]...@[end def]`
+
+Def control markup involves specifying the signature of the resulting
+function (such as with the standard Python `def` statement) and
+encloses the EmPy code that the function should expand. It is then
+defined in the interpreter's globals/locals and can be called like any
+other Python function.
+
+It is best demonstrated with a simple example:
+
+:::{admonition} Example 37: Def controls
+
+
+_Source_:
+``````
+@# Define an EmPy-native function.
+@[def element(name, symbol, atomicNumber, group)]@
+Element @name (symbol @symbol, atomic number @atomicNumber) is a @group@
+@[end def]@
+@# Now use it.
+@element('hydrogen', 'H', 1, 'reactive nonmetal').
+@element('helium', 'He', 2, 'noble gas').
+@element('lithium', 'Li', 3, 'alkali metal').
+@element('beryllium', 'Be', 4, 'alkaline earth metal').
+@element('boron', 'B', 5, 'metalloid').
+@element('carbon', 'C', 6, 'reactive nonmetal').
+``````
+
+_Output_:
+``````
+Element hydrogen (symbol H, atomic number 1) is a reactive nonmetal.
+Element helium (symbol He, atomic number 2) is a noble gas.
+Element lithium (symbol Li, atomic number 3) is a alkali metal.
+Element beryllium (symbol Be, atomic number 4) is a alkaline earth metal.
+Element boron (symbol B, atomic number 5) is a metalloid.
+Element carbon (symbol C, atomic number 6) is a reactive nonmetal.
+``````
+:::
+
+
+:::{hint}
+
+The markup `@[def FUNC(...)]DEFN@[end def]` is equivalent to the
+following Python code:
+
+```python
+def FUNC(...):
+ r"""DEFN"""
+ return empy.expand(r"""DEFN""", locals())
+```
+
+It simply defines a Python function with the provided signature, a
+docstring indicating its EmPy definition, and the function calls the
+`expand` method on the pseudomodule/interpreter with the definition
+and returns the results.
+
+:::
+
+:::{tip}
+
+Functions defined with def control markup are callable Python objects
+like any other. They can be called through any mechanism, whether
+Python (`f(...)`), through EmPy markup (`@f(...)`), or even via
+[functional expression markup](#functional-expression-markup)
+(`@f{...}`).
+
+:::
+
+
+### Diacritic markup: `@^ CHAR DIACRITIC(S)`
+
+EmPy provides a quick and convenient way to combine diacritics
+(accents) to characters with **diacritic markup**. Diacritic markup
+consists of the prefix `@^`, followed by the base character, and then
+either a single character representing the accent to apply or a
+sequence of such characters enclosed in curly braces (`{...}`).
+
+The first character is the base character to combine diacritics with,
+and the remaining characters (possibly more than one if the curly
+braces form is used) are diacritic codes corresponding to Unicode
+combining characters that can be combined (or just appended) to the
+base character. These combining diacritics are simpler, more easily
+entered characters that (at least in some cases) resemble the actual
+desired combining character. For instance, `'` (apostrophe)
+represents the acute accent ◌́; `` ` `` (backquote) represents the grave accent ◌̀; `^` represents the circumflex
+accent ◌̂, and so on:
+
+:::{admonition} Example 38: Diacritics
+
+
+_Source_:
+``````
+French: Voil@^a`, c'est ici que @^c,a s'arr@^e^te.
+Spanish: Necesito ir al ba@^n~o ahora mismo.
+Portuguese: Informa@^c,@^a~o @^e' poder.
+Swedish: Hur m@^aonga kockar kr@^a:vs f@^o:r att koka vatten?
+Vietnamese: Ph@^o{h?} b@^o` vi@^e^n ngon qu@^a'!
+Esperanto: E@^h^o@^s^an@^g^e @^c^iu@^j^a@^u(de!
+Shakespearean: All are punish@^e`d.
+``````
+
+_Output_:
+``````
+French: Voilà, c'est ici que ça s'arrête.
+Spanish: Necesito ir al baño ahora mismo.
+Portuguese: Informação é poder.
+Swedish: Hur många kockar krävs för att koka vatten?
+Vietnamese: Phở bò viên ngon quá!
+Esperanto: Eĥoŝanĝe ĉiuĵaŭde!
+Shakespearean: All are punishèd.
+``````
+:::
+
+
+:::{tip}
+
+Curly braces can enclose zero or more characters representing
+diacritics. If they enclose zero, the diacritic markup has no effect
+(`@^e{}` is no different from `e`). If they enclose one, the results
+are no different from not using curly braces (`@^e{'}` and `@^e'`
+are have identical results). Only for applying more than one
+diacritic are curly braces required.
+
+:::
+
+By default, the base character and diacritics will be combined with
+NFKC normalization -- this will, when possible, replace the base
+character and its combiners with a single Unicode character
+representing the combination, if one exists. Normalization is not
+required (and may sometimes fail when a suitable combined form does
+not exist); in these cases, your system's Unicode renderer will cope
+as best it can. To change the normalization type, use
+`-z`/`--normalization-form=F` (_configuration variable:_ `normalizationForm`). To disable normalization,
+set it to the empty string.
+
+The dictionary mapping all diacritic codes to combining characters is
+stored in the `diacritics` configuration variable.
+This can be modified or completely replaced as desired. The values
+can be integers (Unicode code point values), lists of integers, or
+strings. They can also take the form of a 2-tuple, where the first
+element is one of the above values and the second element is a
+description string used for displaying in help topics.
+
+:::{seealso}
+
+The list of all default diacritic codes is available in the
+`diacritics` help topic and is summarized
+[here](http://www.alcyone.com/software/empy/HELP.em#diacritics-combiners-summary).
+
+:::
+
+:::{note}
+
+Diacritic markup was introduced in EmPy version 4.0.
+
+:::
+
+
+### Icon markup: `@|...`
+
+A customizable brief way to map "icon" keys -- short, user-specified
+strings -- to arbitrary Unicode strings exists in the form of **icon
+markup**. Icon markup is set off with `@|...` and then followed by
+an unambiguous, arbitrary-length sequence of characters (Unicode code
+points) corresponding to one of its keys.
+
+The icon keys can be any set of distinct strings, and are specified in
+the `icons` configuration variable whose keys are the
+string keys as used in the markup, as well as all possible key
+prefixes (more on this in a bit). The values can be integers (Unicode
+code point values), lists of integers, or strings. They can also take
+the form of a 2-tuple, where the first element is one of the above
+values and the second element is a description string used for
+displaying in help topics. An (arbitrary) default set are provided by
+default, but these can be modified or completely replaced as desired.
+
+Keys can be arbitrary length and can consist of whatever characters
+are desired (including letters, numbers, punctuation, or even Unicode
+characters). They are not delimited by whitespace; however, they must
+be unambiguous, so if more than one key exists with the same prefixes
+(say, `#+` and `#-`), a key cannot be defined as the common prefix
+(`#`) as this would be found first and would hide the longer prefixes.
+Such a common prefix key should be set to the value `None` (which
+indicates to the parser that the icon is potentially valid but not yet
+complete).
+
+This validation is done automatically when the icon markup is first
+used: The dictionary of icons is traversed and any common prefixes not
+defined in the dictionary are set to `None`. In the event that this
+auto-validation may be expensive and the user wishes to do it manually
+to avoid this step, specify the `--no-auto-validate-icons`
+command line options to disable it.
+
+:::{admonition} Example 39: Icons
+
+
+_Source_:
+``````
+These are @|"(curly quotes.@|")
+This is a royal flush: A@|%s K@|%s Q@|%s J@|%s T@|%s.
+This is a check mark @|/ and this is an X mark @|\.
+Smile! @|:) Laugh! @|:9 Cry! @|:5 Sleep! @|:Z
+``````
+
+_Output_:
+``````
+These are “curly quotes.”
+This is a royal flush: A♠️ K♠️ Q♠️ J♠️ T♠️.
+This is a check mark ✔️ and this is an X mark ❌️.
+Smile! 😀 Laugh! 🤣 Cry! 🥲 Sleep! 😴
+``````
+:::
+
+
+To customize icons, modify or replace the `icons`
+configuration variable:
+
+:::{admonition} Example 40: Icons, customization
+
+
+_Source_:
+``````
+@# Replace the icons with just a few very serious ones.
+@{
+empy.config.icons = {
+ 'kitty': '\U0001f431',
+ 'cat': '\U0001f408',
+}
+}@
+Counting: one two @|kitty @|cat five.
+``````
+
+_Output_:
+``````
+Counting: one two 🐱 🐈 five.
+``````
+:::
+
+
+:::{tip}
+
+If you're finding problems with icons being ambiguous, you can add
+delimiters at the end of the icon key to ensure that they are
+unambiguous. For example, the icons `!`, `!!` and `!?` would normally
+be ambiguous. However, wrapping them in, say, curly braces, will
+remove the ambiguity: `{!}`, `{!!}`, `{!?}` are unambiguous and can be
+used as icon keys.
+
+:::
+
+:::{seealso}
+
+The list of all valid icon keys is available in the `icons` help topic
+and is summarized [here](http://www.alcyone.com/software/empy/HELP.html#icons-summary).
+
+:::
+
+:::{note}
+
+The default set of icons were chosen by the author for his convenience
+and to demonstrate what icon markup can do. It is expected that users
+using icon markup will modify/replace the icons dictionary.
+
+:::
+
+:::{note}
+
+Icon markup was introduced in EmPy version 4.0.
+
+:::
+
+
+### Emoji markup: `@:...:`
+
+A dedicated **emoji markup** is available to translate Unicode emoji
+names, and Unicode names more generally, into Unicode glyphs. Using
+the markup is simple: Use the `@:...:` syntax and put the name of the
+emoji character between the colons. Since EmPy is often used in
+wrapped text, any newlines in the emoji name will be replaced with
+spaces.
+
+By default it uses the builtin `unicodedata.lookup` function call
+which allow the lookup of any Unicode code point by name, not just
+emoji. Whether names are case sensitive or not, or whether words are
+separated by spaces or underscores or either, is module-dependent.
+The builtin `unicodedata` module (the fallback if no emoji-specific
+modules are installed) is case insensitive and requires spaces, not
+underscores:
+
+:::{admonition} Example 41: Emojis
+
+
+_Source_:
+``````
+Latin capital letter A: @:LATIN CAPITAL LETTER A:
+Latin small letter O with diaeresis: @:latin small letter o with diaeresis:
+White heavy check mark: @:WHITE HEAVY CHECK MARK:
+Volcano: @:VOLCANO:
+``````
+
+_Output_:
+``````
+Latin capital letter A: A
+Latin small letter O with diaeresis: ö
+White heavy check mark: ✅
+Volcano: 🌋
+``````
+:::
+
+
+User-specified emoji can also be assigned to the configuration's
+`emojis` dictionary variable; this will be checked
+before any emoji modules are queried. The values of this dictionary
+can be any string, not necessarily just a single character. Emojis
+in the `emojis` dictionary are case sensitive:
+
+:::{admonition} Example 42: Emojis, custom
+
+
+_Source_:
+``````
+@# What's with this guy and cats?
+@{
+empy.config.emojis['kittycat'] = '\U0001f408'
+}@
+This is a kitty cat: @:kittycat:
+``````
+
+_Output_:
+``````
+This is a kitty cat: 🐈
+``````
+:::
+
+
+{#third-party-emoji-modules}
+The emoji markup can also use third-party emoji modules if they are
+present. These can be installed in the usual way with PyPI (e.g.,
+`python3 -m pip install emoji`) or any other preferred method. The
+following emoji modules are supported:
+
+| Module | Function | Parameter | Capitalization | Spaces or underscores |
+| --- | --- | --- | --- | --- |
+| `emoji` | `emojize` | `':%s:'` | lowercase | underscores |
+| `emojis` | `encode` | `':%s:'` | lowercase | underscores |
+| `emoji_data_python` | `replace_colons` | `':%s:'` | lowercase | underscores |
+| `unicodedata` | `lookup` | `'%s'` | both | spaces |
+
+On first usage, each module is checked to see if it is present and is
+then registered in the order listed above. When a lookup on a name is
+performed, each module which is present is queried in order, and if it
+finds the given name, that is used as output. If no modules find the
+name, by default an error is generated, but this behavior can be
+changed with the `--ignore-emoji-not-found` command line
+option.
+
+The order in which modules are queried is also customizable with the
+`--emoji-modules` command line option; specify the
+sequence of emoji module names to test separated by commas. Use the
+`--no-emoji-modules` command line option to only enable
+the builtin `unicodedata` module lookup, deactivating the use of any
+custom modules which may be installed. And use
+`--disable-emoji-modules` to disable all emoji module
+lookup; only the `emojis` configuration variable will be consulted.
+
+If you're aware of other third-party emoji modules you'd like to see
+supported, [contact the author](#contact).
+
+:::{tip}
+
+It's expected that the typical EmPy user will have at most one
+third-party module installed, so no effort has been put in place to
+avoid conflicts or redundancies regarding emoji names between them
+other than specifying this desired lookup order. Choose a third-party
+module that works for you, or just rely on the builtin `unicodedata`
+lookup table.
+
+If you're relying on a third-party module to be present, you might
+want to have your EmPy code explicitly import that module so that if
+it's missing, the dependency will be more clear.
+
+:::
+
+:::{attention}
+
+Note that when markup which has starting and ending delimiters appears
+alone on a line, the trailing newline will be rendered in the output.
+To avoid these extra newlines, use a trailing `@` to turn it into
+whitespace markup which consumes that trailing newline, so _e.g._
+`@{...}` followed by a newline becomes `@{...}@` followed by a
+newline. This is idiomatic for suppressing unwanted newlines. See
+[here](#idiom) for more details.
+
+:::
+
+:::{note}
+
+Emoji markup was introduced in EmPy version 4.0.
+
+:::
+
+
+### Significator markup: `@%[!]... NL`, `@%%[!]...%% NL`
+
+**Significators** are ways to perform distinctive assignments within
+an EmPy system which are easily parsed externally; for instance, for
+specifying metadata for an EmPy source document. In its simplest
+form, it defines in a variable in the globals with the evaluation of a
+Python value. The significator `@%KEY VALUE` is equivalent to the
+Python assignment statement `__KEY__ = VALUE`.
+
+The name of the assigned variable is preceded and ended with a double
+underscore (`__`). (This behavior can be changed with
+configurations.) Note that the value assigned can be any Python
+expression, not just a string literal:
+
+:::{admonition} Example 43: Significators, basics
+
+
+_Source_:
+``````
+@%title "A Tale of Two Cities"
+@%author 'Charles Dickens'
+@%year 1859
+@%version '.'.join([str(x) for x in __import__('sys').version_info[0:2]])
+The book is _@(__title__)_ (@__year__) by @__author__.
+This version of Python is @__version__.
+``````
+
+_Output_:
+``````
+The book is _A Tale of Two Cities_ (1859) by Charles Dickens.
+This version of Python is 3.10.
+``````
+:::
+
+
+Whitespace is allowed between the `@%` markup introducer and the key,
+and any (non-newline) whitespace is allowed between the key and the
+value. The ending newline is always consumed.
+
+A variant of significator markup can span multiple lines. Instead of
+using `@%` and a newline to delimit the significator, use `@%%` and
+`%%` followed by a newline:
+
+:::{admonition} Example 44: Significators, multiline
+
+
+_Source_:
+``````
+@%%longName "This is a potentially very long \
+name which can span multiple lines." %%
+@%%longerName """This is a triple quoted string
+which itself contains newlines. Note the newlines
+are preserved.""" %%
+@%%longExpression [[1, 2, 3],
+[4, 5, 6],
+[7, 8, 9]] %%
+Long name: @__longName__
+Longer name: @__longerName__
+Long expression: @__longExpression__
+``````
+
+_Output_:
+``````
+Long name: This is a potentially very long name which can span multiple lines.
+Longer name: This is a triple quoted string
+which itself contains newlines. Note the newlines
+are preserved.
+Long expression: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+``````
+:::
+
+
+::::{note}
+
+When using multiline significators, the value must still be a valid
+Python expression. So the significator
+
+``````
+@%%bad 1 + 2 + 3 +
+4 + 5 + 6 %%
+``````
+
+
+is a syntax error due to the intervening newline. To correct this,
+use a backslash character (`\`) to escape the newline or enclose the
+value expression in parentheses:
+
+``````
+@%%good1 1 + 2 + 3 + \
+4 + 5 + 6 %%
+@%%good2 (1 + 2 + 3 +
+4 + 5 + 6) %%
+``````
+
+
+::::
+
+Two more subvariants of significator markup exists, one for each of
+these two variants. Frequently significator values will just be
+string literals and for uniformity users may wish to not deal with
+full Python expressions. For these purposes, significator values can
+be **stringized**, or treated merely as strings with no Python
+evaluation. Simply insert a `!` after the `@%` or `@%%` markup
+introducer and before the name of the key:
+
+:::{admonition} Example 45: Significators, stringized
+
+
+_Source_:
+``````
+@# These values are all implicit strings.
+@%!single This is on a single line.
+@%%!multi This is on
+multiple lines. %%
+Single line: @__single__
+Multiple lines: @__multi__
+``````
+
+_Output_:
+``````
+Single line: This is on a single line.
+Multiple lines: This is on
+multiple lines.
+``````
+:::
+
+
+Finally, the values for both single and multiline significator markups
+are optional. If the markup is not stringized, the value will be
+`None`; if stringized, it will be the empty string (`''`):
+
+:::{admonition} Example 46: Significators, optional values
+
+
+_Source_:
+``````
+@%none
+@%!empty
+This is a None: @repr(__none__).
+This is an empty string: @repr(__empty__).
+``````
+
+_Output_:
+``````
+This is a None: None.
+This is an empty string: ''.
+``````
+:::
+
+
+:::{hint}
+
+Significators can appear anywhere in an EmPy document, but typically
+are used at the beginning.
+
+:::
+
+:::{tip}
+
+A compiled regular expression object is returned by the
+`significatorRe` configuration method and can be used to
+systematically find all the significators in a given text.
+
+The values of a non-stringinized significators can be any Python
+expression, so can include side effects from prior EmPy expansions.
+It's best practice, however, to only have significator values depend
+on the value of previous significators, so that trimmed down
+processors can evaluate them without having to expand the entire
+document.
+
+:::
+
+:::{note}
+
+Significator markup was introduced in EmPy version 1.2. Stringified
+and multi-multiline variants were introduced in version 4.0.
+
+:::
+
+
+### Context markup
+
+Contexts are objects which track the current progress of an EmPy
+interpreter through its source document(s) for the purposes of error
+reporting. This is handled automatically by the EmPy system, but they
+can be modified through the API or with context markup.
+
+:::{note}
+
+Context markups were introduced in EmPy version 3.0.2.
+
+:::
+
+#### Context name markup: `@?... NL`
+
+The **context name markup** can be used to change the current context
+name with `@?... NL`; it uses as the new name what follows on the
+same line and consumes everything up to and including the newline.
+Whitespace surrounding the context name is ignored.
+
+:::{admonition} Example 47: Context names
+
+
+_Source_:
+``````
+@?Test
+This context is now: @empy.getContext().
+``````
+
+_Output_:
+``````
+This context is now: Test:2:22.
+``````
+:::
+
+
+
+#### Context line markup: `@!... NL`
+
+The **context line markup** can be used to change the current context
+line with `@!... NL`; it uses as the new line what follows on the
+same line and consumes everything up to and including the newline.
+Whitespace surrounding the context name is ignored. If the remaining
+text is not parseable as an integer, it is a parse error.
+
+:::{admonition} Example 48: Context lines
+
+
+_Source_:
+``````
+@!1000
+This context is now: @empy.getContext().
+Note that the line is 1001 since it's the next line after the markup.
+``````
+
+_Output_:
+``````
+This context is now: <example 48>:1001:22.
+Note that the line is 1001 since it's the next line after the markup.
+``````
+:::
+
+
+
+### Custom markup: `@<...>`
+
+**Custom markup** is reserved for user-defined use. Unlike the other
+markups, this markup has no specified meaning on its own, and must be
+provided a meaning by the user. This meaning is provided with the use
+of a Python callable object referred to as a **custom callback**, or
+just "callback," which can be set, queried, or reset using
+pseudomodule functions. At most one custom callback can be registered
+at a time.
+
+When the custom markup `@<...>` is encountered, the contents inside
+the markup are passed to the current custom callback. Its return
+value, if not `None`, is then written to the output stream. The
+custom callback may also perform operations with side effects
+resulting in output, as well. If there are multiple opening angle
+brackets, an equal number of closing angle brackets will be required
+to match. This allows the embedding of `<` and `>` in the contents
+passed to the callback.
+
+The custom callback is a callable object which, when invoked, is
+passed a single argument: a string representing the contents of what
+was found inside the custom markup `@<...>`. Only one custom
+callback can be registered at a time.
+
+To register a callback, call `empy.registerCallback`. To remove it,
+call `empy.deregisterCallback`. To see if there is a callback
+registered, use `empy.hasCallback`. To retrieve the callback (if any)
+registered with the interpreter, use `empy.getCallback`. Finally, to
+invoke the callback explicitly just as if the custom markup had been
+encountered, call `empy.invokeCallback`. For instance, `@<This
+text>` would be equivalent to the call `@empy.invokeCallback("This
+text")`.
+
+By default, to invoke a callback (either explicitly with
+`empy.invokeCallback` or by processing a `@<...>` custom markup) when
+no callback has been registered is an error. This behavior can be
+changed with the `--no-callback-error` option; this
+makes the use of the custom markup with no registered callback to
+no-op.
+
+:::{admonition} Example 49: Custom markup
+
+
+_Source_:
+``````
+@{
+def callback(contents):
+ return contents.upper()
+empy.registerCallback(callback)
+}@
+This will be in uppercase: @<This is a test>.
+This will also contain angle brackets: @<<This is <also a> test>>.
+``````
+
+_Output_:
+``````
+This will be in uppercase: THIS IS A TEST.
+This will also contain angle brackets: THIS IS <ALSO A> TEST.
+``````
+:::
+
+
+:::{tip}
+
+It's typical to want to have an instance of the
+interpreter/pseudomodule available to the callback, but it is neither
+done automatically nor is it required.
+
+:::
+
+:::{attention}
+
+Note that when markup which has starting and ending delimiters appears
+alone on a line, the trailing newline will be rendered in the output.
+To avoid these extra newlines, use a trailing `@` to turn it into
+whitespace markup which consumes that trailing newline, so _e.g._
+`@{...}` followed by a newline becomes `@{...}@` followed by a
+newline. This is idiomatic for suppressing unwanted newlines. See
+[here](#idiom) for more details.
+
+:::
+
+:::{note}
+
+Custom markup was introduced in EmPy version 3.3.
+
+:::
+
+
+## Features
+
+Various additional features are available in a running EmPy system.
+
+### Pseudomodule/interpreter
+
+The pseudomodule/interpreter can be accessed by a running EmPy system by
+referencing its name (which defaults to
+`empy`) in the globals:
+
+:::{admonition} Example 2: Pseudomodule sample
+
+
+_Source_:
+``````
+This version of EmPy is @empy.version.
+The prefix in this interpreter is @empy.getPrefix() @
+and the pseudomodule name is @empy.config.pseudomoduleName.
+Do an explicit write: @empy.write("Hello, world!").
+The context is currently @empy.getContext().
+Adding a new global in a weird way: @empy.updateGlobals({'q': 789})@
+Now q is @q!
+You can do explicit expansions: @empy.expand("1 + 1 = @(1 + 1)").
+q is @(empy.defined('q') ? 'defined' ! 'undefined').
+``````
+
+_Output_:
+``````
+This version of EmPy is 4.0.1.
+The prefix in this interpreter is @ and the pseudomodule name is empy.
+Do an explicit write: Hello, world!.
+The context is currently <example 2>:5:26.
+Adding a new global in a weird way: Now q is 789!
+You can do explicit expansions: 1 + 1 = 2.
+q is defined.
+``````
+:::
+
+
+:::{important}
+
+The pseudomodule and interpreter are one and the same object; the
+terms _pseudomodule_ and _interpreter_ are used interchangeably. The
+interpreter exposes itself as the pseudomodule
+`empy` in a running EmPy system; this
+pseudomodule is never imported explicitly.
+
+:::
+
+:::{note}
+
+The pseudomodule was introduced in EmPy version 1.0.
+
+:::
+
+
+#### Interpreter attributes and methods
+
+##### Interpreter attributes
+
+The following attributes are set on the pseudomodule after it is
+initialized.
+
+`version: str`
+
+: The version of EmPy.
+
+`compat: list[str]`
+
+: A list of strings indicating the "compatibility features" that were
+ automatically enabled to support earlier versions of Python.
+ Possible strings are:
+
+| Feature | Description |
+| --- | --- |
+| `BaseException` | No `BaseException` class existed prior to Python 2.5 |
+| `chr/decode` | Substituted an implementation of `chr` for narrow Unicode builds using `decode` |
+| `chr/uliteral` | Substituted an implementation of `chr` for narrow Unicode builds using `uliteral` |
+| `narrow` | Python was built with narrow Unicode (strings natively stored as UTF-16) |
+
+`executable: str`
+
+: The path to the EmPy interpreter that is being used by the system
+ (analogous to `sys.executable`).
+
+`argv: list[str]`
+
+: The arguments (analogous to `sys.argv`) used to start the
+ interpreter. The first element is the EmPy document filename and
+ the remaining elements are the arguments, if any. If no EmPy
+ document was specified, `<->` is used.
+
+`config: Configuration`
+
+: The [configuration](#configuration) instance that the interpreter is
+ using.
+
+`ok: True`
+
+: A Boolean indicating whether or not the interpreter is still active.
+
+`error: Error`
+
+: If an error occurs, the instance of it will be assigned to this
+ attribute. When using `invoke`, this will determine whether or not
+ a failure exit code is returned. No error is indicated by `None`.
+
+##### Interpreter methods
+
+These methods involve the interpreter directly.
+
+:::{note}
+
+Most interpreter methods return `None` so they can be called from
+EmPy expression markup.
+
+:::
+
+{#constructor}
+`__init__(**kwargs)`
+
+: The constructor. It takes the following keyword arguments (listed
+ in alphabetical order), all of which have reasonable (or obvious)
+ defaults:
+
+ | Argument | Meaning | Default |
+ | --- | --- | --- |
+ | `argv` | The system arguments to use | `['<->']` |
+ | `callback` | A custom callback to register | `None` |
+ | `config` | The configuration instance to use | default |
+ | `dispatcher` | Dispatch errors or raise to caller? | `True` |
+ | `evalFunc` | Function to evaluate expressions | `eval` |
+ | `execFunc` | Function to execute statements | `exec` |
+ | `executable` | The path to the EmPy executable | `".../em.py"` |
+ | `filespec` | A 3-tuple of the input filename, output mode, and buffering | `None` |
+ | `filters` | The list of filters to install | `[]` |
+ | `globals` | The globals dictionary to use | `{}` |
+ | `handler` | The error handler to use | default |
+ | `hooks` | The list of hooks to install | `[]` |
+ | `ident` | The identifier of the interpreter (used for debugging) | `None` |
+ | `immediately` | Declare the interpreter [ready](#ready) immediately after initialization? | `True` |
+ | `input` | The input file to use for interactivity | `sys.stdin` |
+ | `output` | The output file to use | `sys.stdout` |
+ | `root` | The root interpreter context filename | `'<root>'` |
+ | `serializerFunc` | Function to serialize objects | `str` |
+
+ The ordering of the arguments does not matter. Missing arguments
+ have reasonable defaults and unrecognized arguments are ignored.
+
+ :::{important}
+
+ The order of the `Interpreter` constructor arguments has changed
+ over time and is subject to change in the future, so you need to use
+ keyword arguments to prevent any ambiguity, _e.g._:
+
+ ```python
+ import em
+
+ myConfig = em.Configuration(...)
+ myGlobals = {...}
+ myOutput = open(...)
+ interp = em.Interpreter(
+ config=myConfig,
+ globals=myGlobals,
+ output=myOutput,
+ ...)
+ ```
+
+ :::
+
+ {#constructor-arguments}
+ The allowed arguments are:
+
+ `argv: Optional[list[str]]`
+
+ : The list of EmPy arguments. The first element is always the EmPy
+ executable, with the remaining elements the actual arguments. If
+ not specified, a reasonable default is used with no arguments.
+
+ `callback: Optional[Callable]`
+
+ : The custom callback to register. Defaults to no callback.
+
+ `config: Optional[Configuration]`
+
+ : The configuration to use for this interpreter. If not specified,
+ a default configuration will be created and used.
+
+ :::{note}
+
+ The current configuration of an interpreter can be modified while
+ the interpreter is running and the changes will be effective as
+ they occur. Configurations can also be shared between multiple
+ interpreters if desired.
+
+ :::
+
+ `dispatcher: bool | Callable`
+
+ : The dispatcher to use when an error is encountered. Dispatchers
+ determine whether the error handler will be called (`True`),
+ whether the error will be reraised to the caller (`False`), or
+ something else (a custom callable). See [Error
+ dispatchers](#error-dispatchers) for more information.
+
+ `evalFunc: Callable`
+
+ : The evaluation function to use (with `@(...)`, etc.). Defaults
+ to `eval`.
+
+ `execFunc: Callable`
+
+ : The execution function to use (with `@({...}`). Defaults to
+ `exec`.
+
+ `executable: str`
+
+ : A string representing the path to the EmPy executable.
+
+ `filespec: Optional[tuple[str, str, int | str]]`
+
+ : An optional 3-tuple of the filename, the file open mode, and the
+ buffering mode of the EmPy script to be loaded. When using the
+ command line arguments, this will be handled automatically.
+
+ `filters: list[Filter]`
+
+ : A list of filters to install at startup. Defaults to none.
+
+ `globals: Optional[dict]`
+
+ : The globals dictionary to use for this interpreter. If not
+ specified, an empty dictionary will be created and used.
+
+ `handler: Optional[Callable]`
+
+ : The error handler to set. If not specified, use the default
+ handler.
+
+ `hooks: list[Hook]`
+
+ : A list of hooks to install at startup. Defaults to none.
+
+ `ident: str`
+
+ : The name of the interpreter, printed when calling `repr` on the
+ interpreter/pseudomodule object. Used only for debugging;
+ defaults to `None`.
+
+ `immediately: bool`
+
+ : A Boolean which indicates whether or not the [`ready`](#ready)
+ method will be called before the constructor exits. This is only
+ relevant for hooks which implement the `atReady` method.
+
+ `input: file`
+
+ : The input file to use for interactive mode and pausing at end.
+ Defaults to `sys.stdin`.
+
+ `output: file`
+
+ : The output file to use. Defaults to `sys.stdout`.
+
+ `root: str | (tuple[str] | tuple[str, int] | tuple[str, int, int]) | Context`
+
+ : The root context to use, which appears at the bottom of every
+ Python error traceback (`-r`/`--raw-errors`). This can be a
+ string, representing the filename; a tuple with between 1 and 3
+ parameters, with the full 3-tuple consisting of the name, the line
+ number, and the column number; or an instance of the `Context`
+ class, which will be cloned.
+
+ `serializerFunc: Callable`
+
+ : The serializer function to use (when rendering evaluations and
+ executions to the output stream). If the object being serialized
+ is `None`, `--none-symbol` will be used instead of
+ the return value of this function. Defaults to `str`.
+
+ :::{note}
+
+ The `...Func` arguments -- `evalFunc`, `execFunc` and
+ `serializerFunc` -- can be collectively changed modify the
+ interpreter's behavior to allow the EmPy interpreter to be applied
+ to languages other than Python (presuming that this language is
+ implemented in Python, of course)!
+
+ :::
+
+ :::{seealso}
+
+ The list of `Interpreter` constructor arguments is available in the
+ `constructor` help topic and is summarized
+ [here](http://www.alcyone.com/software/empy/HELP.html#interpreter-constructor-arguments-summary).
+
+ :::
+
+{#context-management}
+`__enter__()`/`__exit__(*exc)`
+
+: The interpreter presents a context manager interface and so can be
+ used with the `with` Python control structure, _e.g._:
+
+ ```python
+ import em
+
+ with em.Interpreter(...) as interp:
+ ... manipulate interp here ...
+ ```
+
+{#reset}
+`reset([clearStacks])`
+
+: Reset the interpreter to a pristine state. If `clearStacks` is true,
+ reset the stacks as well.
+
+{#ready}
+`ready()`
+
+: Declare the interpreter ready for processing. This calls the
+ `atReady` hook. By default this is called before the
+ [constructor](#constructor) exits, but the user can do this
+ explicitly by passing `False` to the `immediately` constructor
+ argument and calling it when they wish to declare the interpreter
+ ready.
+
+{#shutdown}
+`shutdown()`
+
+: Shutdown the interpreter. No further expansion must be done. This
+ method is idempotent.
+
+ :::{important}
+
+ When you create an interpreter, you must call its `shutdown` method
+ when you are done. This is required to remove the proxy on
+ `sys.stdout` that EmPy requires for proper operation and restore your
+ Python environment to the state it was before creating the
+ interpreter. This can be accomplished by creating the interpreter in
+ a `with` statement -- interpreters are also context managers -- or by
+ creating it and shutting it down in a `try`/`finally` statement.
+
+ This is not needed when calling the `expand` global function; it
+ creates and shuts down an ephemeral interpreter automatically.
+
+ :::
+
+##### Interpreter file-like methods
+
+These methods mimic a file so the interpreter can be treated as a
+file-like object in APIs.
+
+`write(data)`
+
+: Write the string data to the output stream.
+
+`writelines(lines)`
+
+: Write the sequence of strings to the output stream.
+
+`flush()`
+
+: Flush the output stream.
+
+`serialize(object)`
+
+: Write a string version of the object to the output stream. This
+ will reference `--none-symbol` (_configuration variable:_ `noneSymbol`) if the object is
+ `None`.
+
+##### Interpreter context methods
+
+These methods manipulate the interpreter's context stack.
+
+`identify() -> tuple`
+
+: Get a 4-tuple of the current context, consisting of the filename,
+ the line number, the column number, and the number of characters
+ (Unicode code points) processed.
+
+`getContext() -> Context`
+
+: Get the current context object.
+
+`newContext([name, [line, [column]]]) -> Context`
+
+: Create a new context and return it.
+
+`pushContext(context)`
+
+: Push the given context on top of the context stack.
+
+`popContext()`
+
+: Pop the top context off the context stack; do not return it.
+
+`setContext(context)`
+
+: Replace the context on the top of the context stack with the given
+ context.
+
+`setContextName(name)`
+
+: Set the top context's name to the given value.
+
+`setContextLine(line)`
+
+: Set the top context's line to the given value.
+
+`setContextColumn(column)`
+
+: Set the top context's column to the given value.
+
+`setContextData([name, [line, [column]]])`
+
+: Set the top context's name, line, and/or column to the given value(s).
+
+`restoreContext(oldContext)`
+
+: Restore the top context on the stack to the given context.
+
+##### Interpreter finalizer methods
+
+These methods manipulate the interpreter's finalizers.
+
+`clearFinalizers()`
+
+: Clear all finalizers from this interpreter.
+
+`appendFinalizer(finalizer)`/`atExit(finalizer)`
+
+: Append the given finalizer to the finalizers list for this
+ interpreter. `atExit` is an alias.
+
+`prependFinalizer(finalizer)`
+
+: Prepend the given finalizer to the finalizers list for this
+ interpreter.
+
+##### Interpreter globals methods
+
+These methods manipulate the interpreter's globals.
+
+`getGlobals() -> dict`
+
+: Get the current globals dictionary.
+
+`setGlobals(globals)`
+
+: Set the current globals dictionary,.
+
+`updateGlobals(moreGlobals)`
+
+: Update the current globals dictionary, adding this dictionary's
+ entries to it.
+
+`clearGlobals()`
+
+: Clear the current globals dictionary completely.
+
+`saveGlobals([deep])`
+
+: Save a copy of the globals off to on the history stack. If deep is
+ true, do a deep copy (defaults to false).
+
+`restoreGlobals([destructive])`
+
+: Restore the globals dictionary on the top of the globals history
+ stack. If destructive is true (default), pop it off when done.
+
+`flattenGlobals([skipKeys])`
+
+: Flatten the interpreter namespace into the globals. If `skipKeys`
+ is specified, skip over those keys; otherwise, use the defaults from
+ the configuration.
+
+##### Interpreter expansion methods
+
+These methods are involved with markup expansion.
+
+`include(fileOrFilename, [locals, [name]])`
+
+: Include the given EmPy (not Python) document (or filename, which is
+ opened) and process it with the given optional locals dictionary and
+ context name.
+
+`expand(data, [locals, [name], [dispatcher]]) -> str`
+
+: Create a new context and stream to evaluate the EmPy data, with the
+ given optional locals and context name and return the result. If
+ the expansion raises an exception, by default (`False`) it will be
+ raised up to the caller; set `dispatcher` to true to have the
+ interpreter handle it with its formal error handler mechanism. Set
+ `dispatcher` to another callable to do some custom dispatching. See
+ [Error dispatchers](#error-dispatchers) for more information.
+
+`defined(name, [locals]) -> bool`
+
+: Return a Boolean indicating whether the given name is present in the
+ interpreter globals (or the optional locals, if provided).
+
+`lookup(name, [locals]) -> object`
+
+: Lookup the value of a name in the globals (and optionally the
+ locals, if provided) and return the value.
+
+`evaluate(expression, [locals, [write]]) -> object`
+
+: Evaluate the given Python expression in the interpreter, with the
+ given optional locals dictionary. If write is true, write it to the
+ output stream, otherwise return it (defaults to false).
+
+`execute(statements, [locals])`
+
+: Execute the given Python statements in the interpreter, with the
+ given optional locals dictionary.
+
+`single(source, [locals]) -> object`
+
+: Execute the given Python expression or statement, with the given
+ optional locals dictionary. This compiles the code with the
+ `single` Python compilation mode which supports either. Return the
+ result or `None`.
+
+`atomic(name, value, [locals])`
+
+: Do an atomic assignment of the given name and value in the
+ interpreter globals. If the optional locals dictionary is provided,
+ set it in the locals instead.
+
+`assign(name, value, [locals])`
+
+: Do a potentially complex assignment of the given name "lvalue" and
+ "rvalue." Unlike `atomic`, `assign` can support tuple assignment.
+
+`significate(key, [value, [locals]])`
+
+: Declare a significator with the given key and optional value (if not
+ specified, defaults to `None`). If the optional locals dictionary
+ is provided, set it in the locals instead.
+
+`quote(string) -> str`
+
+: Given an EmPy string, return it quoted.
+
+`escape(string) -> str`
+
+: Given an EmPy string, escape non-ASCII characters in it and return.
+
+`getPrefix() -> str`
+
+: Get this interpreter's prefix.
+
+`setPrefix(char)`
+
+: Set this interpreter's prefix.
+
+##### Interpreter diversion methods
+
+These methods manipulate the interpreter's diversions.
+
+`stopDiverting()`
+
+: Stop any current diversion.
+
+`createDiversion(name)`
+
+: Create a new diversion with the given name but do not start diverting
+ to it.
+
+`retrieveDiversion(name) -> Diversion`
+
+: Get the diversion with the given name.
+
+`startDiversion(name)`
+
+: Start diverting to a diversion with the given name, creating if it
+ necessary.
+
+`playDiversion(name, [drop])`
+
+: Play the diversion with the given name, optionally dropping it
+ (default is true).
+
+`replayDiversion(name, [drop])`
+
+: Play the diversion with the given name, optionally dropping it
+ (default is false).
+
+`dropDiversion(name)`
+
+: Drop the diversion with the given name without playing it.
+
+`playAllDiversions()`
+
+: Play all diversions in sorted order by name, dropping them.
+
+`replayAllDiversions()`
+
+: Replay all diversions in sorted order by name, leaving them in
+ place.
+
+`dropAllDiversions()`
+
+: Drop all diversions without playing them.
+
+`getCurrentDiversionName() -> Optional[str]`
+
+: Get the name of the current diversion or `None` if there is no
+ current diversion.
+
+`getAllDiversionNames() -> list[str]`
+
+: Get a list of the names of all diversions in sorted order.
+
+`isExistingDiversionName(name) -> bool`
+
+: Is the given name the name of an existing diversion?
+
+##### Interpreter filter methods
+
+These methods manipulate the interpreter's filters.
+
+`resetFilter()`
+
+: Reset the filtering system so there are no filters.
+
+`getFilter() -> Filter`
+
+: Get the top-most filter.
+
+`getLastFilter() -> Filter`
+
+: Get the bottom-most filter.
+
+`setFilter(*filters)`
+
+: Set the top-most filter(s) to the given filter chain, replacing any
+ current chain. More than one filter can be specified as separate
+ arguments.
+
+`prependFilter(filter)`
+
+: Prepend the given filter to the current filter chain.
+
+`appendFilter(filter)`
+
+: Append the given filter to the current filter chain.
+
+`setFilterChain(filters)`
+
+: Set the filter chain to the given list of filters, replacing any
+ current chain.
+
+##### Interpreter hook methods
+
+These methods manipulate the interpreter's hooks.
+
+`invokeHook(_name, **kwargs)`
+
+: Invoke the hooks associated with the given name and keyword
+ arguments dictionary. This is the primary method called when hook
+ events are invoked.
+
+`areHooksEnabled() -> bool`
+
+: Are hooks currently enabled?
+
+`enableHooks()`
+
+: Enable hooks.
+
+`disableHooks()`
+
+: Disable hooks. Any existing hooks will not be called until
+ `enableHooks` is called.
+
+`getHooks() -> list[Hook]`
+
+: Get the current list of hooks.
+
+`prependHook(hook)`
+
+: Prepend the given hook to the list of hooks.
+
+`appendHook(hook)`
+
+: Append the given hook to the list of hooks.
+
+`removeHook(hook)`
+
+: Remove the given hook from the list of hooks.
+
+`clearHooks()`
+
+: Clear the list of hooks.
+
+##### Interpreter callback methods
+
+These methods manipulate the interpreter's custom callback. A
+callback is a callable object which takes one argument: the content
+to process.
+
+`hasCallback() -> bool`
+
+: Does this interpreter have a custom callback registered?
+
+`getCallback() -> Optional[Callable]`
+
+: Return the interpreter's registered custom callback or `None` if
+ none is registered.
+
+`registerCallback(callback)`
+
+: Register the given callback with the interpreter, replacing any
+ existing callback.
+
+`deregisterCallback()`
+
+: Remove the current interpreter's registered callback, if any.
+
+`invokeCallback(contents)`
+
+: Manually invoke the interpreter's custom callback as if the custom
+ markup `@<...>` were expanded.
+
+##### Interpreter error handler methods
+
+These methods manipulate the interpreter's error handler. A handler
+is a callable object which takes three arguments: the type of the
+error, the error instance itself, and a traceback object.
+
+`defaultHandler(type, error, traceback)`
+
+: The default EmPy error handler. This can be called manually by
+ custom error handlers if desired.
+
+`getHandler() -> object`
+
+: Get the current error handler, or `None` for the default.
+
+`setHandler(handler, [exitOnError])`
+
+: Set the error handler. If `exitOnError` is not `None` (defaults to
+ false), also set the interpreter's configuration's `exitOnError`
+ configuration variable. This default is so that custom error
+ handlers do not automatically exit which is usually the intent.
+
+`invokeHandler(*exc)`
+
+: Manually invoke the error handler. The arguments should be the
+ 3-tuple of the return value of `sys.exc_info` as a single argument
+ or as variable arguments, _e.g._:
+
+ ```python
+ interp.invokeHandler(sys.exc_info()) # or: *sys.exc_info()
+ ```
+
+##### Interpreter emoji methods
+
+`initializeEmojiModules([moduleNames])`
+
+: Initialize the allowed emoji modules to use by name. If the names
+ list is not specified, use the defaults.
+
+`getEmojiModule(moduleName) -> Module`
+
+: Get the initialized module abstraction corresponding to the given
+ module name.
+
+`getEmojiModuleNames() -> list[str]`
+
+: Return the list of available emoji modules by name in their proper
+ order.
+
+`substituteEmoji(text) -> str`
+
+: Use the emoji facilities to lookup the given emoji name and return
+ the result as if the emoji markup `@:...:` were expanded.
+
+:::{seealso}
+
+The list of pseudomodule/interpreter attributes in methods is
+available in the `pseudo` help topic and is summarized
+[here](http://www.alcyone.com/software/empy/HELP.html#pseudomodule-attributes-and-methods-summary).
+
+:::
+
+
+### Diversions
+
+EmPy supports an extended form of **diversions**, which are a
+mechanism for deferring and playing back output on demand, similar to
+the functionality included in [m4](https://www.gnu.org/software/m4/).
+Multiple "streams" of output can be diverted (deferred) and played
+back (undiverted) in this manner. A diversion is identified with a
+name, which is any immutable object such an integer or string.
+Diversions can be played back multiple times ("replayed") if desired.
+When recalled, diverted code is *not* resent through the EmPy
+interpreter (although a [filter](#filters) could be set up to do
+this).
+
+By default, no diversions take place. When no diversion is in effect,
+processing output goes directly to the specified output file. This
+state can be explicitly requested at any time by calling the
+`empy.stopDiverting` function. It is always legal to call this
+function, even when there is currently no active diversion.
+
+When diverted, however, output goes to a deferred location which can
+then be recalled later. Output is diverted with the
+`empy.startDiversion` function, which takes an argument that is the
+name of the diversion. If there is no diversion by that name, a new
+diversion is created and output will be sent to that diversion; if the
+diversion already exists, output will be appended to that preexisting
+diversion.
+
+Output send to diversions can be recalled in two ways. The first is
+through the `empy.playDiversion` function, which takes the name of the
+diversion as an argument. This plays back the named diversion, sends
+it to the output, and then erases that diversion. A variant of this
+behavior is the `empy.replayDiversion`, which plays back the named
+diversion but does not eliminate it afterwards; `empy.replayDiversion`
+can be repeatedly called with the same diversion name, and will replay
+that diversion repeatedly. `empy.createDiversion` will create a
+diversion without actually diverting to it, for cases where you want
+to make sure a diversion exists but do not yet want to send anything
+to it.
+
+The diversion object itself can be retrieved with
+`empy.retrieveDiversion`. Diversions act as writable file-objects,
+supporting the usual `write`, `writelines`, `flush`, and `close`
+methods. The data that has been diverted to them can be manually
+retrieved in one of two ways; either through the `asString` method,
+which returns the entire contents of the diversion as a single string,
+or through the `asFile` method, which returns the contents of the
+diversion as a readable (not writable) file-like object.
+
+Diversions can also be explicitly deleted without playing them back
+with the `empy.dropDiversion` function, which takes the desired
+diversion name as an argument.
+
+Additionally there are three functions which will apply the above
+operations to all existing diversions: `empy.playAllDiversions`,
+`empy.replayAllDiversions`, and `empy.dropAllDiversions`. The
+diversions are handled in lexicographical order by their name. Also,
+all three will do the equivalent of a `empy.stopDiverting` call before
+they do their thing.
+
+The name of the current diversion can be requested with the
+`empy.getCurrentDiversionName` function; also, the names of all
+existing diversions (in sorted order) can be retrieved with
+`empy.getAllDiversionNames`. `empy.isExistingDiversionName` will
+return whether or not a diversion with the given name exists.
+
+When all processing is finished, the equivalent of a call to
+`empy.playAllDiversions` is done. This can be disabled with the
+`--no-auto-play-diversions` (_configuration variable:_ `autoPlayDiversions`) option.
+
+:::{admonition} Example 3: Diversions sample
+
+
+_Source_:
+``````
+This text is output normally.
+@empy.startDiversion('A')@
+(This text was diverted!)
+@empy.stopDiverting()@
+This text is back to being output normally.
+Now playing the diversion:
+@empy.playDiversion('A')@
+And now back to normal output.
+``````
+
+_Output_:
+``````
+This text is output normally.
+This text is back to being output normally.
+Now playing the diversion:
+(This text was diverted!)
+And now back to normal output.
+``````
+:::
+
+
+:::{note}
+
+Diversions were introduced in EmPy version 1.0.
+
+:::
+
+
+### Filters
+
+EmPy also supports dynamic **filters**. Filters are put in place
+immediately before the final output file, and so are only invoked
+after all other processing has taken place (including interpreting and
+diverting). Filters take input, remap it, and then send it to the
+output. They can be chained together where a series of filters point
+to each other in series and then finally to the output file.
+
+The current top-level filter can be retrieved with `empy.getFilter`
+(or `empy.getFirstFilter`). The last filter in the chain (the one
+just before the underlying file) can be retrieved with
+`empy.getLastFilter`. The filter can be set with `empy.setFilter`
+(which allows multiple arguments to constitute a chain). To append a
+filter at the end of the chain (inserting it just before the
+underlying output file), use `empy.appendFilter`. To prepend it to
+the top of the chain, use `empy.prependFilter`. A filter chain can be
+set directly with `empy.setFilterChain`. And a filter chain can be
+reset with `empy.resetFilter`, removing all filters.
+
+Filters are, at their core, simply file-like objects (minimally
+supporting `write`, `flush`, and `close` methods that behave in the
+usual way) which, after performing whatever processing they need to
+do, send their work to the next file-like object or filter in line,
+called that filter's "sink." That is to say, filters can be "chained"
+together; the action of each filter takes place in sequence, with the
+output of one filter being the input of the next. The final sink of
+the filter chain will be the output file. Additionally, filters
+support a `_flush` method (note the leading underscore) which will
+always flush the filter's underlying sink; this method should be not
+overridden.
+
+Filters also support two additional methods, not part of the
+traditional file interface: `attach`, which takes as an argument a
+file-like object (perhaps another filter) and sets that as the
+filter's "sink" -- that is, the next filter/file-like object in line.
+`detach` (which takes no arguments) is another method which flushes
+the filter and removes its sink, leaving it isolated. Finally,
+`next`, if present, is an attribute which references the filter's sink
+-- or `None`, if the filter does not yet have a sink attached.
+
+To create your own filter, you can create an object which supports the
+above described interface, or simply derive from the `Filter` class
+(or one of its subclasses) in the `emlib` module and override the
+relevant methods.
+
+:::{admonition} Example 4: Filters sample
+
+
+_Source_:
+``````
+@{
+# For access to the filter classes.
+import emlib
+}@
+This text is normal.
+@empy.appendFilter(emlib.FunctionFilter(lambda x: x.upper()))@
+This text is in all uppercase!
+@empy.appendFilter(emlib.FunctionFilter(lambda x: '[' + x + ']'))@
+Now it's also surrounded by brackets!
+(Note the brackets are around output as it is sent,
+not at the beginning and end of each line.)
+@empy.resetFilter()@
+Now it's back to normal.
+``````
+
+_Output_:
+``````
+This text is normal.
+THIS TEXT IS IN ALL UPPERCASE!
+[NOW IT'S ALSO SURROUNDED BY BRACKETS!
+(NOTE THE BRACKETS ARE AROUND OUTPUT AS IT IS SENT,
+NOT AT THE BEGINNING AND END OF EACH LINE.)
+]Now it's back to normal.
+``````
+:::
+
+
+:::{note}
+
+Filters were introduced in EmPy version 1.3.
+
+:::
+
+
+### Hooks
+
+The EmPy system allows for the registration of **hooks** with a
+running EmPy interpreter. Hooks are objects, registered with an
+interpreter, whose methods represent specific hook events. Any number
+of hook objects can be registered with an interpreter, and when a hook
+is invoked, the associated method on each one of those hook objects
+will be called by the interpreter in sequence. The method name
+indicates the type of hook, and it is called with a keyword list of
+arguments corresponding the event arguments.
+
+To use a hook, derive a class from `emlib.Hook` and override the
+desired methods (with the same signatures as they appear in the base
+class). Create an instance of that subclass, and then register it
+with a running interpreter with the `empy.addHook` function. A hook
+instance can be removed with the `empy.removeHook` function.
+
+More than one hook instance can be registered with an interpreter; in
+such a case, the appropriate methods are invoked on each instance in
+the order in which they were appended. To adjust this behavior, an
+optional `prepend` argument to the `empy.addHook` function can be used
+dictate that the new hook should placed at the *beginning* of the
+sequence of hooks, rather than at the end (which is the default).
+Also there are explicit `empy.appendHook` and `empy.prependHook`
+functions.
+
+All hooks can be enabled and disabled entirely for a given
+interpreter; this is done with the `empy.enableHooks` and
+`empy.disableHooks` functions. By default hooks are enabled, but
+obviously if no hooks have been registered no hook callbacks will be
+made. Whether hooks are enabled or disabled can be determined by
+calling `empy.areHooksEnabled`. To get the list of registered hooks,
+call `empy.getHooks`. All the hooks can be removed with
+`empy.clearHooks`. Finally, to invoke a hook manually, use
+`empy.invokeHook`.
+
+For a list of supported hook callbacks, see the `Hook` class
+definition in the `emlib` module. (There is also an `AbstractHook`
+class in this module which does not have blank stubs for existing hook
+methods in case a user wishes to create them dynamically.)
+
+For example:
+
+:::{admonition} Example 5: Hooks sample
+
+
+_Source_:
+``````
+@# Modify the backquote markup to prepend and append backquotes
+@# (say, for a document rendering system, cough cough).
+@{
+import emlib
+
+class BackquoteHook(emlib.Hook):
+
+ def __init__(self, interp):
+ self.interp = interp
+
+ def preBackquote(self, literal):
+ self.interp.write('`' + literal + '`')
+ return True # return true to skip the standard behavior
+
+empy.addHook(BackquoteHook(empy))
+}@
+Now backquote markup will render with backquotes: @
+@`this is now in backquotes`!
+``````
+
+_Output_:
+``````
+Now backquote markup will render with backquotes: `this is now in backquotes`!
+``````
+:::
+
+
+:::{note}
+
+Hooks were originally introduced in EmPy version 2.0, much improved in
+version 3.2, and revamped again in version 4.0.
+
+:::
+
+
+#### Hook methods
+
+##### Hook `at...` methods
+
+These hooks are called when a self-contained event occurs.
+
+`atInstallProxy(proxy, new)`
+
+: A `sys.stdout` proxy was installed. The Boolean value `new`
+ indicates whether or not the proxy was preexisting.
+
+`atUninstallProxy(proxy, done)`
+
+: A `sys.stdout` proxy was uninstalled. The Boolean value `done`
+ indicates whether the reference count went to zero (and so the proxy
+ has been completely removed).
+
+`atStartup()`
+
+: The interpreter has started up.
+
+`atReady()`
+
+: The interpreter has declared itself ready for processing.
+
+`atFinalize()`
+
+: The interpreter is finalizing.
+
+`atShutdown()`
+
+: The interpreter is shutting down.
+
+`atParse(scanner, locals)`
+
+: The interpreter is initiating a parse action with the given scanner
+ and locals dictionary (which may be `None`).
+
+`atToken(token)`
+
+: The interpreter is expanding a token.
+
+`atHandle(info, fatal, contexts)`
+
+: The interpreter has encountered an error. The `info` parameter is a
+ 3-tuple error (error type, error, traceback) returned from
+ `sys.exc_info`, `fatal` is a Boolean indicating whether the
+ interpreter should exit afterwards, and `contexts` is the context
+ stack.
+
+`atInteract()`
+
+: The interpreter is going interactive.
+
+##### Hook context methods
+
+`pushContext(context)`
+
+: This context is being pushed.
+
+`popContext(context)`
+
+: This context has been popped.
+
+`setContext(context)`
+
+: This context has been set or modified.
+
+`restoreContext(context)`
+
+: This context has been restored.
+
+##### Hook `pre...`/`post...` methods
+
+The `pre...` hooks are invoked before a token expands. The hook can
+return a true value to indicate that it has intercepted the expansion
+and the token should cancel native expansion. Not explicitly
+returning anything, as in standard Python, is equivalent to returning
+`None`, which is a false value, which continues expansion:
+
+:::{admonition} Example 50: Hook `pre...` methods
+
+
+_Source_:
+``````
+@{
+import emlib
+import sys
+
+class Hook(emlib.Hook):
+
+ def __init__(self, interp):
+ self.interp = interp
+
+ def preString(self, string):
+ self.interp.write('[' + string + ']')
+ return True
+
+empy.addHook(Hook(empy))
+}@
+@# Now test it:
+@"Hello, world!"
+``````
+
+_Output_:
+``````
+["Hello, world!"]
+``````
+:::
+
+
+:::{tip}
+
+It's typical to want to have an instance of the
+interpreter/pseudomodule available to the hook, but it is neither done
+automatically nor is it required.
+
+:::
+
+The `post...` hooks are invoked after a non-intercepted token finishes
+expanding. Not all `pre...` hooks have a corresponding `post...`
+hook. The `post...` hooks take at most one argument (the result of
+the token expansion, if applicable) and their return value is ignored.
+
+`preLineComment(comment)`, `postLineComment()`
+
+: The line comment `@#... NL` with the given text.
+
+`preInlineComment(comment)`, `postInlineComment()`
+
+: The inline comment `@*...*` with the given text.
+
+`preWhitespace(whitespace)`
+
+: The whitespace token `@ WS` with the given whitespace.
+
+`prePrefix()`
+
+: The prefix token `@@`.
+
+`preString(string)`, `postString()`
+
+: The string token `@'...'`, etc. with the given string.
+
+`preBackquote(literal)`, `postBackquote(result)`
+
+: The backquote token `` @`...` `` with the given literal.
+
+`preSignificator(key, value, stringized)`, `postSignificator()`
+
+: The significator token `@%... NL`, etc. with the given key, value
+ and a Boolean indicating whether the significator is stringized.
+
+`preContextName(name)`, `postContentName()`
+
+: The context name token `@?...` with the given name.
+
+`preContextLine(line)`, `postContextLine()`
+
+: The context line token `@!...` with the given line.
+
+`preExpression(pairs, except, locals)`, `postExpression(result)`
+
+: The expression token `@(...)` with the given if-then run pairs, the
+ except run, and the locals dictionary (which may be `None`).
+
+`preSimple(code, subtokens, locals)`, `postSimple(result)`
+
+: The simple expression token `@word` (etc.) with the given code,
+ subtokens and locals.
+
+`preInPlace(code, locals)`, `postInPlace(result)`
+
+: The in-place expression token `@$...$...$` with the given code
+ (first section) and locals (which may be `None`).
+
+`preStatement(code, locals)`, `postStatement()`
+
+: The statement token `@{...}` with the given code and locals (which
+ may be `None`).
+
+`preControl(type, rest, locals)`, `postControl()`
+
+: The control token `@[...]` of the given type, with the rest run and
+ locals (which may be None).
+
+`preEscape(code)`, `postEscape()`
+
+: The control token `@\...` with the resulting code.
+
+`preDiacritic(code)`, `postDiacritic()`
+
+: The diacritic token `@^...` with the resulting code.
+
+`preIcon(code)`, `postIcon()`
+
+: The icon token `@|...` with the resulting code.
+
+`preEmoji(name)`, `postEmoji()`
+
+: The emoji token `@:...:` with the given name.
+
+`preCustom(contents)`, `postCustom()`
+
+: The custom token `@<...>` with the given contents.
+
+
+##### Hook `before...`/`after...` methods
+
+The `before...` and `after...` hooks are invoked before and after (go
+figure) mid-level expansion activities are performed. Any `locals`
+argument indicates the locals dictionary, which may be `None`.
+
+If the expansion returns something relevant, it is passed as a
+`result` argument to the corresponding `after...` method.
+
+`beforeProcess(command, n)`, `afterProcess()`
+
+: The given command (with index number) is being processed.
+
+`beforeInclude(file, locals, name)`, `afterInclude()`
+
+: The given file is being processed with the given name.
+
+`beforeExpand(string, locals, name)`, `afterExpand(result)`
+
+: `empy.expand` is being called with the given string and name.
+
+`beforeTokens(tokens, locals)`, `afterTokens(result)`
+
+: The given list of tokens is being processed.
+
+`beforeFileLines(file, locals)`, `afterFileLines()`
+
+: The given file is being read by lines.
+
+`beforeFileChunks(file, locals)`, `afterFileChunks()`
+
+: The given file is being read by buffered chunks.
+
+`beforeFileFull(file, locals)`, `afterFileFull()`
+
+: The given file is being read fully.
+
+`beforeString(string, locals)`, `afterString()`
+
+: The given string is being processed.
+
+`beforeQuote(string)`, `afterQuote(result)`
+
+: The given string is being quoted.
+
+`beforeEscape(string)`, `afterEscape(result)`
+
+: The given string is being escaped.
+
+`beforeSignificate(key, value, locals)`, `afterSignificate()`
+
+: The given key/value pair is being processed.
+
+`beforeCallback(contents)`, `afterCallback()`
+
+: The custom callback is being processed with the given contents.
+
+`beforeAtomic(name, value, locals)`, `afterAtomic()`
+
+: The given atomic variable setting with the name and value is being
+ processed.
+
+`beforeMulti(names, values, locals)`, `afterMulti()`
+
+: The given complex variable setting with the names and values is
+ being processed.
+
+`beforeImport(name, locals)`, `afterImport()`
+
+: A module with the given name is being imported.
+
+`beforeFunctional(code, lists, locals)`, `afterFunctional(result)`
+
+: A functional markup is with the given code and argument lists (of
+ EmPy code) is being processed.
+
+`beforeEvaluate(expression, locals, write)`, `afterEvaluate(result)`
+
+: An evaluation markup is being processed with the given code and a
+ Boolean indicating whether or not the results are being written
+ directly to the output stream or returned.
+
+`beforeExecute(statements, locals)`, `afterExecute()`
+
+: A statement markup is being processed.
+
+`beforeSingle(source, locals)`, `afterSingle(result)`
+
+: A "single" source (either an expression or a statement) is being
+ compiled and processed.
+
+`beforeFinalizer(final)`, `afterFinalizer()`
+
+: The given finalizer is being processed. If the `beforeFinalizer`
+ hook returns true for a particular finalizer, then that finalizer
+ will not be called.
+
+:::{seealso}
+
+The list of hook methods is available in the `hooks` help topic and is
+summarized [here](http://www.alcyone.com/software/empy/HELP.html#hook-methods-summary).
+
+:::
+
+
+## Customization
+
+The behavior of an EmPy system can be customized in various ways.
+
+### Command line options
+
+EmPy uses a standard GNU-style command line options processor with
+both short and long options (_e.g._, `-p` or `--prefix`). Short
+options can be combined into one word, and options can have values
+either in the next word or in the same word separated by an `=`. An
+option consisting of only `--` indicates that no further option
+processing should be performed.
+
+EmPy supports the following options:
+
+`-V`/`--version`
+
+: Print version information exit. Repeat the option for more details
+ (see below).
+
+`-W`/`--info`
+
+: Print additional information, including the operating system, Python
+ implementation and Python version number.
+
+`-Z`/`--details`
+
+: Print all additional details about the running environment,
+ including interpreter, system, platform, and operating system
+ release details.
+
+`-h`/`--help`
+
+: Print basic help and exit. Repeat the option for more extensive
+ help. Specifying `-h` once is equivalent to `-H default`; twice to
+ `-H more`, and three or more times to `-H all` (see below).
+
+`-H`/`--topics=TOPICS`
+
+: Print extended help by topic(s). Topics are a comma-separated list
+ of the following choices:
+
+ | Topic | Description |
+ | --- | --- |
+ | `usage` | Basic command line usage |
+ | `options` | Command line options |
+ | `markup` | Markup syntax |
+ | `escapes` | Escape sequences |
+ | `environ` | Environment variables |
+ | `pseudo` | Pseudomodule attributes and functions |
+ | `variables` | Configuration variable attributes |
+ | `methods` | Configuration methods |
+ | `hook` | Hook methods |
+ | `controls` | Named escapes (control codes) |
+ | `diacritics` | Diacritic combiners |
+ | `icons` | Icons |
+ | `emojis` | User-specified emojis (optional) |
+ | `hints` | Usage hints |
+ | `topics` | This list of topics |
+ | `default` | `usage,options,markup,hints` and `topics` |
+ | `more` | `usage,options,markup,escapes,environ,hints` and `topics` |
+ | `all` | `usage,options,markup,escapes,environ,pseudo,config,controls,diacritics,icons,hints` |
+
+ As a special case, `-H` with no topic argument is treated as `-H
+ all` rather than error.
+
+`-v`/`--verbose`
+
+: The EmPy system will print debugging information to `sys.stderr` as
+ it is doing its processing.
+
+`-p`/`--prefix=CHAR` (_environment variable:_ `EMPY_PREFIX`, _configuration variable:_ `prefix`)
+
+: Specify the desired EmPy prefix. It must consistent of a single
+ Unicode code point (or character), or an empty string for no prefix
+ (see below). Defaults to `@`.
+
+`--no-prefix`
+
+: Specify that EmPy use no prefix. In this mode, will only process
+ text and perform no markup expansion. This is equivalent to
+ specyfing `-p ''`.
+
+`-q`/`--no-output`
+
+: Use a null file for the output file.
+
+`-m`/`--pseudomodule=NAME` (_environment variable:_ `EMPY_PSEUDO`, _configuration variable:_ `pseudomoduleName`)
+
+: Specify the name of the EmPy pseudomodule/interpreter. Defaults to
+ `empy`.
+
+`-f`/`--flatten` (_environment variable:_ `EMPY_FLATTEN`, _configuration variable:_ `doFlatten`)
+
+: Before processing, move the contents of the
+ `empy` pseudomodule into the globals, just
+ as if `empy.flattenGlobals()` were executed immediately after
+ starting the interpreter. This is the equivalent of executing `from
+ empy import *` (though since the pseudomodule is not a real module
+ that statement is invalid). _e.g._, `empy.include` can be referred
+ to simply as `include` when this flag is specified on the command
+ line.
+
+`-k`/`--keep-going`
+
+: Don't exit immediately when an error occurs. Execute the error
+ handler but continue processing EmPy tokens.
+
+`-e`/`--ignore-errors`
+
+: Ignore errors completely. No error dispatcher or handler is
+ executed and token processing continues indefinitely. Implies
+ `-k`/`--keep-going`.
+
+`-r`/`--raw-errors` (_environment variable:_ `EMPY_RAW_ERRORS`, _configuration variable:_ `rawErrors`)
+
+: After logging an EmPy error, show the full Python traceback that
+ caused it. Useful for debugging.
+
+`-i`/`--interactive` (_environment variable:_ `EMPY_INTERACTIVE`, _configuration variable:_ `goInteractive`)
+
+: Enter interactive mode after processing is complete by continuing to
+ process EmPy markup from the input file, which is by default
+ `sys.stdin`); this can be changed with the `input` interpreter
+ attribute. This is helpful for inspecting the state of the
+ interpreter after processing.
+
+`-d`/`--delete-on-error` (_environment variable:_ `EMPY_DELETE_ON_ERROR`, _configuration variable:_ `deleteOnError`)
+
+: If an error occurs, delete the output file; requires the use of the
+ one of the output options such as `-o`/`--output=FILENAME`. This is
+ useful when running EmPy under a build systemn such as GNU Make. If
+ this option is not selected and an error occurs, the output file
+ will stop when the error is encountered.
+
+`-n`/`--no-proxy` (_environment variable:_ `EMPY_NO_PROXY`, _configuration variable:_ `useProxy`)
+
+: Do not install a proxy in `sys.stdout`. This will make EmPy thread
+ safe but writing to `sys.stdout` will not be captured or processed
+ in any way.
+
+`--config=STATEMENTS`
+
+: Perform the given configuration variable assignments. This option
+ can be specified multiple times.
+
+`-c`/`--config-file=FILENAME` (_environment variable:_ `EMPY_CONFIG`)
+
+: Read and process the given configuration file(s), separated by the
+ platform-specific path delimiter (`;` on Windows, `:` on other
+ operating systems). This option can be specified multiple times.
+
+`--config-variable=NAME` (_configuration variable:_ `configVariableName`)
+
+: Specify the variable name corresponding to the current configuration
+ when configuration files are processed. Defaults to
+ `_`.
+
+`-C`/`--ignore-missing-config`
+
+: Ignore missing files while reading and processing configurations.
+ By default, a missing file is an error.
+
+`-o`/`--output=FILENAME`
+
+: Specify the file to write output to. If this argument is not used,
+ final output is written to the underlying `sys.stdout`.
+
+`-a`/`--append=FILENAME`
+
+: Specify the file to append output to. If this argument is not used,
+ final output is appended to the underlying `sys.stdout`.
+
+`-O`/`--output-binary=FILENAME`
+
+: Specify the file to write output to and open it as binary.
+
+`-A`/`--append-binary=FILENAME`
+
+: Specify the file to append output to and open it as binary.
+
+`--output-mode=MODE`
+
+: Specify the output mode to use.
+
+`--input-mode=MODE`
+
+: Specify the input mode to use. Defaults to `'r'`.
+
+`-b`/`--buffering` (_environment variable:_ `EMPY_BUFFERING`, _configuration variable:_ `buffering`)
+
+: Specify the buffering to use. Use an integer to specify the maximum
+ number of bytes to read per block or one of the following string
+ values:
+
+ | Name | Value | Description |
+ | --- | --- | --- |
+ | `full` | -1 | Use full buffering |
+ | `none` | 0 | Use no buffering |
+ | `line` | 1 | Use line buffering |
+ | `default` | 16384 | Default buffering |
+
+ If the choice of buffering is incompatible with other settings, a
+ `ConfigurationError` is raised. This option has no effect on
+ interactive mode, as `sys.stdin` is already open. Defaults to
+ 16384.
+
+`--default-buffering`
+
+: Use default buffering.
+
+`-N`/`--no-buffering`
+
+: Use no buffering.
+
+`-L`/`--line-buffering`
+
+: Use line buffering.
+
+`-B`/`--full-buffering`
+
+: Use full buffering.
+
+`-P`/`--preprocess=FILENAME`
+
+: Process the given EmPy (not Python) file before main document
+ processing begins.
+
+`-Q`/`--postprocess=FILENAME`
+
+: Process the given EmPy (not Python) file after main document
+ processing begins.
+
+`-I`/`--import=MODULES`
+
+: Import the given Python (not EmPy) module(s) into the interpreter
+ globals before main document processing begins.
+
+`-D`/`--define=DEFN`
+
+: Define the given variable into the interpreter globals before main
+ document processing begins. This is executed as a Python assignment
+ statement (`variable = ...`); if it does not contain a `=`
+ character, then the variable is defined in the globals with the
+ value `None`.
+
+`-S`/`--string=STR`
+
+: Define the given string variable into the interpreter globals before
+ main document processing begins. The value is always treated as a
+ string and never evaluated; if it does not contain a `=` character,
+ then the variable is defined as the empty string (`''`).
+
+`-E`/`--execute=STATEMENT`
+
+: Execute the given arbitrary Python (not EmPy) statement before main
+ document processing begins.
+
+`-F`/`--file=FILENAME`
+
+: Execute the given Python (not EmPy) file before main document
+ processing begins.
+
+`-G`/`--postfile=FILENAME`
+
+: Execute the given Python (not EmPy) file after main document
+ processing begins.
+
+`-w`/`--pause-at-end`
+
+: Prompt for a line of input after all processing is complete. Useful
+ for systems where the window running EmPy would automatically
+ disappear after EmPy exits (_e.g._, Windows). By default, the input
+ file used is `sys.stdin`, so this will not work when redirecting
+ stdin to an EmPy process. This can be changed with the `input`
+ interpreter attribute.
+
+`-l`/`--relative-path` (_configuration variable:_ `relativePath`)
+
+: Prepend the location of the EmPy script to Python's `sys.path`.
+ This is useful when the EmPy scripts themselves import Python .py
+ modules in that same directory.
+
+`--no-callback-error`
+
+: If the custom markup is used without a registered callback, do not
+ report an error.
+
+`--no-ignore-bangpaths`
+
+: Do not treat bangpaths as comments. By default, bangpaths (starting
+ lines that begin with the characters `#!`) are treated as comments
+ and ignored.
+
+`--none-symbol` (_configuration variable:_ `noneSymbol`)
+
+: The string to write when expanding the value `None`. Defaults to
+ `None`, which will result in no output.
+
+`--no-none-symbol`
+
+: Do not write any preset string when expanding `None`; equivalent to
+ setting `noneSymbol` to `None`.
+
+`--no-expand-user`
+
+: Do not expand user constructions (`~user`) in pathnames. By default
+ they are expanded.
+
+`--no-auto-validate-icons`
+
+: Do not auto-validate icons when an icon markup is first used. See
+ below.
+
+`--starting-line` (_configuration variable:_ `startingLine`)
+
+: Specify an integer representing the default starting line for
+ contexts. Default is 1.
+
+`--starting-column` (_configuration variable:_ `startingColumn`)
+
+: Specify an integer representing the default starting column for
+ contexts. Default is 1.
+
+`--emoji-modules` (_configuration variable:_ `emojiModuleNames`)
+
+: A comma-separated list of emoji modules to try to use for the emoji
+ markup (`@:...:`). See below. Defaults to
+ `emoji,emojis,emoji_data_python,unicodedata`.
+
+`--no-emoji-modules`
+
+: Only use `unicodedata` as an emoji module; disable all other emoji
+ modules.
+
+`--disable-emoji-modules`
+
+: Disable all emoji module usage; just rely on the `emojis` attribute
+ of the configuration. See below.
+
+`--ignore-emoji-not-found`
+
+: When using emoji markup (`@:...:`), do not raise an error when an
+ emoji is not found; just pass the `:...:` text through.
+
+`-u`/`--binary`/`--unicode` (_environment variable:_ `EMPY_BINARY`, _configuration variable:_ `useBinary`)
+
+: Operate in binary mode; open files in binary mode and use the
+ `codecs` module for Unicode support. This is necessary in older
+ versions of Python 2._x_.
+
+`-x`/`--encoding=E`
+
+: Specify both input and output Unicode encodings. Requires
+ specifying both an input and an output file.
+
+`--input-encoding=E` (_environment variable:_ `EMPY_INPUT_ENCODING`, _configuration variable:_ `inputEncoding`)
+
+: Specify the input Unicode encoding. Requires specifying an input
+ file rather than `sys.stdout`.
+
+ :::{note}
+
+ Specifying a non-default encoding when using interactive mode
+ (`sys.stdin`) raises a `ConfigurationError`.
+
+ :::
+
+`--output-encoding=E` (_environment variable:_ `EMPY_OUTPUT_ENCODING`, _configuration variable:_ `outputEncoding`)
+
+: Specify the output Unicode encoding. Requires specifying an output
+ file rather than `sys.stdout`.
+
+ :::{note}
+
+ Specifying a non-default encoding when using `sys.stdout` raises a
+ `ConfigurationError`.
+
+ :::
+
+`-y`/`--errors=E`
+
+: Specify both [input and output Unicode error
+ handlers](https://docs.python.org/3/library/functions.html#open).
+
+`--input-errors=E` (_environment variable:_ `EMPY_INPUT_ERRORS`, _configuration variable:_ `inputErrors`)
+
+: Specify the [input Unicode error
+ handler](https://docs.python.org/3/library/functions.html#open).
+
+ :::{note}
+
+ Specifying a non-default error handler when using interactive mode
+ (`sys.stdin`) raises a `ConfigurationError`.
+
+ :::
+
+`--output-errors=E` (_environment variable:_ `EMPY_OUTPUT_ERRORS`, _configuration variable:_ `outputErrors`)
+
+: Specify the [output Unicode error
+ handler](https://docs.python.org/3/library/functions.html#open).
+
+ :::{note}
+
+ Specifying a non-default error handler when using `sys.stdout`
+ raises a `ConfigurationError`.
+
+ :::
+
+`-z`/`--normalization-form=F` (_configuration variable:_ `normalizationForm`)
+
+: Specify the Unicode normalization to perform when using the
+ diacritics markup (`@^...`). Specify an empty string (`''`) to
+ skip normalization. Defaults to `NFKC`
+ for modern versions of Python and `''` for very old versions of
+ Python 2._x_.
+
+`--no-auto-play-diversions` (_configuration variable:_ `autoPlayDiversions`)
+
+: Before exiting, do not automatically play back any remaining
+ diversions. By default such diversions are played back.
+
+`--no-check-variables` (_configuration variable:_ `checkVariables`)
+
+: When modifying configuration variables, normally the existence and
+ types of these variables is checked and if it doesn't exist or it is
+ attempting to be assigned to an incompatible type, it will raise a
+ `ConfigurationError`. To override this behavior, use this flag.
+
+`--context-format` (_configuration variable:_ `contextFormat`)
+
+: Specify the format for printing contexts. See below.
+
+`--success-code=N` (_configuration variable:_ `successCode`)
+
+: Specify the exit code for the Python interpreter on success.
+ Defaults to 0.
+
+`--failure-code=N` (_configuration variable:_ `failureCode`)
+
+: Specify the exit code for the Python interpreter when a processing
+ error occurs. Defaults to 1.
+
+`--unknown-code=N` (_configuration variable:_ `unknownCode`)
+
+: Specify the exit code for the Python interpreter when an invalid
+ configuration (such as unknown command line options) is encountered.
+ Defaults to 2.
+
+:::{seealso}
+
+The list of command line options is available in the `options` help
+topic and is summarized
+[here](http://www.alcyone.com/software/empy/HELP.html#command-line-options-summary).
+
+:::
+
+
+### Environment variables
+
+The following environment variables are supported:
+
+`EMPY_OPTIONS`
+
+: Specify additional command line options to be used. These are in
+ effect added to the start of the command line and parsed before
+ any explicit command line options and processing begins.
+
+ For example, this will run the EmPy interpreter as if the `-r` and
+ `-d` command line options were specified:
+
+ <pre class="shell"><b><i>% export EMPY_OPTIONS='-r -d'; em.py ...</i></b>
+</pre>
+
+
+`EMPY_CONFIG` (_command line option:_ `-c`/`--config-file=FILENAME`)
+
+: Specify the configuration file(s) to process before main document
+ processing begins.
+
+`EMPY_PREFIX` (_command line option:_ `-p`/`--prefix=CHAR`, _configuration variable:_ `prefix`)
+
+: Specify the prefix to use when processing.
+
+`EMPY_PSEUDO` (_command line option:_ `-m`/`--pseudomodule=NAME`, _configuration variable:_ `pseudomoduleName`)
+
+: Specify the name of the pseudomodule/interpreter to use when
+ processing.
+
+`EMPY_FLATTEN` (_command line option:_ `-f`/`--flatten`, _configuration variable:_ `doFlatten`)
+
+: If defined, flatten the globals before processing.
+
+`EMPY_RAW_ERRORS` (_command line option:_ `-r`/`--raw-errors`, _configuration variable:_ `rawErrors`)
+
+: If defined, after an error occurs, show the full Python tracebacks
+ of the exception.
+
+`EMPY_INTERACTIVE` (_command line option:_ `-i`/`--interactive`, _configuration variable:_ `goInteractive`)
+
+: If defined, enter interactive mode by processing markup from
+ `sys.stdin` after main document processing is complete.
+
+`EMPY_DELETE_ON_ERROR` (_command line option:_ `-d`/`--delete-on-error`, _configuration variable:_ `deleteOnError`)
+
+: If defined, when an error occurs, delete the corresponding output
+ file.
+
+`EMPY_NO_PROXY` (_command line option:_ `-n`/`--no-proxy`, _configuration variable:_ `useProxy`)
+
+: If defined, do not install a `sys.stdout` proxy.
+
+`EMPY_BUFFERING` (_command line option:_ `-b`/`--buffering`, _configuration variable:_ `buffering`)
+
+: Specify the desired file buffering.
+
+`EMPY_BINARY` (_command line option:_ `-u`/`--binary`/`--unicode`, _configuration variable:_ `useBinary`)
+
+: If defined, use binary mode.
+
+`EMPY_ENCODING`
+
+: Specify the desired input and output Unicode encodings.
+
+`EMPY_INPUT_ENCODING` (_command line option:_ `--input-encoding=E`, _configuration variable:_ `inputEncoding`)
+
+: Specify the desired input Unicode encoding only.
+
+`EMPY_OUTPUT_ENCODING` (_command line option:_ `--output-encoding=E`, _configuration variable:_ `outputEncoding`)
+
+: Specify the desired output Unicode encoding only.
+
+`EMPY_ERRORS`
+
+: Specify the desired input and output Unicode error handler.
+
+`EMPY_INPUT_ERRORS` (_command line option:_ `--input-errors=E`, _configuration variable:_ `inputErrors`)
+
+: Specify the desired input Unicode error handler.
+
+`EMPY_OUTPUT_ERRORS` (_command line option:_ `--output-errors=E`, _configuration variable:_ `outputErrors`)
+
+: Specify the desired output Unicode error handler.
+
+:::{seealso}
+
+The list of environment variables is available in the `environ` help
+topic and is summarized
+[here](http://www.alcyone.com/software/empy/HELP.html#environment-variables-summary).
+
+:::
+
+:::{note}
+
+Environment variables were first introduced in EmPy version 2.2, and
+revamped in version 4.0.
+
+:::
+
+
+### Configuration
+
+**Configurations** are objects which determine the behavior of an EmPy
+interpreter. They can be created with an instance of the
+`Configuration` class and have a set of attributes (**configuration
+variables**) which can be modified. Most configuration variables
+correspond to a command line option. The configuration instance also
+contains supporting methods which are used by the interpreter which
+can be overridden.
+
+When configuration variables are modified, they are by default checked
+to make sure have a known name and that they have the correct type; if
+not, a `ConfigurationError` will be raised. This behavior can be
+disabled with `--no-check-variables` (_configuration variable:_ `checkVariables`).
+
+When a configuration is assigned to an interpreter, it exists as a
+`config` attribute of the `empy` pseudomodule and can be modified by a
+running EmPy system. Configurations can be shared between multiple
+interpreters if desired.
+
+:::{admonition} Example 51: Configuration instances
+
+
+_Source_:
+``````
+@{
+empy.config.prefix = '$'
+}$
+${
+print("The EmPy prefix is now $, not @!")
+}$
+``````
+
+_Output_:
+``````
+The EmPy prefix is now $, not @!
+``````
+:::
+
+
+:::{tip}
+
+This example shows a quirk of changing configurations in the middle of
+processing an EmPy document; the prefix changes from a `@` to a `$`
+by the end of the first statement markup, so a `$` and a newline is
+required to suppress the trailing newline; a `@` would have been sent
+to the output unchanged since it is no longer the prefix. Use
+[configuration files](#configuration-files) to avoid issues like this,
+as they are processed before any EmPy document or commands such as
+`-P`/`--preprocess=FILENAME`.
+
+:::
+
+
+#### Configuration files
+
+**Configuration files** are snippets of Python (not EmPy) code which
+can be executed under an EmPy system to modify the current
+configuration. By convention they have the extension .conf. though
+this is not a requirement. Configuration files are processed before
+any expansion begins and are specified with the `-c`/`--config-file=FILENAME` (_environment variable:_ `EMPY_CONFIG`) command line option; a list of configuration files can be
+specified with a `:` delimiter (`;` on Windows); the delimiter can be
+specified with `--path-separator` (_configuration variable:_ `pathSeparator`). A nonexistent
+configuration file specified in this way is an error unless
+`-C`/`--ignore-missing-config` is specified.
+
+When a configuration file is processed, its contents are executed in a
+Python (not EmPy) interpreter and then any resulting variable
+assignments are assigned to the configuration instance. So:
+
+``````python
+prefix = '$'
+``````
+
+
+is a simple configuration file which will change the EmPy prefix to
+`$`.
+
+Any resulting variable beginning with an underscore will be ignored.
+Thus these variables can be used as auxiliary variables in the
+configuration file. For example, this configuration file will define
+custom emojis for the numbered keycaps:
+
+``````python
+emojis = {}
+for _x in range(10):
+ emojis[str(_x)] = '{}\ufe0f\u20e3'.format(_x)
+``````
+
+
+Finally, when a configuration file is processed, the current
+configuration instance is presented as a variable named `_` (this can
+be changed with `--config-variable=NAME` (_configuration variable:_ `configVariableName`)). The
+following example does the same as the previous example but uses the
+dedicated variable:
+
+``````python
+_.emojis.update(((str(_x), '{}\ufe0f\u20e3'.format(_x)) for _x in range(10)))
+``````
+
+
+:::{tip}
+
+To make a set of configuration files automatic loaded by EmPy, use the
+`EMPY_CONFIG` environment variable in your startup
+shell:
+
+<pre class="shell"><b><i>% export EMPY_CONFIG=~/path/to/default.conf</i></b>
+</pre>
+
+
+To make a more general set of _options_ available, set `EMPY_OPTIONS`.
+
+:::
+
+
+#### Configuration variables
+
+The following configuration variables exist with the given types and
+their corresponding command line options and environment variables.
+Default values are shown in brackets. When a corresponding command
+line option exists, See the [command line
+options](#command-line-options) for more detailed information.
+
+`name: str` [`default`]
+
+: The name of this configuration. It is for organizational purposes
+ and is not used directly by the EmPy system.
+
+`notes` [`None`]
+
+: Arbitrary data about this configuration. It can be anything from an
+ integer to a string to a dictionary to a class instance, or its
+ default, `None`. It is for organizational purposes and is not used
+ directly by the EmPy system.
+
+`prefix: str` (_command line option:_ `-p`/`--prefix=CHAR`, _environment variable:_ `EMPY_PREFIX`) [`@`]
+
+: The prefix the interpreter is using to delimit EmPy markup. Must be
+ a single Unicode code point (character).
+
+`pseudomoduleName: str` (_command line option:_ `-m`/`--pseudomodule=NAME`, _environment variable:_ `EMPY_PSEUDO`) [`empy`]
+
+: The name of the pseudomodule for this interpreter.
+
+`verbose: bool` [`False`]
+
+: If true, print debugging information before processing each EmPy
+ token.
+
+`rawErrors: bool` (_command line option:_ `-r`/`--raw-errors`, _environment variable:_ `EMPY_RAW_ERRORS`) [`False`]
+
+: If true, print a Python traceback for every exception that is thrown.
+
+`exitOnError: bool` [`True`]
+
+: If true, exit the EmPy interpreter after an error occurs. If false,
+ processing will continue despite the error.
+
+`ignoreErrors: bool` [`False`]
+
+: If true, all errors are ignored by the EmPy interpreter. Setting
+ this to true also implies `exitOnError` is false.
+
+`contextFormat: str` (_command line option:_ `--context-format`) [`%(name)s:%(line)d:%(column)d`]
+
+: The string format to use to render contexts. EmPy will
+ automatically determine whether or not it should use the `%`
+ operator or the `str.format` method with this format. See [Context
+ formatting](#context-formatting) for more details.
+
+`goInteractive: bool` (_command line option:_ `-i`/`--interactive`, _environment variable:_ `EMPY_INTERACTIVE`) [`False`]
+
+: When done processing the main EmPy document (if any), go into
+ interactive mode by running a REPL loop with `sys.stdin`. If such
+ document is specified (_i.e._, EmPy is invoked with no arguments),
+ go into interactive mode as well.
+
+`deleteOnError: bool` (_command line option:_ `-d`/`--delete-on-error`, _environment variable:_ `EMPY_DELETE_ON_ERROR`) [`False`]
+
+: If an output file is chosen (_e.g._, with `-o`/`--output=FILENAME` or one
+ of the other such options) and an error occurs, delete the output
+ file. If this is set to true with output set to `sys.stdout`, a
+ ConfigurationError will be raised.
+
+`doFlatten: bool` (_command line option:_ `-f`/`--flatten`, _environment variable:_ `EMPY_FLATTEN`) [`False`]
+
+: Flatten the contents of the `empy`
+ pseudomodule into the globals rather than having them all under the
+ pseudomodule name.
+
+`useProxy: bool` (_command line option:_ `-n`/`--no-proxy`, _environment variable:_ `EMPY_NO_PROXY`) [`True`]
+
+: If true, install a proxy object for `sys.stdout`. This should be
+ true if any output is being done via `print` or `sys.stdout.write`.
+
+`relativePath: bool` (_command line option:_ `-l`/`--relative-path`) [`False`]
+
+: If true, the directory of the EmPy script's path will be prepended
+ to Python's `sys.path`.
+
+`buffering: int` (_command line option:_ `-b`/`--buffering`, _environment variable:_ `EMPY_BUFFERING`) [`16384`]
+
+: Specify the buffering for the input and output files.
+
+`noCallbackIsError: bool` [`True`]
+
+: By default, not having a custom callback set when using custom
+ markup (`@<...>`) is an error. If this is set to true, that error
+ will be suppressed.
+
+`replaceNewlines: bool` [`True`]
+
+: If true, newlines in emoji names, Unicode character name escape
+ markup, and code evaluation will be changed to spaces. This can
+ help when writing EmPy with a word-wrapping editor.
+
+`ignoreBangpaths: bool` [`True`]
+
+: If true, a bangpath (the first line of a file which starts with
+ `#!`) will be treated as an EmPy comment, allowing the creation of
+ EmPy executable scripts. If false, it will not be treated specially
+ and will be rendered to the output.
+
+`noneSymbol: Optional[str]` (_command line option:_ `--none-symbol`) [`None`]
+
+: When an EmPy expansion evaluates to None (_e.g._, `@(None)`), this
+ is the string that will be rendered to the output stream. If set to
+ `None` (the default), no output will be rendered.
+
+`missingConfigIsError: bool` [`True`]
+
+: If a configuration file is specified with `-c`/`--config-file=FILENAME` but
+ does not exist, if this variable is true an error will be raised.
+
+`pauseAtEnd: bool` [`False`]
+
+: When done processing EmPy files, read a line from `sys.stdin` before
+ exiting the interpreter. This can be useful when testing under
+ consoles on Windows.
+
+`startingLine: int` (_command line option:_ `--starting-line`) [`1`]
+
+: The line to start with in contexts.
+
+`startingColumn: int` (_command line option:_ `--starting-column`) [`1`]
+
+: The column to start with in contexts.
+
+`significatorDelimiters: tuple` [`('__', '__')`]
+
+: A 2-tuple of strings representing the prefix and suffix to add to
+ significator names in order to determine what name to give them in
+ the globals.
+
+`emptySignificator: object` [`None`]
+
+: The default value to use for non-stringized significators.
+
+`autoValidateIcons: bool` [`True`]
+
+: When icons are used with a custom dictionary, a preprocessing phase
+ needs to be done to make sure that all icon starting substrings are
+ marked in the `icons` dictionary. If this variable is false, this
+ extra processing step will not be done; this is provided if the user
+ wants to specify their own properly-validated icons dictionary and
+ wishes to avoid a redundant step.
+
+`emojiModuleNames: list` (_command line option:_ `--emoji-modules`) [`['emoji', 'emojis', 'emoji_data_python', 'unicodedata']`]
+
+: The list of names of supported emoji modules that the EmPy system
+ will attempt t use at startup.
+
+`emojiNotFoundIsError: bool` [`True`]
+
+: If true, a non-existing emoji is an error.
+
+`useBinary: bool` (_command line option:_ `-u`/`--binary`/`--unicode`, _environment variable:_ `EMPY_BINARY`) [`False`]
+
+: If true, open files in binary mode.
+
+`inputEncoding: str` (_command line option:_ `--input-encoding=E`, _environment variable:_ `EMPY_INPUT_ENCODING`) [`utf-8`]
+
+: The file input encoding to use. This needs to be set before files
+ are opened to take effect.
+
+`outputEncoding: str` (_command line option:_ `--output-encoding=E`, _environment variable:_ `EMPY_OUTPUT_ENCODING`) [`utf-8`]
+
+: The file output encoding to use. This needs to be set before files
+ are opened to take effect.
+
+`inputErrors: str` (_command line option:_ `--input-errors=E`, _environment variable:_ `EMPY_INPUT_ERRORS`) [`strict`]
+
+: the file input error handler to use. This needs to be set before files
+ are opened to take effect.
+
+`outputErrors: str` (_command line option:_ `--output-errors=E`, _environment variable:_ `EMPY_OUTPUT_ERRORS`) [`strict`]
+
+: The file output error handler to use. This needs to be set before files
+ are opened to take effect.
+
+`normalizationForm: str` (_command line option:_ `-z`/`--normalization-form=F`) [`NFKC`]
+
+: The normalization form to use when applying diacritic combiners.
+ Set to `None` or `''` in order to skip normalization.
+
+`autoPlayDiversions: bool` (_command line option:_ `--no-auto-play-diversions`) [`True`]
+
+: If diversions are extant when an interpreter is ready to exist, if
+ this variable is true then those diversions will be undiverted to
+ the output stream in lexicographical order by name.
+
+`expandUserConstructions: bool` [`True`]
+
+: If true, when processing configuration files, call
+ `os.path.expanduser` on each filename to expand `~` and `~user`
+ constructions.
+
+`configVariableName: str` (_command line option:_ `--config-variable=NAME`) [`_`]
+
+: When processing configuration files, the existing configuration
+ object can be referenced as a variable. This indicates its name.
+
+`successCode: int` (_command line option:_ `--success-code=N`) [`0`]
+
+: The exit code to return when a processing is successful.
+
+`failureCode: int` (_command line option:_ `--failure-code=N`) [`1`]
+
+: The exit code to return when an error occurs during processing.
+
+`unknownCode: int` (_command line option:_ `--unknown-code=N`) [`2`]
+
+: The exit code to return when a configuration error is found (and
+ processing never starts).
+
+`checkVariables: bool` (_command line option:_ `--no-check-variables`) [`True`]
+
+: If true, configuration variables will be checked for existing and
+ proper type n assignment.
+
+`pathSeparator: str` (_command line option:_ `--path-separator`) [`;` (Windows), `:` (others)]
+
+: The path separator to use when specifying multiple filenames with
+ `-c`/`--config-file=FILENAME`. Defaults to `;` on Windows and `:` on other
+ platforms.
+
+`controls: dict` [`{...}`]
+
+: The controls dictionary used by the [named escape
+ markup](#named-escape-markup).
+
+`diacritics: dict` [`{...}`]
+
+: The diacritic combiners dictionary used by the [diacritic
+ markup](#diacritic-markup).
+
+`icons: dict` [`{...}`]
+
+: The icons dictionary used by the [icon markup](#icon-markup).
+
+`emojis: dict` [`{...}`]
+
+: The custom emojis dictionary which is referenced first by the [emoji
+ markup](#emoji-markup). Defaults to an empty dictionary.
+
+:::{seealso}
+
+The list of configuration variables is available in the `variables` help
+topic and is summarized
+[here](http://www.alcyone.com/software/empy/HELP.html#configuration-variables-summary).
+
+:::
+
+:::{note}
+
+Configuration objects were introduced in EmPy version 4.0; previously
+an underused options dictionary was introduced in version 2.2.2.
+
+:::
+
+
+#### Configuration methods
+
+The following methods are supported by configuration instances:
+
+`__init__(**kwargs)`
+
+: The constructor. Takes a set of keyword arguments that are then set
+ as attributes in the configuration instance. So
+
+ ```python
+ config = em.Configuration(prefix='$')
+ ```
+
+ is a shorter form of
+
+ ```python
+ config = em.Configuration()
+ config.prefix = '$'
+ ```
+
+`isInitialized() -> bool`
+
+: Has this instance been initialized? Before initialization, no
+ typechecking is done even if `checkVariables` is set.
+
+`check(inputFilename, outputFilename)`
+
+: Check the file settings against these filenames and raise a
+ `ConfigurationError` is there appears to be an inconsistency.
+
+`has(name) -> bool`
+
+: Is this name an existing configuration variable?
+
+`get(name, default=None) -> bool`
+
+: Get the value of this configuration variable or return this default
+ if it does not exist.
+
+`set(name, value)`
+
+: Set the configuration variable to the given value.
+
+`update(**kwargs)`
+
+: Set a series of configuration variables via a set of keyword
+ arguments.
+
+`clone(deep=False) -> Configuration`
+
+: Clone this configuration and return it. If `deep` is true, make it
+ a deep copy.
+
+`run(statements)`
+
+: Execute a series of configuration commands.
+
+`load(filename, required=None)`
+
+: Load and execute a configuration file. If `required` is true, raise
+ an exception; if false, ignore; if `None`, use the default for this
+ configuration.
+
+`path(path, required=None)`
+
+: Load and execute one or more configuration files separated by the
+ path separator. `required` argument is the same as for `load`
+ above.
+
+`hasEnvironment(name) -> bool`
+
+: Is the given environment variable defined, regardless of its value?
+
+`environment(name, default=None, blank=None)`
+
+: Get the value of the environment variable. If it is not defined,
+ return `default`; if it is defined but is empty, return `blank`.
+
+`hasDefaultPrefix() -> bool`
+
+: Is the `prefix` configuration variable set to the
+ default?
+
+`has{Full|No|Line|Fixed}Buffering() -> bool`
+
+: Is buffering set to full, none, line, or some fixed value,
+ respectively?
+
+`createFactory([tokens]) -> Factory`
+
+: Create a token factory from the list of token classes and return it.
+ If `tokens` is not specified, use the default list.
+
+`adjustFactory()`
+
+: Adjust an existing factory to take into account a non-default prefix.
+
+`getFactory([tokens], [force])`
+
+: Get a factory, creating one if one has not yet been created, with
+ the given `tokens` list (if not specified, a default list will be
+ used). If `force` is true, then create a new one even if one
+ already exists.
+
+`resetFactory()`
+
+: Clear the current factory, if any.
+
+`hasBinary() -> bool`
+
+: Is binary (formerly called Unicode) support enabled?
+
+`enableBinary([major, minor])`
+
+: Enable binary support, conditionally if `major` and `minor` (the
+ major and minor versions of Python) are specified and binary support
+ is needed for this version of Python.
+
+`disableBinary()`
+
+: Turn off binary/Unicode support.
+
+`isDefaultEncodingErrors([encoding, errors, asInput]) -> bool`
+
+: Are both the file encoding and file error handler the default?
+ Check for input if `asInput` is true, otherwise check for output.
+
+`getDefaultEncoding([default]) -> str`
+
+: Get the current default encoding, overriding with `default` if
+ desired.
+
+`open(filename, mode=None, buffering=-1, encoding=None, errors=None, expand=None) -> file`
+
+: The main wrapper around the `open`/`codecs.open` call, allowing for
+ seamless file opening in both binary and non-binary mode across all
+ supported Python versions.
+
+`significatorReString() -> str`
+
+: Return a regular expression string that will match significators in
+ EmPy code with this configuration's prefix.
+
+ :::{hint}
+
+ It can be used in Python like this:
+
+ ```python
+ data = open('script.em', 'r').read()
+ for result in empy.config.significatorRe().findall(data):
+ string2, key2, value2, string1, key1, value1 = result
+ if key1:
+ print("Single line significator: {} = {}{}".format(
+ key1, value1, ' (stringized)' if string1 else ''))
+ else: # key2
+ print("Multi-line significator: {} = {}{}".format(
+ key2, value2, ' (stringized)' if string2 else ''))
+ ```
+
+ :::
+
+`significatorRe([flags]) -> re.Pattern`
+
+: Return a compiled regular expression pattern object for this
+ configuration's prefix. Override the `re` `flags` if desired.
+
+`significatorFor(key) -> str`
+
+: Return the significator variable name for this significator key.
+
+`setContextFormat(rawFormat)`
+
+: Set the context format for this configuration. See [context
+ formatting](#context-formatting).
+
+`renderContext(context) -> str`
+
+: Render the given context using the existing context format string.
+
+`calculateIconsSignature() -> tuple`
+
+: Calculate the icons signature to try to detect any accidental
+ changes.
+
+`signIcons()`
+
+: Calculate the icons signature and update the configuration with it.
+
+`transmogrifyIcons([icons])`
+
+: Process the icons dictionary and make sure any keys' prefixes are
+ backfilled with `None` values. This is necessary for the
+ functioning of the [icon markup](#icon-markup). This method will be
+ called automatically unless `autoValidateIcons` is
+ false.
+
+`validateIcons([icons])`
+
+: Check whether the icons have possibly changed and transmogrify them
+ if necessary.
+
+`initializeEmojiModules([moduleNames])`
+
+: Scan for existing emoji modules and set up the appropriate internal
+ data structures. Use the list of module names in the configuration
+ if `moduleNames` is not specified.
+
+`substituteEmoji(text) -> str`
+
+: Perform emoji substitution with the detected emoji modules.
+
+`isSuccessCode(code) -> bool`
+
+: Is this exit code a success code?
+
+`isExitError(error) -> bool`
+
+: Is this exception instance an exit error rather than a real error?
+
+`errorToExitCode(error) -> int`
+
+: Return an appropriate exit code for this error.
+
+`isNotAnError(error) -> bool`
+
+: Does this exception instance not represent an actual error?
+
+`formatError(error[, prefix, suffix]) -> str`
+
+: Return a string representing the details of the given exception
+ instance, with an optional prefix and suffix.
+
+:::{seealso}
+
+The list of configuration methods is available in the `methods` help
+topic and is summarized
+[here](http://www.alcyone.com/software/empy/HELP.html#configuration-methods-summary).
+
+:::
+
+
+### Error handling
+
+#### Error dispatchers
+
+When an error occurs in an EmPy system, first an **error dispatcher**
+is invoked. The purpose of the dispatcher is to determine at a
+high-level what should be done about the error. A dispatcher is a
+zero-argument callable which primarily determines whether the error
+should be handled by the running interpreter, whether it should be
+raise to the parent caller rather than handled by the interpreter, or
+some other custom behavior.
+
+When specified to the [`Interpreter` constructor](#constructor), one
+of the high-level interpreter methods (_e.g._, `file` or `string`), it
+can take on a few special values:
+
+| Value | Meaning | Corresponding method |
+| --- | --- | --- |
+| `None` | Use interpreter default | -- |
+| `True` | Interpreter should handle error | `dispatch` |
+| `False` | Interpreter should reraise error | `reraise` |
+
+:::{note}
+
+For standalone interpreters and its high-level methods, the default
+dispatcher is `True` (`dispatch`); that is, the interpeter will handle
+the error itself. When calling the `expand` interpreter method or the
+global `expand` function, the dispatcher is `False` (`reraise`); in
+other words, calls to `expand` will result in any occurring errors
+being raised to the caller rather than handled by the interpteter.
+
+:::
+
+
+#### Error handlers
+
+Once an error is dispatched to the interpteter, it is handled by an
+**error handler**. An error handler is a callable object that will
+respond to the error and take any necessary action. If no
+user-specified error handler is set, the default error handler is
+used, which prints a formatted EmPy error message to `sys.stderr`.
+
+An error handler is a callable object with the following signature:
+
+`handler(type, error, traceback) -> bool`
+
+It takes the error type, the error instance, and the traceback object
+corresponding to an exception (the return value of `sys.exc_info()`)
+and returns an optional Boolean. If the return value is true, the
+default handler will _also_ be invoked after the error handler is
+called. (Not explicitly returning anything will implicitly return
+`None`, which is a false value.)
+
+The current error that the interpreter has encountered is set in the
+interpreter's `error` attribute (with `None` indicating no error).
+The error handler can manually set this attribute to `None` to clear
+the error if desired.
+
+After the error handler(s) have been called, the interpreter will then
+decide how to resolve the error. If the `error` attribute of the
+interpreter is still non-`None` and the configuration variable
+`exitOnError` is true (option: `-k`/`--keep-going`), the
+interpreter will exit. If the `error` attribute is `None`, it will
+continue running.
+
+If the `ignoreErrors` configuration variable (option:
+`-e`/`--ignore-errors`) is true, then no error dispatchers or error
+handlers will be called.
+
+
+## Reference
+
+The following reference material is available:
+
+### Getting version and debugging information
+
+To print the version of EmPy you have installed, run:
+
+<pre class="shell"><b><i>% em.py -V # or: --version</i></b>
+Welcome to EmPy version 4.0.1.</pre>
+
+To print additional information including the Python implementation
+and version, operating system, and machine type, run:
+
+<pre class="shell"><b><i>% em.py -W # or: --info</i></b>
+Welcome to EmPy version 4.0.1, in CPython/3.10.12, on Linux (POSIX), with x86_64.</pre>
+
+For diagnostic details (say, to report a potential problem to the
+developer), run:
+
+<pre class="shell"><b><i>% em.py -Z # or: --details</i></b>
+Welcome to EmPy version 4.0.1, in CPython/3.10.12, on Linux (POSIX), with x86_64.
+Details:
+- basic/implementation: CPython
+- basic/machine: x86_64
+- basic/os: POSIX
+- basic/system: Linux
+- basic/version: 3.10.12
+...</pre>
+
+
+### Examples and testing
+
+For quick examples of EmPy code, check out the examples throughout
+this document. For a more expansive tour of examples illustrating
+EmPy features, check out tests/sample/sample.em. For a real-world
+example, check out README.md.em, which is the EmPy source file from
+which this documentation is generated.
+
+EmPy has an extensive testing system. (If you have EmPy installed via
+an operating system package that does not include the test system and
+you wish to use it, [download the tarball](#getting-the-software).)
+
+EmPy's testing system consists of the shell script test.sh and two
+directories: tests and suites. The tests directory contains the
+unit/system tests, and the suites directory contains files with lists
+of tests to run. The test.sh shell script will run with any modern
+Bourne-like shell.
+
+Tests can be run changing to the directory where test.sh and both the
+tests and suites directories are located, and then executing
+`./test.sh` followed by the tests desired to be run following on the
+command line. For example, this runs a quick test:
+
+<pre class="shell"><b><i>% ./test.sh tests/sample/sample.em</i></b>
+tests/sample/sample.em (python3) [PASS]
+
+PASSES: 1/1
+All tests passed (python3).</pre>
+
+Specifying a directory will run all the tests contained in that
+directory and all its subdirectories:
+
+<pre class="shell"><b><i>% ./test.sh tests/common/trivial</i></b>
+tests/common/trivial/empty.em (python3) [PASS]
+tests/common/trivial/long.em (python3) [PASS]
+tests/common/trivial/medium.em (python3) [PASS]
+tests/common/trivial/short.em (python3) [PASS]
+tests/common/trivial/short_no_newline.em (python3) [PASS]
+
+PASSES: 5/5
+All tests passed (python3).</pre>
+
+:::{warning}
+
+The tests directory contains a superset of all tests for Python
+versions, so running all the tests with `./test.sh tests` will
+generate test failures.
+
+:::
+
+Suites can be run by using the `@` character before the filename. A
+suite is a list of tests, one per line, to run:
+
+<pre class="shell"><b><i>% cat suites/default</i></b>
+# Run tests for Python versions from 3.0 up.
+tests/common
+tests/modern
+tests/python3
+tests/sample</pre>
+<pre class="shell"><b><i>% ./test.sh @suites/default</i></b>
+tests/common/callbacks/deregister.em (python3) [PASS]
+tests/common/callbacks/deregister_twice.em (python3) [PASS]
+tests/common/callbacks/get_none.em (python3) [PASS]
+<i>...</i>
+PASSES: 393/393
+All tests passed (python3).</pre>
+
+To test a version of Python other than the default (_i.e._, that is, a
+Python 3._x_ interpreter named `python3`), specify it with the
+`-p` option to the test script and use that version's test suite. To
+test CPython 2.7, for instance:
+
+<pre class="shell"><b><i>% ./test.sh -p python2.7 @suites/python2.7</i></b>
+tests/common/callbacks/deregister.em (python2.7) [PASS]
+tests/common/callbacks/deregister_twice.em (python2.7) [PASS]
+tests/common/callbacks/get_none.em (python2.7) [PASS]
+<i>...</i></pre>
+
+Suites for all supported interpreters and versions are provided. For
+example, if you have PyPy 2.7 installed:
+
+<pre class="shell"><b><i>% ./test.sh -p pypy2.7 @suites/pypy2.7</i></b>
+tests/common/callbacks/deregister.em (pypy2.7) [PASS]
+tests/common/callbacks/deregister_twice.em (pypy2.7) [PASS]
+tests/common/callbacks/get_none.em (pypy2.7) [PASS]
+<i>...</i></pre>
+
+To only report errors ("quiet mode"), use the `-q` option:
+
+<pre class="shell"><b><i>% ./test.sh -q @suites/default</i></b>
+PASSES: 393/393
+All tests passed (python3).</pre>
+
+For more information about the testing tool, run:
+
+<pre class="shell"><b><i>% ./test.sh -h # or: --help</i></b>
+Usage: ./test.sh [<option>...] [--] (<file> | <directory> | @<suite>)...
+
+Run one or more EmPy tests, comparing the results to exemplars, and
+return an exit code indicating whether all tests succeeded or whether
+there were some failures. If no tests are specified, this help is
+displayed. Test filenames, directory names, and suite names cannot
+contain spaces.
+
+...</pre>
+
+:::{note}
+
+A simple benchmark test system was introduced in EmPy version 2.1, and
+was expanded to a full unit and system test suites for all supported
+versions of Python in EmPy version 4.0.
+
+:::
+
+
+### Embedding EmPy
+
+EmPy can be easily embedded into your Python programs. Simply ensure
+that the em.py file is available in the `PYTHONPATH` and import `em`
+as a module:
+
+```python
+import em
+
+print(em)
+```
+
+To embed an interpreter, create an instance of the `Interpreter`
+class. The interpreter constructor requires keyword arguments, all
+with reasonable defaults; [see here for the list](#constructor). One
+important argument to an interpreter is a
+[configuration](#configuration), which, if needed, should be
+constructed first and then passed into the interpreter. If no
+configuration is specified, a default instance will be created and
+used:
+
+```python
+import em
+
+config = em.Configuration(...)
+interp = em.Interpreter(config=config, ...)
+```
+
+Then call interpreter methods on it such as `write`, `string`,
+`evaluate`, `execute`, `expand`, and so on. The full list of
+interpreter methods is [here](#interpreter-methods). Exceptions that
+occur during processing will be handled by the interpreter's error
+handler.
+
+:::{important}
+
+When you create an interpreter, you must call its `shutdown` method
+when you are done. This is required to remove the proxy on
+`sys.stdout` that EmPy requires for proper operation and restore your
+Python environment to the state it was before creating the
+interpreter. This can be accomplished by creating the interpreter in
+a `with` statement -- interpreters are also context managers -- or by
+creating it and shutting it down in a `try`/`finally` statement.
+
+This is not needed when calling the `expand` global function; it
+creates and shuts down an ephemeral interpreter automatically.
+
+:::
+
+Calling the interpreter's `shutdown` can be handled with either with a
+`try`/`finally` statement or a `with` statement:
+
+```python
+import em
+
+interp = em.Interpreter(...)
+try:
+ ... do some things with the interpreter ...
+finally:
+ interp.shutdown()
+
+# or ...
+
+with em.Interpreter(...) as interp:
+ ... do other things with the interpreter ...
+```
+
+:::{warning}
+
+If you receive a `ConsistencyError` mentioning the proxy when quitting
+your program, you are likely not calling the `shutdown` method on the
+interpreter. Make sure to call `shutdown` so the interpreter can
+clean up after itself.
+
+:::
+
+There is also a global `expand` function which will expand a single
+string, creating and destroying an ephemeral interpreter to do so.
+You can use this function to do a one-off expansion of, say, a large
+file:
+
+```python
+import em
+
+data = open('tests/sample/sample.em').read()
+print(em.expand(data))
+```
+
+If an exception occurs during `expand` processing, the exception will
+be raised to the caller.
+
+
+### Modules
+
+A fully-functional EmPy system contains the following modules and files.
+
+
+#### `empy` pseudomodule
+
+The pseudomodule is not an actual module, but rather the instance of
+the running EmPy interpreter exposed to the EmPy system. It is
+automatically placed into the interpreter's globals and cannot be
+imported explicitly. See
+[Pseudomodule/interpreter](#pseudomodule-interpreter) for details.
+
+
+#### `em` module
+
+The primary EmPy module. It contains the `Configuration` and
+`Interpreter` classes as well as all supporting logic. An EmPy system
+can be functional with only this module present if needed.
+
+It also includes the following global functions:
+
+{#details}
+`details(level, [prelim, postlim, file])`
+
+: Write details about the running system to the given file, which
+ defaults to `sys.stdout`. The `level` parameter is an attribute of
+ the `em.Version` class (effectively an enum). `prelim` and
+ `postlim` indicate preliminary and postliminary text to output
+ before and after the details (and have reasonable defaults).
+
+ :::{note}
+
+ This function requires the `emlib` to be installed to function most
+ effectively.
+
+ :::
+
+{#expand}
+`expand(data, **kwargs) -> str`
+
+: Create a ephemeral interpreter with the given kwargs, expand data,
+ shut the interpreter down, and then return the expansion. The
+ function takes the same keyword arguments as the [`Interpreter`
+ constructor](#constructor), with the following additions:
+
+ {#expand-arguments}
+ | Argument | Meaning | Default |
+ | --- | --- | --- |
+ | `dispatcher` | Dispatch errors or raise to caller? | `False` |
+ | `locals` | The locals dictionary | `{}` |
+ | `name` | The context filename | `"<expand>"` |
+
+ If the markup that is being expanded causes an exception to be
+ raised, by default the exception will be let through to the caller.
+
+ :::{important}
+
+ As with the [`Interpreter` constructor](#constructor), the order of
+ the `expand` arguments has changed over time and is subject to
+ change in the future, so you need to use keyword arguments to
+ prevent any ambiguity, _e.g._:
+
+ ```python
+ myConfig = em.Configuration(...)
+ myGlobals = {...}
+ myOutput = open(...)
+ result = em.expand(source, config=myConfig, globals=myGlobals, ...)
+ ```
+
+ Attempts have been made to make the `expand` function as backward
+ compatible (to 3._x_) as feasible, but some usages are ambiguous or
+ do not have direct mappings to configurations. A
+ `CompatibilityError` will be raised in these cases; if you encounter
+ this, redesign your use of `expand` to be compatible with [the
+ modern usage](#expand). In particular, in 3._x_, additional keyword
+ arguments were used to indicate the locals dictionary; in 4._x_,
+ keyword arguments are used for all arguments so the locals
+ dictionary must be specified as a distinct `locals` keyword
+ argument:
+
+ ```python
+ myGlobals = {...}
+ myLocals = {...}
+ result = em.expand(source, globals=myGlobals, locals=myLocals)
+ ```
+
+ :::
+
+ :::{warning}
+
+ Not all of the `Interpreter` constructor arguments are compatible
+ with the `expand` function. The `filters`, `input` and `output`
+ arguments are immediately overridden by the inherent nature of the
+ ephemeral interpreter and so would not behave as expected. Thus, if
+ they are specified, a `ConfigurationError` will be raised. For more
+ detailed configuration of an interpreter, it's better to create one
+ yourself rather than rely on `expand`.
+
+ :::
+
+{#invoke}
+`invoke(args, **kwargs)`
+
+: Invoke the EmPy system with the given command line arguments
+ (`sys.argv[1:]`, not `sys.argv`) and optional strting settings.
+ This is the entry point used by the main EmPy function. The
+ remaining keyword arguments correspond to the [`Interpreter`
+ constructor](#constructor) arguments.
+
+ :::{warning}
+
+ Since the `invoke` function configures and manages the lifetime of
+ an `Interpreter`, not all of the constructor arguments are
+ compatible with it. Specifically, the `filespec` and `immediately`
+ arguments need to be managed by the function and so specifying a
+ starting value is nonsensical. Thus, if they are specified, a
+ `ConfigurationError` will be raised.
+
+ :::
+
+
+#### `emlib` module
+
+The EmPy supporting library. It contains various support classes,
+including the base classes `Filter` and `Hook` to assist in creating
+this supporting functionality.
+
+
+#### `emhelp` module
+
+The EmPy help system. It can be accessed from the main executable
+with the `-h`/`--help` and `-H`/`--topics=TOPICS` command
+line options. If the emlib module is not available to the executable,
+the help system will return an error.
+
+
+#### `emdoc` module
+
+The EmPy documentation system, used to create this document.
+
+
+### Using EmPy with build tools
+
+If you're using EmPy to process documents within a build system such
+as GNU Make or Ninja, you'll want to use the `-o`/`--output=FILENAME` (or
+`-a`/`--append=FILENAME`) and `-d`/`--delete-on-error` options together. This
+will guarantee that a file will be output (or appended) to a file
+without shell redirection, and that the file will be deleted if an
+error occurs. This will prevent errors from leaving a partial file
+around which subsequent invocations of the build system will mistake
+as being up to date. The invocation of EmPy should look like this
+(the `--` is not required if the input filename never starts with a
+dash):
+
+```shell
+em.py -d -o $output -- $input
+```
+
+For GNU Make:
+
+````make
+
+EMPY ?= em.py
+EMPY_OPTIONS ?= -d
+
+%: %.em
+ $(EMPY) $(EMPY_OPTIONS) -o $@ -- $<
+````
+
+For Ninja:
+
+```ninja
+empy = em.py
+empy_options = -d
+
+rule empy
+ command = $empy $empy_options -o $out -- $in
+```
+
+
+### Context formatting
+
+**Contexts** are objects which contain the filename, the line number,
+the column number, and the character (Unicode code point) number to
+record the location of an EmPy error during processing.
+
+These are formatted into human-readable strings with a **context
+format**, a string specifiable with `--context-format` (_configuration variable:_ `contextFormat`). A few different mechanisms for formatting contexts are
+available:
+
+| Mechanism | Description | Example
+| --- | --- | --- |
+| format | Use the `str.format` method | `{name}:{line}:{column}` |
+| operator | Use the `%` operator | `%(name)s:%(line)d:%(column)d` |
+| variable | Use `$` variables | `$NAME:$LINE:$COLUMN` |
+
+The default context format is `%(name)s:%(line)d:%(column)d` and
+uses the operator mechanism for backward compatibility.
+
+When a context format is set, EmPy will attempt to detect which of the above mechanisms is needed:
+
+| Mechanism | Criteria |
+| --- | --- |
+| format | string begins with `format:` or does not contain a `%` |
+| operator | string begins with `operator:` or contains a `%` |
+| variable | string begins with `variable:` |
+
+
+### Data flow
+
+**input ⟶ interpreter ⟶ diversions ⟶ filters ⟶ output**
+
+Here, in summary, is how data flows through a working EmPy system:
+
+1. Input comes from a source, such as an .em file on the command line,
+ `sys.stdin`, or via an `empy.include` statement.
+
+2. The interpreter processes this material as it comes in,
+ processing EmPy expansions as it goes.
+
+3. After interpretation, data is then sent through the diversion
+ layer, which may allow it directly through (if no diversion is
+ in progress) or defer it temporarily. Diversions that are
+ recalled initiate from this point.
+
+4. Any filters in place are then used to filter the data and
+ produce filtered data as output.
+
+5. Finally, any material surviving this far is sent to the output
+ stream. That stream is `sys.stdout` by default, but can be changed
+ with the `-o`/`--output=FILENAME` or `-a`/`--append=FILENAME` options.
+
+6. If an error occurs, execute the error handler (which by default
+ prints an EmPy error) If the `-r`/`--raw-errors` option is
+ specified, then print a full Python traceback. If
+ `-k`/`--keep-going` is specified, continue processing rather than
+ exit; otherwise halt.
+
+7. On unsuccessful exit, if `-d`/`--delete-on-error` is specified, delete any
+ specified output file.
+
+
+### Glossary
+
+The following terms with their definitions are used by EmPy:
+
+*callback*
+
+: The user-provided callback which is called when the custom markup
+ `@<...>` is encountered.
+
+*command*
+
+: A processing step which is performed before or after main document
+ processing. Examples are `-D`/`--define=DEFN`, `-F`/`--file=FILENAME` or
+ `-P`/`--preprocess=FILENAME`.
+
+*configuration*
+
+: An object encapsulating all the configurable behavior of an
+ interpreter which passed into interpreter on creation.
+ Configurations can be shared between multiple interpreters.
+
+*context*
+
+: An object which tracks the location of the parser in an EmPy file
+ for tracking and error reporting purposes.
+
+*control markup*
+
+: A markup used to direct high-level control flow within an EmPy
+ session. Control markups are expressed with the `@[...]` notation.
+
+*custom*
+
+: The custom markup invokes a callback which is provided by the user,
+ allowing any desired behavior. Custom markup is `@<...>`.
+
+*diacritic*
+
+: A markup which joins together a letter and one or more combining
+ characters from a dictionary in the configuration and outputs it.
+ Diacritic markup is `@^...`.
+
+*dispatcher*
+
+: An error dispatcher determines whether to dispatch the error to the
+ interpreter's error handler (`True`), to reraise the error to the
+ caller (`False`), or something else.
+
+*diversion*
+
+: A process by which output is deferred, and can be recalled later on
+ demand, multiple times if desired.
+
+*document*
+
+: An EmPy file containing EmPy markup to expand.
+
+*emoji*
+
+: A markup which looks up a Unicode code point by name via a
+ customizable set of installable emoji modules, or via a dictionary
+ in the configuration. Emoji markup is `@:...:`.
+
+*error*
+
+: An exception thrown by a running EmPy system. When these occur,
+ they are dispatched by an error dispatcher and then (possibly)
+ passed to an error handler.
+
+*escape*
+
+: A markup designed to expand to a single (often non-printable)
+ character, similar to escape sequences in C or other languages.
+ Escape markup is `@\...`.
+
+*expansion*
+
+: The process of processing EmPy markups and producing output.
+
+*expression*
+
+: An expression markup represents a Python expression to be evaluated,
+ and replaced with the `str` of its value. Expression markup is
+ `@(...)`.
+
+*file*
+
+: An object which exhibits a file-like interface (methods such as
+ `write` and `close`).
+
+*filter*
+
+: A file-like object which can be chained to other filters or the
+ final stream, and can buffer, alter, or manipulate in any way the
+ data sent. Filters can be chained together in arbitrary order.
+
+*finalizer*
+
+: A function which is called when an interpreter exits. Multiple
+ finalizers can be added to each interpreter.
+
+*globals*
+
+: The dictionary (or dictionary-like object) which resides inside the
+ interpreter and holds the currently-defined variables.
+
+*handler*
+
+: An error handler which is called whenever an error occurs in the
+ EmPy system. The default error handler prints details about the
+ error to `sys.stderr`.
+
+*hook*
+
+: A callable object that can be registered in a dictionary, and which
+ will be invoked before, during, or after certain internal
+ operations, identified by name with a string. Some types of hooks
+ can override the behavior of the EmPy interpreter.
+
+*icon*
+
+: A markup which looks up a variable-length abbreviation for a string
+ from a lookup table in the configuration. Icon markup is `@|...`.
+
+*interpreter*
+
+: The application (or class instance) which processes EmPy markup.
+
+*locals*
+
+: Along with the globals, a locals dictionary can be passed into
+ individual EmPy API calls.
+
+*markup*
+
+: EmPy substitutions set off with a prefix (by default `@`) and
+ appropriate delimiters.
+
+*named escape*
+
+: A control character referenced by name in an escape markup,
+ `@\^{...}`.
+
+*output*
+
+: The final destination of the result of processing an EmPy file.
+
+*prefix*
+
+: The Unicode code point (character) used to set off an expansions.
+ By default, the prefix is `@`. If set to `None`, no markup will be
+ processed.
+
+*processor*
+
+: An extensible system which processes a group of EmPy files, usually
+ arranged in a filesystem, and scans them for significators.
+
+*proxy*
+
+: An object which replaces the `sys.stdout` file object and allows the
+ EmPy system to intercept any indirect output to `sys.stdout` (say,
+ by the `print` function).
+
+*pseudomodule*
+
+: The module-like object named `empy` (by default) which is exposed as
+ a global inside every EmPy system. The pseudomodule and the
+ interpreter are in fact the same object, an instance of the
+ `Interpreter` class.
+
+*significator*
+
+: A special form of an assignment markup in EmPy which can be easily
+ parsed externally, primarily designed for representing uniform
+ assignment across a collection of files. Significator markup is
+ `@%[!]... NL` and `@%%[!]...%% NL`.
+
+*statement*
+
+: A line of code that needs to be executed; statements do not have
+ return values. Statement markup is `@{...}`.
+
+*stream*
+
+: A file-like object which manages diversion and filtering. A stack
+ of these is used by the interpreter with the top one being active.
+
+*system*
+
+: A running EmPy environment.
+
+*token*
+
+: An element of EmPy parsing. Tokens are parsed and then processed
+ one at a time.
+
+
+### Statistics
+
+<pre class="shell"><b><i>% wc setup.py emdoc.py emhelp.py emlib.py em.py test.sh LICENSE.md README.md README.md.em</i></b>
+ 69 266 2166 setup.py
+ 430 1167 14587 emdoc.py
+ 981 4342 42101 emhelp.py
+ 1124 3341 35456 emlib.py
+ 5955 21090 221197 em.py
+ 764 2737 19816 test.sh
+ 14 230 1520 LICENSE.md
+ 5878 26003 180313 README.md
+ 5937 27787 193528 README.md.em
+ 21152 86963 710684 total</pre>
+<pre class="shell"><b><i>% sha1sum setup.py emdoc.py emhelp.py emlib.py em.py test.sh LICENSE.md README.md README.md.em</i></b>
+729ef26c5aac648dd1b737ab97ad9c1e197a7710 setup.py
+7f7cd3b337e28fc18f08fb13c020bbd10b6411c0 emdoc.py
+672184dbf2f994f52f80275b1ec6fc121be78d9c emhelp.py
+74bd59e46166657a4597c48698e47a2b8569c187 emlib.py
+5cdc3f9f363d628074a7ceac5c40182021e64060 em.py
+0590cfa3e99ca493103f3dbbe7bd200663c3b962 test.sh
+1b09e5254cb5a907ebbc9dd150a858d8ae8a7d60 LICENSE.md
+dfa5421c2aa133561e5a6f6829d03da995682533 README.md
+c59ffad2f045a1e6746f31db655e4fd28210630f README.md.em</pre>
+
+
+## End notes
+### Author's notes
+
+I originally conceived EmPy as a replacement for my [Web templating
+system](http://www.alcyone.com/max/info/m4.html) which uses
+[m4](https://www.gnu.org/software/m4/), a general macroprocessing
+system for Unix.
+
+Most of my Web sites use a variety of m4 files, some of which are
+dynamically generated from databases, which are then scanned by a
+cataloging tool to organize them hierarchically (so that, say, a
+particular m4 file can understand where it is in the hierarchy, or
+what the titles of files related to it are without duplicating
+information); the results of the catalog are then written in database
+form as an m4 file (which every other m4 file implicitly includes),
+and then GNU Make converts each m4 to an HTML file by processing it.
+
+As the Web sites got more complicated, the use of m4 (which I had
+originally enjoyed for the challenge and abstractness) really started
+to become an impediment to serious work; while I was very
+knowledgeable about m4 -- having used it for so many years -- getting
+even simple things done with it is awkward and often difficult. Worse
+yet, as I started to use Python more and more over the years, the
+cataloging programs which scanned the m4 and built m4 databases were
+migrated to Python and made almost trivial, but writing out huge
+awkward tables of m4 definitions simply to make them accessible in
+other m4 scripts started to become almost farcical.
+
+It occurred to me what I really wanted was an all-Python solution.
+But replacing what used to be the m4 files with standalone Python
+programs would result in somewhat awkward programs normally consisting
+mostly of unprocessed text punctuated by small portions where
+variables and small amounts of code need to be substituted. Thus the
+idea was a sort of inverse of a Python interpreter: a program that
+normally would just pass text through unmolested, but when it found a
+special signifier would execute Python code in a normal environment.
+I looked at existing Python templating systems, and didn't find
+anything that appealed to me -- I wanted something where the desired
+markups were simple and unobtrusive. After considering choices of
+prefixes, I settled on `@` and EmPy was born.
+
+As I developed the tool, I realized it could have general appeal, even
+to those with widely varying problems to solve, provided the core tool
+they needed was an interpreter that could embed Python code inside
+templated text. As I continue to use the tool, I have been adding
+features as unobtrusively as possible as I see areas that can be
+improved.
+
+A design goal of EmPy is that its feature set should work on several
+levels; at any given level, if the user does not wish or need to use
+features from another level, they are under no obligation to do so --
+in fact, they wouldn't even need to know they exist. If you have no
+need of diversions, for instance, you are under no obligation to use
+them or even to know anything about them. If significators will not
+help you organize a set of EmPy scripts globally, then you can ignore
+them. New features that are being added are whenever feasible
+transparently backward compatible (except for major version releases);
+if you do not need them, their introduction should not affect you in
+any way. Finally, the use of unknown prefix and escape sequences
+results in errors, ensuring that they are reserved for future use.
+
+
+### Acknowledgements
+
+Questions, suggestions, bug reports, evangelism, and even complaints
+from many people over the years have helped make EmPy what it is
+today. Some, but by no means all, of these people are (in
+alphabetical order by surname):
+
+- Biswapesh Chattopadhyay
+- Beni Cherniavsky
+- Dr. S. Candelaria de Ram
+- Eric Eide
+- Dinu Gherman
+- Grzegorz Adam Hankiewicz
+- Robert Kroeger
+- Bohdan Kushnir
+- Kouichi Takahashi
+- Ville Vainio
+
+
+### Known issues and caveats
+
+- A running EmPy system is just an alternate form of a Python
+ interpreter; EmPy code is just as powerful as any Python code. Thus
+ it is vitally important that an EmPy system not expand EmPy markup
+ from an untrusted source; this is just as unsafe and potentially
+ dangerous as executing untrusted Python code.
+
+- To function properly, EmPy must override `sys.stdout` with a proxy
+ file object, so that it can capture output of side effects and
+ support diversions for each interpreter instance. It is important
+ that code executed in an environment _not_ rebind `sys.stdout`,
+ although it is perfectly legal to reference it explicitly (_e.g._,
+ `@sys.stdout.write("Hello world\n")`). If one really needs to
+ access the "true" stdout, then use `sys.__stdout__` instead (which
+ should also not be rebound). EmPy uses the standard Python error
+ handlers when exceptions are raised in EmPy code, which print to
+ `sys.stderr`. `sys.stderr`, `sys.__stdout__`, and `sys.__stderr__`
+ are never overridden by the interpreter; only `sys.stdout` is.
+
+- If you are using multiple interpreters with distinct output files
+ and are using the low-level interpreter methods (the ones not
+ documented here) to perform expansion and output, the `sys.stdout`
+ proxy will not be reliable. Only the high-level interpreter methods
+ (`evaluate`, `execute`, `string`, `expand` properly use the
+ protected stream stack on the `sys.stdout` proxy to guarantee valid
+ output. Either only use a single interpreter instance at a time
+ (creating and shutting it down with its `shutdown` method), use the
+ `-n`/`--no-proxy` option and only perform output with the
+ `write` method on the interpreter (_i.e._, do not use any `print`
+ statements in your code), or only use the high-level interpreter
+ methods documented here.
+
+- The `empy` "module" exposed through the EmPy interface (_e.g._,
+ `@empy`) is an artificial module. It is automatically exposed in
+ the globals of a running interpreter and it cannot be manually
+ imported with the `import` statement (nor should it be -- it is an
+ artifact of the EmPy processing system and does not correspond
+ directly to any .py file).
+
+- For an EmPy statement expansion all alone on a line, _e.g._, `@{a =
+ 1}`, will include a blank line due to the newline following the
+ closing curly brace. To suppress this blank line, use the symmetric
+ convention `@{a = 1}@`, where the final `@` markup precedes the
+ newline, making it whitespace markup and thus consumed. For
+ instance:
+
+ ````
+ @{a = 1}
+ There will be an extra newline above (following the closing brace).
+ Compare this to:
+ @{a = 1}@
+ There will be no extra newline above.
+ ````
+
+- Errors generated from within nested control structures (_e.g._,
+ `@[for ...]@[if ...]...@[end if]@[end for]` will report a context
+ of the start of the top-level control structure markup, not the
+ innermost markup, which would be much more helpful. This issue is
+ not new to 4.0 and will be addressed in a future release.
+
+- Contexts (such as `empy.identify`) track the context of executed
+ _EmPy_ code, not Python code. This means, for instance, that blocks
+ of code delimited with `@{` and `}` will identify themselves as
+ appearing on the line at which the `@{` appears. If you're
+ tracking errors and want more information about the location of the
+ errors from the Python code, use the `-r`/`--raw-errors` option, which
+ will provide you with the full Python traceback.
+
+- The `@[for ...]` variable specification supports tuples for tuple
+ unpacking, even recursive tuples. However, it is limited in that
+ the names included may only be valid Python identifiers, not
+ arbitrary Python "lvalues." Since this is something of an
+ accidental Python feature that is very unlikely to be relied on in
+ practice, this is not thought to be a significant limitation. As a
+ concrete example:
+
+ ```python
+ a = [None]
+ for a[0] in range(5):
+ print(a)
+ ```
+
+ is valid (but strange) Python, but the EmPy equivalent with `@[for
+ a[0] in range(5)]...` is invalid.
+
+- The `:=` assignment expression syntax ("walrus operator") for
+ `while` loops and `if` statements is not supported in the EmPy
+ equivalent control markups `@[while]` and `@[if]`. This may be
+ supported in the future.
+
+- An EmPy equivalent of the Python `match`/`case` control structure
+ does not exist. This syntax may be too awkward to make it practical
+ as an EmPy control markup, but further research is required; this
+ may be implemented in the future.
+
+
+### For package maintainers
+
+EmPy is available as a system package in most major Linux
+distributions, though most distributions have not updated to EmPy 4.0
+yet.
+
+EmPy can be made available as an operating system/distribution package
+in several different ways. Regardless of the high-level organization,
+the installed .py Python files must be made available as importable
+Python modules, with the additional requirement that em.py must be
+made available as an executable in the default `PATH`. If necessary,
+this executable may also be named `empy`, but `em.py` is preferred --
+and either way it is still important that the em.py file be available
+for importing as a Python module (`em`).
+
+:::{note}
+
+Since EmPy 4.0 is not fully compatible with EmPy 3._x_, I suggest
+making both EmPy 3._x_ and 4.0 packages available side by side until
+4.0 becomes more fully adopted by the community.
+
+:::
+
+Here is a breakdown of the contents of a release tarball:
+
+| File | Description |
+| --- | --- |
+| em.py | Main EmPy module and executable |
+| emhelp.py | Help subsystem module |
+| emlib.py | Supplementary EmPy facilities module |
+| emdoc.py | Documentation subsystem module |
+| ANNOUNCE.md | EmPy 4.0 release announcement |
+| HELP.md | Help topic summaries |
+| LICENSE.md | Software license |
+| README.md | README (this file) |
+| README.md.em | README source file |
+| doc | HTML documentation directory hierarchy |
+| test.sh | Test shell script |
+| tests | Tests directory hierarchy |
+| suites | Test suites directory hierarchy |
+
+They can either be bundled up into a single, monolithic package, or
+divided into a series of subpackages. Here's a suggestion for a
+fleshed-out series of EmPy subpackages:
+
+`empy-minimal`
+
+: Just the em.py file, available as a Python module as well as an
+ executable. Note that this will not allow the use of the EmPy help
+ subsystem, unless the module emhelp.py is also included.
+
+`empy-basic`
+
+: The .md files, all the .py files (em.py,
+ emhelp.py, emlib.py, emdoc.py) available as Python modules, with the
+ em.py file also available as an executable.
+
+`empy-doc`
+
+: Just the contents of the README source file README.md.em and the
+ docs directory hierarchy.
+
+`empy-test`
+
+: The test script test.sh, the tests directory, and the suites
+ directory.
+
+`empy`
+
+: All of the above.
+
+
+### Reporting bugs
+
+If you find a bug in EmPy, please follow these steps:
+
+1. Whittle a reproducible test case down to the smallest standalone
+ example which demonstrates the issue, the smaller the better;
+
+2. Collect the output of `em.py -Z` (this will provide detailed
+ diagnostic details about your environment), or at least `em.py -W`
+ (which provides only basic details);
+
+3. [Send me an email](mailto:software@alcyone.com) with _EmPy_ in the
+ Subject line including both files and a description of the problem.
+
+Thank you!
+
+
+### Release history
+
+4.0.1 (2023 Dec 24)
+
+: Add root context argument, serializers, and idents to interpreter;
+ fix `setContext...` methods so they also modify the currents stack;
+ better backward compatibility for `expand` function and
+ `CompatibilityError`; fix inconsistent stack usage with `expand`
+ method; add error dispatchers, cleaner error handling and
+ `ignoreErrors`; have `expand` method/function raise
+ exceptions to caller; eliminate need for `FullContext` class
+ distinct from `Context`; support comments in "clean" controls; add
+ `--no-none-symbol` option; add clearer errors for removed literal
+ markup; add `Container` support class in `emlib`; hide non-standard
+ proxy attributes and methods; support string errors (why not);
+ update and expand tests; help subsystem and documentation updates.
+
+4.0 (2023 Nov 29)
+
+: A major revamp, refresh, and modernization. Major new features
+ include inline comments `@*...*`; backquote literals `` @`...`
+ ``; chained if-then-else expressions; functional expressions
+ `@f{...}`; full support for `@[try]`, `@[while ...]` and `@[with
+ ...]` control markup; `@[defined ...]` control markup; stringized
+ and multiline significators; named escapes `@\^{...}`; diacritics
+ `@^...`; icons `@|...`; emojis `@:...:`; configurations; full
+ Unicode and file buffering support; proxy now reference counted;
+ hooks can override behavior; many bug fixes; an extensive builtin
+ help system (`emhelp`); and rewritten and expanded documentation.
+ Changes include relicensing to BSD, interpreter constructor now
+ requires keyword arguments, `-d`/`--delete-on-error` instead of "fully
+ buffered files"; cleaned up environment variables; "repr" markup
+ replaced with emoji markup; remove literal markups `@)`, `@]`,
+ `@}`; context line markup `@!...` no longer pre-adjusts line;
+ custom markup `@<...>` now parsed more sensibly; filter shortcuts
+ removed; context now track column and character count; auxiliary
+ classes moved to `emlib` module; use `argv` instead of `argc` for
+ interpreter arguments. See [Full list of changes between EmPy 3._x_
+ and
+ 4.0](http://www.alcyone.com/software/empy/ANNOUNCE.html#full-list-of-changes-between-empy-3-x-and-4-0)
+ for a more comprehensive list.
+
+3.3.4a (2021 Nov 19)
+
+: Fix an error in the setup.py in the downloadable tarball (did not
+ affect PIP downloads).
+
+3.3.4 (2019 Feb 26)
+
+: Minor fix for a Python 3._x_ compatibility issue.
+
+3.3.3 (2017 Feb 12)
+
+: Fix for `empy.defined` interpreter method.
+
+3.3.2 (2014 Jan 24)
+
+: Additional fix for source compatibility between 2._x_ and 3.0.
+
+3.3.1 (2014 Jan 22)
+
+: Source compatibility for 2._x_ and 3.0; 1._x_ compatibility dropped.
+
+3.3 (2003 Oct 27)
+
+: Custom markup `@<...>`; remove separate pseudomodule instance for
+ greater transparency; deprecate `Interpreter` attribute of
+ pseudomodule; deprecate auxiliary class name attributes associated
+ with pseudomodule in preparation for separate support library in
+ 4.0; add `--no-callback-error` and
+ `--no-bangpath-processing` [now `--no-ignore-bangpaths`]
+ command line options; add `atToken` hook.
+
+3.2 (2003 Oct 7)
+
+: Reengineer hooks support to use hook instances; add `-v`/`--verbose`
+ and `-l`/`--relative-path` option; reversed PEP 317 style;
+ modify Unicode support to give less confusing errors in the case of
+ unknown encodings and error handlers; relicensed under LGPL.
+
+3.1.1 (2003 Sep 20)
+
+: Add string literal `@"..."` markup; add
+ `-w`/`--pause-at-end` option; fix improper globals collision
+ error via the `sys.stdout` proxy.
+
+3.1 (2003 Aug 8)
+
+: Unicode support (Python 2.0 and above); add Document and Processor
+ helper classes for processing significators [later moved to
+ `emlib`]; add `--no-prefix` option for suppressing all
+ markups.
+
+3.0.4 (2003 Aug 7)
+
+: Implement somewhat more robust "lvalue" parsing for `@[for]`
+ construct (thanks to Beni Cherniavsky for inspiration).
+
+3.0.3 (2003 Jul 9)
+
+: Fix bug regarding recursive tuple unpacking using `@[for]`; add
+ `empy.saveGlobals`, `empy.restoreGlobals`, and `empy.defined`
+ functions.
+
+3.0.2 (2003 Jun 19)
+
+: `@?` and `@!` markups for changing the current context name and
+ line, respectively; add `update` method to interpreter; new and
+ renamed context operations, `empy.setContextName`,
+ `empy.setContextLine`, `empy.pushContext`, `empy.popContext`.
+
+3.0.1 (2003 Jun 9)
+
+: Fix simple bug preventing command line preprocessing directives
+ (`-I`/`--import=MODULES`, `-D`/`--define=DEFN`, `-E`/`--execute=STATEMENT`,
+ `-F`/`--file=FILENAME`, `-P`/`--preprocess=FILENAME`) from executing properly;
+ defensive PEP 317 compliance [defunct].
+
+3.0 (2003 Jun 1)
+
+: Replace substitution markup with control markup `@[...]`; support
+ `@(...?...!...)` for conditional expressions; add acknowledgements
+ and glossary sections to documentation; rename buffering option back
+ to `-b`/`--buffering`; add `-m`/`--pseudomodule=NAME` (_environment variable:_ `EMPY_PSEUDO`, _configuration variable:_ `pseudomoduleName`) and
+ `-n`/`--no-proxy` (_environment variable:_ `EMPY_NO_PROXY`, _configuration variable:_ `useProxy`) for suppressing `sys.stdout` proxy; rename
+ main error class to `Error`; add standalone `expand` function; add
+ `--binary` and `--chunk-size` options [defunct]; reengineer parsing
+ system to use tokens for easy extensibility; safeguard curly braces
+ in simple expressions [now used by functional expressions]; fix bug
+ involving custom `Interpreter` instances ignoring globals argument;
+ `distutils` [now `setuptools`] support.
+
+2.3 (2003 Feb 20)
+
+: Proper and full support for concurrent and recursive interpreters;
+ protection from closing the true stdout file object; detect edge
+ cases of interpreter globals or `sys.stdout` proxy collisions; add
+ globals manipulation functions `empy.getGlobals`, `empy.setGlobals`,
+ and `empy.updateGlobals` which properly preserve the `empy`
+ pseudomodule; separate usage info out into easily accessible lists
+ for easier presentation; have `-h` option show simple usage and `-H`
+ show extended usage [defunct]; add `NullFile` utility class.
+
+2.2.6 (2003 Jan 30)
+
+: Fix a bug in the `Filter.detach` method (which would not normally be
+ called anyway).
+
+2.2.5 (2003 Jan 9)
+
+: Strip carriage returns out of executed code blocks for DOS/Windows
+ compatibility.
+
+2.2.4 (2002 Dec 23)
+
+: Abstract Filter interface to use methods only; add `@[noop: ...]`
+ substitution for completeness and block commenting [defunct].
+
+2.2.3 (2002 Dec 16)
+
+: Support compatibility with Jython by working around a minor
+ difference between CPython and Jython in string splitting.
+
+2.2.2 (2002 Dec 14)
+
+: Include better docstrings for pseudomodule functions; segue to a
+ dictionary-based options system for interpreters; add
+ `empy.clearAllHooks` and `empy.clearGlobals`; include a short
+ documentation section on embedding interpreters; fix a bug in
+ significator regular expression.
+
+2.2.1 (2002 Nov 30)
+
+: Tweak test script to avoid writing unnecessary temporary file; add
+ `Interpreter.single` method; expose `evaluate`, `execute`,
+ `substitute` [defunct], and `single` methods to the pseudomodule;
+ add (rather obvious) `EMPY_OPTIONS` environment variable support;
+ add `empy.enableHooks` and `empy.disableHooks`; include optimization
+ to transparently disable hooks until they are actually used.
+
+2.2 (2002 Nov 21)
+
+: Switched to -V option for version information;
+ `empy.createDiversion` for creating initially empty diversion;
+ direct access to diversion objects with `empy.retrieveDiversion`;
+ environment variable support; removed `--raw` long argument (use
+ `-r`/`--raw-errors` instead); added quaternary escape code
+ (well, why not).
+
+2.1 (2002 Oct 18)
+
+: `empy.atExit` [now `empy.appendFinalizer`] registration separate
+ from hooks to allow for normal interpreter support; include a
+ benchmark sample and test.sh verification script; expose
+ `empy.string` directly; `-D`/`--define=DEFN` option for explicit defines
+ on command line; remove ill-conceived support for `@else:`
+ separator in `@[if ...]` substitution [defunct]; handle nested
+ substitutions properly [defunct]; `@[macro ...]` substitution for
+ creating recallable expansions [defunct].
+
+2.0.1 (2002 Oct 8)
+
+: Fix missing usage information; fix `after_evaluate` hook not getting
+ called [defunct]; add `empy.atExit` [now `empy.appendFinalizer`]
+ call to register a finalizer.
+
+2.0 (2002 Sep 30)
+
+: Parsing system completely revamped and simplified, eliminating a
+ whole class of context-related bugs; builtin support for buffered
+ filters; support for registering hooks; support for command line
+ arguments; interactive mode with `-i`/`--interactive`; significator
+ value extended to be any valid Python expression.
+
+1.5.1 (2002 Sep 24)
+
+: Allow `@]` to represent unbalanced close brackets in `@[...]`
+ markups [defunct].
+
+1.5 (2002 Sep 18)
+
+: Escape codes (`@\...`); conditional and repeated expansion
+ substitutions [defunct]; replaced with control markups]; fix a few
+ bugs involving files which do not end in newlines.
+
+1.4 (2002 Sep 7)
+
+: Add in-place markup `@:...:...:` [now `@$...$...$`]; fix bug with
+ triple quotes; collapse conditional and protected expression
+ syntaxes into the single generalized `@(...)` notation;
+ `empy.setName` and `empy.setLine` functions [now
+ `empy.setContextName` and `empy.setContextLine`]; true support for
+ multiple concurrent interpreters with improved `sys.stdout` proxy;
+ proper support for `empy.expand` to return a string evaluated in a
+ subinterpreter as intended; merged Context and Parser classes
+ together, and separated out Scanner functionality.
+
+1.3 (2002 Aug 24)
+
+: Pseudomodule as true instance; move toward more verbose (and clear)
+ pseudomodule functions; fleshed out diversions model; filters;
+ conditional expressions; protected expressions; preprocessing with
+ `-P`/`--preprocess=FILENAME` (in preparation for possible support for command
+ line arguments).
+
+1.2 (2002 Aug 16)
+
+: Treat bangpaths as comments; `empy.quote` for the opposite process
+ of `empy.expand`; significators (`@%...` sequences); add
+ `-I`/`--import=MODULES` and `-f`/`--flatten` options; much improved
+ documentation.
+
+1.1.5 (2002 Aug 15)
+
+: Add a separate `invoke` function that can be called multiple times
+ with arguments to simulate multiple runs.
+
+1.1.4 (2002 Aug 12)
+
+: Handle strings thrown as exceptions properly; use `getopt` to
+ process command line arguments; cleanup file buffering with
+ AbstractFile; very slight documentation and code cleanup.
+
+1.1.3 (2002 Aug 9)
+
+: Support for changing the prefix from within the `empy` pseudomodule.
+
+1.1.2 (2002 Aug 5)
+
+: Renamed buffering option [defunct], added `-F`/`--file=FILENAME` option
+ for interpreting Python files from the command line, fixed improper
+ handling of exceptions from command line options (`-E`/`--execute=STATEMENT`,
+ `-F`/`--file=FILENAME`).
+
+1.1.1 (2002 Aug 4)
+
+: Typo bugfixes; documentation clarification.
+
+1.1 (2002 Aug 4)
+
+: Added option for fully buffering output (including file opens),
+ executing commands through the command line; some documentation
+ errors fixed.
+
+1.0 (2002 Jul 23)
+
+: Renamed project to EmPy. Documentation and sample tweaks; added
+ `empy.flatten` [now `empy.flattenGlobals`]; added `-a`/`--append=FILENAME`
+ option. First official release.
+
+0.3 (2002 Apr 14)
+
+: Extended "simple expression" syntax, interpreter abstraction, proper
+ context handling, better error handling, explicit file inclusion,
+ extended samples.
+
+0.2 (2002 Apr 13)
+
+: Bugfixes, support non-expansion of `None`s, allow choice of alternate
+ prefix.
+
+0.1.1 (2002 Apr 12)
+
+: Bugfixes, support for Python 1.5._x_ [defunct], add
+ `-r`/`--raw-errors` option.
+
+0.1 (2002 Apr 12)
+
+: Initial early access release.
+
+
+### Contact
+
+This software was written by [Erik Max
+Francis](http://www.alcyone.com/max/). If you use this software, have
+suggestions for future releases, or bug reports or problems with this
+documentation, [I'd love to hear about
+it](mailto:software@alcyone.com).
+
+Even if you try out EmPy for a project and find it unsuitable, I'd
+like to know what stumbling blocks you ran into so they can
+potentially be addressed in a future version.
+
+I hope you enjoy using EmPy! ℰ
+
+
+### About this document
+
+This document was generated with EmPy itself using the `emdoc` module.
+Both the source (README.md.em) and the resulting Markdown text
+(README.md) are included in the release tarball, as is the HTML
+directory hierarchy generated with Sphinx (doc).
+
+_This documentation for EmPy version 4.0.1 was generated from README.md.em (SHA1 `c59ffad2f045a1e6746f31db655e4fd28210630f`, 193528 bytes) at 2023-12-24 17:04:25 with EmPy version 4.0.1, in CPython/3.10.12, on Linux (POSIX), with x86_64._
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Module: em</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Module: em</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A system for processing Python as markup embedded in text.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Imported modules">Imported modules</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<b>import</b> <a href="http://www.python.org/doc/current/lib/module-copy.html">copy</a><br>
-<b>import</b> <a href="http://www.python.org/doc/current/lib/module-getopt.html">getopt</a><br>
-<b>import</b> <a href="http://www.python.org/doc/current/lib/module-os.html">os</a><br>
-<b>import</b> <a href="http://www.python.org/doc/current/lib/module-re.html">re</a><br>
-<b>import</b> <a href="http://www.python.org/doc/current/lib/module-string.html">string</a><br>
-<b>import</b> <a href="http://www.python.org/doc/current/lib/module-sys.html">sys</a><br>
-<b>import</b> <a href="http://www.python.org/doc/current/lib/module-types.html">types</a><br>
-
-</td></tr>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Functions">Functions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#environment">environment</a><br>
-<a href="#expand">expand</a><br>
-<a href="#info">info</a><br>
-<a href="#invoke">invoke</a><br>
-<a href="#main">main</a><br>
-<a href="#usage">usage</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="environment"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">environment </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-environment ( name, default=None )
-
-</pre></font>
-
-<p>Get data from the current environment. If the default is True
- or False, then presume that we're only interested in the existence
- or non-existence of the environment variable.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="expand"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">expand </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-expand (
- _data,
- _globals=None,
- _argv=None,
- _prefix=DEFAULT_PREFIX,
- _pseudo=None,
- _options=None,
- **_locals,
- )
-
-</pre></font>
-
-<p>Do an atomic expansion of the given source data, creating and
- shutting down an interpreter dedicated to the task. The sys.stdout
- object is saved off and then replaced before this function
- returns.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="info"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">info </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-info ( table )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="invoke"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">invoke </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-invoke ( args )
-
-</pre></font>
-
-<p>Run a standalone instance of an EmPy interpeter.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-Error, "prefix must be single-character string"<br>
-ValueError, "-b only makes sense with -o or -a arguments"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="main"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">main </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-main ()
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="usage"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">usage </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-usage ( verbose=True )
-
-</pre></font>
-
-<p>Print usage information.</p>
-</td></tr>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Classes">Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<table border="0" cellpadding="3" cellspacing="0">
-<tr><td valign="top" align="left"><p><a href="em/AbstractFile.html">AbstractFile</a></p></td><td valign="top" align="left">
-<p>An abstracted file that, when buffered, will totally buffer the</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/BreakFlow.html">BreakFlow</a></p></td><td valign="top" align="left">
-<p>A break control flow.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/BufferedFilter.html">BufferedFilter</a></p></td><td valign="top" align="left">
-<p>A buffered filter is one that doesn't modify the source data</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/CommentToken.html">CommentToken</a></p></td><td valign="top" align="left">
-<p>A comment markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Context.html">Context</a></p></td><td valign="top" align="left">
-<p>An interpreter context, which encapsulates a name, an input</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/ContextLineToken.html">ContextLineToken</a></p></td><td valign="top" align="left">
-<p>A context line change markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/ContextNameToken.html">ContextNameToken</a></p></td><td valign="top" align="left">
-<p>A context name change markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/ContinueFlow.html">ContinueFlow</a></p></td><td valign="top" align="left">
-<p>A continue control flow.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/ControlToken.html">ControlToken</a></p></td><td valign="top" align="left">
-<p>A control token.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/CustomToken.html">CustomToken</a></p></td><td valign="top" align="left">
-<p>A custom markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Diversion.html">Diversion</a></p></td><td valign="top" align="left">
-<p>The representation of an active diversion. Diversions act as</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/DiversionError.html">DiversionError</a></p></td><td valign="top" align="left">
-<p>An error related to diversions.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Document.html">Document</a></p></td><td valign="top" align="left">
-<p>A representation of an individual EmPy document, as used by a</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Error.html">Error</a></p></td><td valign="top" align="left">
-<p>The base class for all EmPy errors.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/EscapeToken.html">EscapeToken</a></p></td><td valign="top" align="left">
-<p>An escape markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/ExpansionToken.html">ExpansionToken</a></p></td><td valign="top" align="left">
-<p>A token that involves an expansion.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/ExpressionToken.html">ExpressionToken</a></p></td><td valign="top" align="left">
-<p>An expression markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Filter.html">Filter</a></p></td><td valign="top" align="left">
-<p>An abstract filter.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/FilterError.html">FilterError</a></p></td><td valign="top" align="left">
-<p>An error related to filters.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/FlowError.html">FlowError</a></p></td><td valign="top" align="left">
-<p>An exception related to control flow.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/FunctionFilter.html">FunctionFilter</a></p></td><td valign="top" align="left">
-<p>A filter that works simply by pumping its input through a</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Hook.html">Hook</a></p></td><td valign="top" align="left">
-<p>The base class for implementing hooks.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/InPlaceToken.html">InPlaceToken</a></p></td><td valign="top" align="left">
-<p>An in-place markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Interpreter.html">Interpreter</a></p></td><td valign="top" align="left">
-<p>An interpreter can process chunks of EmPy code.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/LineBufferedFilter.html">LineBufferedFilter</a></p></td><td valign="top" align="left">
-<p>A line-buffered filter only lets data through when it sees</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/LiteralToken.html">LiteralToken</a></p></td><td valign="top" align="left">
-<p>A literal markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/MaximallyBufferedFilter.html">MaximallyBufferedFilter</a></p></td><td valign="top" align="left">
-<p>A maximally-buffered filter only lets its data through on the final</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/MetaError.html">MetaError</a></p></td><td valign="top" align="left">
-<p>A wrapper around a real Python exception for including a copy of</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/NullFile.html">NullFile</a></p></td><td valign="top" align="left">
-<p>A simple class that supports all the file-like object methods</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/NullFilter.html">NullFilter</a></p></td><td valign="top" align="left">
-<p>A filter that never sends any output to its sink.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/NullToken.html">NullToken</a></p></td><td valign="top" align="left">
-<p>A chunk of data not containing markups.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/ParseError.html">ParseError</a></p></td><td valign="top" align="left">
-<p>A parse error occurred.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/PrefixToken.html">PrefixToken</a></p></td><td valign="top" align="left">
-<p>A prefix markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Processor.html">Processor</a></p></td><td valign="top" align="left">
-<p>An entity which is capable of processing a hierarchy of EmPy</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/ProxyFile.html">ProxyFile</a></p></td><td valign="top" align="left">
-<p>The proxy file object that is intended to take the place of</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/ReprToken.html">ReprToken</a></p></td><td valign="top" align="left">
-<p>A repr markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Scanner.html">Scanner</a></p></td><td valign="top" align="left">
-<p>A scanner holds a buffer for lookahead parsing and has the</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/SignificatorToken.html">SignificatorToken</a></p></td><td valign="top" align="left">
-<p>A significator markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/SimpleExpressionToken.html">SimpleExpressionToken</a></p></td><td valign="top" align="left">
-<p>A simple expression markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/SizeBufferedFilter.html">SizeBufferedFilter</a></p></td><td valign="top" align="left">
-<p>A size-buffered filter only in fixed size chunks (excepting the</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Stack.html">Stack</a></p></td><td valign="top" align="left">
-<p>A simple stack that behaves as a sequence (with 0 being the top</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/StackUnderflowError.html">StackUnderflowError</a></p></td><td valign="top" align="left">
-<p>A stack underflow.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/StatementToken.html">StatementToken</a></p></td><td valign="top" align="left">
-<p>A statement markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Stream.html">Stream</a></p></td><td valign="top" align="left">
-<p>A wrapper around an (output) file object which supports</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/StringFilter.html">StringFilter</a></p></td><td valign="top" align="left">
-<p>A filter that takes a translation string (256 characters) and</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/StringLiteralToken.html">StringLiteralToken</a></p></td><td valign="top" align="left">
-<p>A string token markup.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Subsystem.html">Subsystem</a></p></td><td valign="top" align="left">
-<p>The subsystem class defers file creation so that it can create</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/SubsystemError.html">SubsystemError</a></p></td><td valign="top" align="left">
-<p>An error associated with the Unicode subsystem.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/Token.html">Token</a></p></td><td valign="top" align="left">
-<p>An element of expansion.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/TransientParseError.html">TransientParseError</a></p></td><td valign="top" align="left">
-<p>A parse error occurred which may be resolved by feeding more data.</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/UncloseableFile.html">UncloseableFile</a></p></td><td valign="top" align="left">
-<p>A simple class which wraps around a delegate file-like object</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/VerboseHook.html">VerboseHook</a></p></td><td valign="top" align="left">
-<p>A verbose hook that reports all information received by the</p>
-</td></tr>
-<tr><td valign="top" align="left"><p><a href="em/WhitespaceToken.html">WhitespaceToken</a></p></td><td valign="top" align="left">
-<p>A whitespace markup.</p>
-</td></tr>
-</table>
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: AbstractFile</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: AbstractFile</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An abstracted file that, when buffered, will totally buffer the
- file, including even the file open.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__del__">__del__</a><br>
-<a href="#__init__">__init__</a><br>
-<a href="#abort">abort</a><br>
-<a href="#close">close</a><br>
-<a href="#commit">commit</a><br>
-<a href="#flush">flush</a><br>
-<a href="#write">write</a><br>
-<a href="#writelines">writelines</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__del__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__del__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__del__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ (
- self,
- filename,
- mode='w',
- buffered=False,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="abort"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">abort </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-abort ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="close"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">close </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-close ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="commit"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">commit </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-commit ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flush ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="writelines"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">writelines </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-writelines ( self, data )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: BreakFlow</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: BreakFlow</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A break control flow.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="FlowError.html">FlowError</a><br>
-<ul>
-
-<a href="Error.html">Error</a><br>
-<ul>
-
-Exception<br>
-
-</ul>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: BufferedFilter</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: BufferedFilter</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A buffered filter is one that doesn't modify the source data
- sent to the sink, but instead holds it for a time. The standard
- variety only sends the data along when it receives a flush
- command.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Filter.html">Filter</a><br>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#flush">flush</a><br>
-<a href="#write">write</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flush ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: CommentToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: CommentToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A comment markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-TransientParseError, "comment expects newline"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Context</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Context</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An interpreter context, which encapsulates a name, an input
- file object, and a parser object.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#__str__">__str__</a><br>
-<a href="#bump">bump</a><br>
-<a href="#identify">identify</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ (
- self,
- name,
- line=0,
- units=DEFAULT_UNIT,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__str__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__str__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__str__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="bump"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">bump </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-bump ( self, quantity=1 )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="identify"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">identify </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-identify ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: ContextLineToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: ContextLineToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A context line change markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "context line requires integer"<br>
-TransientParseError, "context line expects newline"<br>
-
-</td></tr>
-</table>
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: ContextNameToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: ContextNameToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A context name change markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-TransientParseError, "context name expects newline"<br>
-
-</td></tr>
-</table>
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: ContinueFlow</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: ContinueFlow</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A continue control flow.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="FlowError.html">FlowError</a><br>
-<ul>
-
-<a href="Error.html">Error</a><br>
-<ul>
-
-Exception<br>
-
-</ul>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: ControlToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: ControlToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A control token.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#build">build</a><br>
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-<a href="#subrun">subrun</a><br>
-<a href="#subscan">subscan</a><br>
-<a href="#substring">substring</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="build"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">build </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-build ( self, allowed=None )
-
-</pre></font>
-
-<p>Process the list of subtokens and divide it into a list of
- 2-tuples, consisting of the dividing tokens and the list of
- subtokens that follow them. If allowed is specified, it will
- represent the list of the only secondary markup types which
- are allowed.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "control unexpected secondary: '%s'" % subtoken.type<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-
- <table border="0" cellspacing="2" cellpadding="2" width="100%">
- <tr>
- <td align="LEFT" valign="TOP">
-BreakFlow, "control 'break' without 'for', 'while'"<br>
-ContinueFlow, "control 'continue' without 'for', 'while'"<br>
-ParseError, "control '%s' cannot be at this level" % self.type<br>
-ParseError, "control 'end' requires primary markup"<br>
-ParseError, "control 'for' expects at most one 'else'"<br>
-ParseError, "control 'if' unexpected secondary: '%s'" % secondary.type<br>
-</td>
-<td align="LEFT" valign="TOP">
-ParseError, "control 'try' can only have one 'finally'"<br>
-ParseError, "control 'try' cannot have 'except' and 'finally'"<br>
-ParseError, "control 'try' needs 'except' or 'finally'"<br>
-ParseError, "control 'while' expects at most one 'else'"<br>
-ParseError, "control expected 'for x in seq'"<br>
-</td>
-</tr>
- </table>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "control '%s' needs arguments" % self.type<br>
-ParseError, "unknown control markup: '%s'" % self.type<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="subrun"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">subrun </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-subrun (
- self,
- tokens,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-<p>Execute a sequence of tokens.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="subscan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">subscan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-subscan (
- self,
- scanner,
- primary,
- )
-
-</pre></font>
-
-<p>Do a subscan for contained tokens.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "control must end with 'end %s'" % primary<br>
-TransientParseError, "control '%s' needs more tokens" % primary<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="substring"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">substring </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-substring ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: CustomToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: CustomToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A custom markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Diversion</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Diversion</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>The representation of an active diversion. Diversions act as
- (writable) file objects, and then can be recalled either as pure
- strings or (readable) file objects.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#asFile">asFile</a><br>
-<a href="#asString">asString</a><br>
-<a href="#close">close</a><br>
-<a href="#flush">flush</a><br>
-<a href="#write">write</a><br>
-<a href="#writelines">writelines</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="asFile"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">asFile </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-asFile ( self )
-
-</pre></font>
-
-<p>Return the diversion as a file.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="asString"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">asString </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-asString ( self )
-
-</pre></font>
-
-<p>Return the diversion as a string.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="close"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">close </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-close ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flush ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="writelines"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">writelines </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-writelines ( self, lines )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: DiversionError</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: DiversionError</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An error related to diversions.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Error.html">Error</a><br>
-<ul>
-
-Exception<br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Document</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Document</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A representation of an individual EmPy document, as used by a
- processor.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ (
- self,
- ID,
- filename,
- )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Error</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Error</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>The base class for all EmPy errors.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-Exception<br>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: EscapeToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: EscapeToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An escape markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "invalid escape control code"<br>
-ParseError, "invalid numeric escape code"<br>
-ParseError, "unrecognized escape code"<br>
-ParseError, r"Unicode name escape should be \N{...}"<br>
-SubsystemError, "unknown Unicode character name: %s" % name<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: ExpansionToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: ExpansionToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A token that involves an expansion.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Token.html">Token</a><br>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ (
- self,
- prefix,
- first,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: ExpressionToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: ExpressionToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An expression markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Filter</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Filter</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An abstract filter.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-
- <table border="0" cellspacing="2" cellpadding="2" width="100%">
- <tr>
- <td align="LEFT" valign="TOP">
-<a href="#__init__">__init__</a><br>
-<a href="#_flush">_flush</a><br>
-<a href="#attach">attach</a><br>
-<a href="#close">close</a><br>
-<a href="#detach">detach</a><br>
-</td>
-<td align="LEFT" valign="TOP">
-<a href="#flush">flush</a><br>
-<a href="#last">last</a><br>
-<a href="#next">next</a><br>
-<a href="#write">write</a><br>
-<a href="#writelines">writelines</a><br>
-</td>
-</tr>
- </table>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-NotImplementedError<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="_flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">_flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-_flush ( self )
-
-</pre></font>
-
-<p>The _flush method should always flush the sink and should not
- be overridden.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="attach"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">attach </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-attach ( self, filter )
-
-</pre></font>
-
-<p>Attach a filter to this one.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="close"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">close </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-close ( self )
-
-</pre></font>
-
-<p>Close the filter. Do an explicit flush first, then close the
- sink.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="detach"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">detach </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-detach ( self )
-
-</pre></font>
-
-<p>Detach a filter from its sink.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flush ( self )
-
-</pre></font>
-
-<p>The flush method can be overridden.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="last"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">last </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-last ( self )
-
-</pre></font>
-
-<p>Find the last filter in this chain.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="next"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">next </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-next ( self )
-
-</pre></font>
-
-<p>Return the next filter/file-like object in the sequence, or None.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-<p>The standard write method; this must be overridden in subclasses.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-NotImplementedError<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="writelines"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">writelines </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-writelines ( self, lines )
-
-</pre></font>
-
-<p>Standard writelines wrapper.</p>
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: FilterError</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: FilterError</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An error related to filters.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Error.html">Error</a><br>
-<ul>
-
-Exception<br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: FlowError</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: FlowError</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An exception related to control flow.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Error.html">Error</a><br>
-<ul>
-
-Exception<br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: FunctionFilter</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: FunctionFilter</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A filter that works simply by pumping its input through a
- function which maps strings into strings.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Filter.html">Filter</a><br>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#write">write</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self, function )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Hook</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Hook</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>The base class for implementing hooks.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-
- <table border="0" cellspacing="2" cellpadding="2" width="100%">
- <tr>
- <td align="LEFT" valign="TOP">
-<a href="#__init__">__init__</a><br>
-<a href="#afterAtomic">afterAtomic</a><br>
-<a href="#afterBinary">afterBinary</a><br>
-<a href="#afterClause">afterClause</a><br>
-<a href="#afterControl">afterControl</a><br>
-<a href="#afterDefined">afterDefined</a><br>
-<a href="#afterEscape">afterEscape</a><br>
-<a href="#afterEvaluate">afterEvaluate</a><br>
-<a href="#afterExecute">afterExecute</a><br>
-<a href="#afterExpand">afterExpand</a><br>
-<a href="#afterFile">afterFile</a><br>
-<a href="#afterImport">afterImport</a><br>
-<a href="#afterInclude">afterInclude</a><br>
-<a href="#afterLiteral">afterLiteral</a><br>
-<a href="#afterMulti">afterMulti</a><br>
-<a href="#afterQuote">afterQuote</a><br>
-<a href="#afterSerialize">afterSerialize</a><br>
-<a href="#afterSignificate">afterSignificate</a><br>
-</td>
-<td align="LEFT" valign="TOP">
-<a href="#afterSingle">afterSingle</a><br>
-<a href="#afterString">afterString</a><br>
-<a href="#atFinalize">atFinalize</a><br>
-<a href="#atHandle">atHandle</a><br>
-<a href="#atInteract">atInteract</a><br>
-<a href="#atParse">atParse</a><br>
-<a href="#atReady">atReady</a><br>
-<a href="#atShutdown">atShutdown</a><br>
-<a href="#atStartup">atStartup</a><br>
-<a href="#atToken">atToken</a><br>
-<a href="#beforeAtomic">beforeAtomic</a><br>
-<a href="#beforeBinary">beforeBinary</a><br>
-<a href="#beforeClause">beforeClause</a><br>
-<a href="#beforeControl">beforeControl</a><br>
-<a href="#beforeDefined">beforeDefined</a><br>
-<a href="#beforeEscape">beforeEscape</a><br>
-<a href="#beforeEvaluate">beforeEvaluate</a><br>
-<a href="#beforeExecute">beforeExecute</a><br>
-</td>
-<td align="LEFT" valign="TOP">
-<a href="#beforeExpand">beforeExpand</a><br>
-<a href="#beforeFile">beforeFile</a><br>
-<a href="#beforeImport">beforeImport</a><br>
-<a href="#beforeInclude">beforeInclude</a><br>
-<a href="#beforeLiteral">beforeLiteral</a><br>
-<a href="#beforeMulti">beforeMulti</a><br>
-<a href="#beforeQuote">beforeQuote</a><br>
-<a href="#beforeSerialize">beforeSerialize</a><br>
-<a href="#beforeSignificate">beforeSignificate</a><br>
-<a href="#beforeSingle">beforeSingle</a><br>
-<a href="#beforeString">beforeString</a><br>
-<a href="#deregister">deregister</a><br>
-<a href="#null">null</a><br>
-<a href="#pop">pop</a><br>
-<a href="#push">push</a><br>
-<a href="#register">register</a><br>
-</td>
-</tr>
- </table>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterAtomic"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterAtomic </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterAtomic ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterBinary"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterBinary </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterBinary ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterClause"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterClause </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterClause (
- self,
- exception,
- variable,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterControl"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterControl </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterControl ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterDefined"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterDefined </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterDefined ( self, result )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterEscape"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterEscape </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterEscape ( self, result )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterEvaluate"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterEvaluate </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterEvaluate ( self, result )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterExecute"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterExecute </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterExecute ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterExpand"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterExpand </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterExpand ( self, result )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterFile"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterFile </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterFile ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterImport"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterImport </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterImport ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterInclude"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterInclude </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterInclude ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterLiteral"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterLiteral </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterLiteral ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterMulti"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterMulti </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterMulti ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterQuote"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterQuote </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterQuote ( self, result )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterSerialize"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterSerialize </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterSerialize ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterSignificate"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterSignificate </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterSignificate ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterSingle"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterSingle </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterSingle ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="afterString"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">afterString </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-afterString ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="atFinalize"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">atFinalize </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-atFinalize ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="atHandle"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">atHandle </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-atHandle ( self, meta )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="atInteract"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">atInteract </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-atInteract ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="atParse"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">atParse </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-atParse (
- self,
- scanner,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="atReady"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">atReady </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-atReady ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="atShutdown"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">atShutdown </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-atShutdown ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="atStartup"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">atStartup </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-atStartup ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="atToken"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">atToken </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-atToken ( self, token )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeAtomic"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeAtomic </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeAtomic (
- self,
- name,
- value,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeBinary"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeBinary </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeBinary (
- self,
- name,
- file,
- chunkSize,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeClause"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeClause </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeClause (
- self,
- catch,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeControl"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeControl </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeControl (
- self,
- type,
- rest,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeDefined"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeDefined </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeDefined (
- self,
- name,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeEscape"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeEscape </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeEscape (
- self,
- string,
- more,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeEvaluate"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeEvaluate </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeEvaluate (
- self,
- expression,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeExecute"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeExecute </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeExecute (
- self,
- statements,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeExpand"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeExpand </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeExpand (
- self,
- string,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeFile"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeFile </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeFile (
- self,
- name,
- file,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeImport"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeImport </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeImport (
- self,
- name,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeInclude"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeInclude </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeInclude (
- self,
- name,
- file,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeLiteral"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeLiteral </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeLiteral ( self, text )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeMulti"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeMulti </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeMulti (
- self,
- name,
- values,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeQuote"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeQuote </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeQuote ( self, string )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeSerialize"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeSerialize </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeSerialize (
- self,
- expression,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeSignificate"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeSignificate </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeSignificate (
- self,
- key,
- value,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeSingle"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeSingle </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeSingle (
- self,
- source,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="beforeString"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">beforeString </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-beforeString (
- self,
- name,
- string,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="deregister"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">deregister </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-deregister ( self, interpreter )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-Error, "hook not associated with this interpreter"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="null"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">null </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-null ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="pop"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">pop </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-pop ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="push"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">push </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-push ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="register"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">register </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-register ( self, interpreter )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: HookError</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: HookError</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An exception associated with hooks.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Error.html">Error</a><br>
-<ul>
-
-Exception<br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 00:58:36 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: InPlaceToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: InPlaceToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An in-place markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Interpreter</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Interpreter</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An interpreter can process chunks of EmPy code.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-
- <table border="0" cellspacing="2" cellpadding="2" width="100%">
- <tr>
- <td align="LEFT" valign="TOP">
-<a href="#__del__">__del__</a><br>
-<a href="#__init__">__init__</a><br>
-<a href="#__repr__">__repr__</a><br>
-<a href="#addHook">addHook</a><br>
-<a href="#areHooksEnabled">areHooksEnabled</a><br>
-<a href="#assign">assign</a><br>
-<a href="#atExit">atExit</a><br>
-<a href="#atomic">atomic</a><br>
-<a href="#attachFilter">attachFilter</a><br>
-<a href="#binary">binary</a><br>
-<a href="#clause">clause</a><br>
-<a href="#clear">clear</a><br>
-<a href="#clearGlobals">clearGlobals</a><br>
-<a href="#clearHooks">clearHooks</a><br>
-<a href="#close">close</a><br>
-<a href="#context">context</a><br>
-<a href="#createDiversion">createDiversion</a><br>
-<a href="#defined">defined</a><br>
-<a href="#deregister">deregister</a><br>
-<a href="#deregisterCallback">deregisterCallback</a><br>
-<a href="#disableHooks">disableHooks</a><br>
-<a href="#enableHooks">enableHooks</a><br>
-<a href="#escape">escape</a><br>
-<a href="#evaluate">evaluate</a><br>
-<a href="#execute">execute</a><br>
-<a href="#expand">expand</a><br>
-<a href="#fail">fail</a><br>
-<a href="#file">file</a><br>
-<a href="#finalize">finalize</a><br>
-<a href="#fix">fix</a><br>
-<a href="#flatten">flatten</a><br>
-<a href="#flush">flush</a><br>
-<a href="#getAllDiversions">getAllDiversions</a><br>
-</td>
-<td align="LEFT" valign="TOP">
-<a href="#getCallback">getCallback</a><br>
-<a href="#getCurrentDiversion">getCurrentDiversion</a><br>
-<a href="#getFilter">getFilter</a><br>
-<a href="#getGlobals">getGlobals</a><br>
-<a href="#getHooks">getHooks</a><br>
-<a href="#getPrefix">getPrefix</a><br>
-<a href="#handle">handle</a><br>
-<a href="#identify">identify</a><br>
-<a href="#import_">import_</a><br>
-<a href="#include">include</a><br>
-<a href="#installProxy">installProxy</a><br>
-<a href="#interact">interact</a><br>
-<a href="#invoke">invoke</a><br>
-<a href="#invokeCallback">invokeCallback</a><br>
-<a href="#invokeHook">invokeHook</a><br>
-<a href="#literal">literal</a><br>
-<a href="#meta">meta</a><br>
-<a href="#multi">multi</a><br>
-<a href="#nullFilter">nullFilter</a><br>
-<a href="#ok">ok</a><br>
-<a href="#parse">parse</a><br>
-<a href="#playAllDiversions">playAllDiversions</a><br>
-<a href="#playDiversion">playDiversion</a><br>
-<a href="#pop">pop</a><br>
-<a href="#popContext">popContext</a><br>
-<a href="#purgeAllDiversions">purgeAllDiversions</a><br>
-<a href="#purgeDiversion">purgeDiversion</a><br>
-<a href="#push">push</a><br>
-<a href="#pushContext">pushContext</a><br>
-<a href="#quote">quote</a><br>
-<a href="#ready">ready</a><br>
-<a href="#register">register</a><br>
-<a href="#registerCallback">registerCallback</a><br>
-</td>
-<td align="LEFT" valign="TOP">
-<a href="#removeHook">removeHook</a><br>
-<a href="#replayAllDiversions">replayAllDiversions</a><br>
-<a href="#replayDiversion">replayDiversion</a><br>
-<a href="#reset">reset</a><br>
-<a href="#resetFilter">resetFilter</a><br>
-<a href="#restore">restore</a><br>
-<a href="#restoreGlobals">restoreGlobals</a><br>
-<a href="#retrieveDiversion">retrieveDiversion</a><br>
-<a href="#safe">safe</a><br>
-<a href="#save">save</a><br>
-<a href="#saveGlobals">saveGlobals</a><br>
-<a href="#serialize">serialize</a><br>
-<a href="#setContextLine">setContextLine</a><br>
-<a href="#setContextName">setContextName</a><br>
-<a href="#setFilter">setFilter</a><br>
-<a href="#setGlobals">setGlobals</a><br>
-<a href="#setPrefix">setPrefix</a><br>
-<a href="#shutdown">shutdown</a><br>
-<a href="#significate">significate</a><br>
-<a href="#single">single</a><br>
-<a href="#startDiversion">startDiversion</a><br>
-<a href="#stopDiverting">stopDiverting</a><br>
-<a href="#stream">stream</a><br>
-<a href="#string">string</a><br>
-<a href="#tokenize">tokenize</a><br>
-<a href="#unfix">unfix</a><br>
-<a href="#update">update</a><br>
-<a href="#updateGlobals">updateGlobals</a><br>
-<a href="#wrap">wrap</a><br>
-<a href="#write">write</a><br>
-<a href="#writelines">writelines</a><br>
-</td>
-</tr>
- </table>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__del__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__del__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__del__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ (
- self,
- output=None,
- argv=None,
- prefix=DEFAULT_PREFIX,
- pseudo=None,
- options=None,
- globals=None,
- hooks=None,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__repr__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__repr__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__repr__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="addHook"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">addHook </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-addHook (
- self,
- hook,
- prepend=False,
- )
-
-</pre></font>
-
-<p>Add a new hook; optionally insert it rather than appending it.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="areHooksEnabled"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">areHooksEnabled </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-areHooksEnabled ( self )
-
-</pre></font>
-
-<p>Return whether or not hooks are presently enabled.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="assign"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">assign </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-assign (
- self,
- name,
- value,
- locals=None,
- )
-
-</pre></font>
-
-<p>Do a potentially complex (including tuple unpacking) assignment.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="atExit"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">atExit </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-atExit ( self, callable )
-
-</pre></font>
-
-<p>Register a function to be called at exit.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="atomic"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">atomic </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-atomic (
- self,
- name,
- value,
- locals=None,
- )
-
-</pre></font>
-
-<p>Do an atomic assignment.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="attachFilter"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">attachFilter </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-attachFilter ( self, shortcut )
-
-</pre></font>
-
-<p>Attach a single filter to the end of the current filter chain.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="binary"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">binary </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-binary (
- self,
- file,
- name='<binary>',
- chunkSize=0,
- locals=None,
- )
-
-</pre></font>
-
-<p>Parse the entire contents of a file-like object, in chunks.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="clause"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">clause </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-clause (
- self,
- catch,
- locals=None,
- )
-
-</pre></font>
-
-<p>Given the string representation of an except clause, turn it into
- a 2-tuple consisting of the class name, and either a variable name
- or None.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="clear"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">clear </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-clear ( self )
-
-</pre></font>
-
-<p>Clear out the globals dictionary with a brand new one.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="clearGlobals"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">clearGlobals </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-clearGlobals ( self )
-
-</pre></font>
-
-<p>Clear out the globals with a brand new dictionary.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="clearHooks"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">clearHooks </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-clearHooks ( self )
-
-</pre></font>
-
-<p>Clear all hooks.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="close"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">close </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-close ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="context"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">context </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-context ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="createDiversion"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">createDiversion </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-createDiversion ( self, name )
-
-</pre></font>
-
-<p>Create a diversion (but do not divert to it) if it does not
- already exist.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="defined"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">defined </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-defined (
- self,
- name,
- locals=None,
- )
-
-</pre></font>
-
-<p>Return a Boolean indicating whether or not the name is
- defined either in the locals or the globals.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="deregister"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">deregister </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-deregister ( self, hook )
-
-</pre></font>
-
-<p>Remove an already registered hook.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="deregisterCallback"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">deregisterCallback </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-deregisterCallback ( self )
-
-</pre></font>
-
-<p>Remove any previously registered callback with this interpreter.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="disableHooks"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">disableHooks </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-disableHooks ( self )
-
-</pre></font>
-
-<p>Disable hooks.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="enableHooks"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">enableHooks </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-enableHooks ( self )
-
-</pre></font>
-
-<p>Enable hooks.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="escape"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">escape </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-escape (
- self,
- data,
- more='',
- )
-
-</pre></font>
-
-<p>Escape a string so that nonprintable characters are replaced
- with compatible EmPy expansions.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="evaluate"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">evaluate </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-evaluate (
- self,
- expression,
- locals=None,
- )
-
-</pre></font>
-
-<p>Evaluate an expression.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="execute"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">execute </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-execute (
- self,
- statements,
- locals=None,
- )
-
-</pre></font>
-
-<p>Execute a statement.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="expand"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">expand </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-expand (
- self,
- data,
- locals=None,
- )
-
-</pre></font>
-
-<p>Do an explicit expansion on a subordinate stream.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="fail"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">fail </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-fail (
- self,
- error,
- fatal=False,
- )
-
-</pre></font>
-
-<p>Handle an actual error that occurred.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="file"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">file </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-file (
- self,
- file,
- name='<file>',
- locals=None,
- )
-
-</pre></font>
-
-<p>Parse the entire contents of a file-like object, line by line.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="finalize"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">finalize </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-finalize ( self )
-
-</pre></font>
-
-<p>Execute any remaining final routines.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="fix"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">fix </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-fix ( self )
-
-</pre></font>
-
-<p>Reset the globals, stamping in the pseudomodule.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-Error, "interpreter globals collision"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flatten"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flatten </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flatten ( self, keys=None )
-
-</pre></font>
-
-<p>Flatten the contents of the pseudo-module into the globals
- namespace.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flush ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="getAllDiversions"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">getAllDiversions </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-getAllDiversions ( self )
-
-</pre></font>
-
-<p>Get the names of all existing diversions.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="getCallback"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">getCallback </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-getCallback ( self )
-
-</pre></font>
-
-<p>Get the callback registered with this interpreter, or None.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="getCurrentDiversion"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">getCurrentDiversion </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-getCurrentDiversion ( self )
-
-</pre></font>
-
-<p>Get the name of the current diversion.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="getFilter"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">getFilter </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-getFilter ( self )
-
-</pre></font>
-
-<p>Get the current filter.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="getGlobals"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">getGlobals </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-getGlobals ( self )
-
-</pre></font>
-
-<p>Retrieve the globals.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="getHooks"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">getHooks </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-getHooks ( self )
-
-</pre></font>
-
-<p>Get the current hooks.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="getPrefix"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">getPrefix </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-getPrefix ( self )
-
-</pre></font>
-
-<p>Get the current prefix.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="handle"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">handle </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-handle ( self, meta )
-
-</pre></font>
-
-<p>Handle a MetaError.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="identify"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">identify </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-identify ( self )
-
-</pre></font>
-
-<p>Identify the topmost context with a 2-tuple of the name and
- line number.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="import_"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">import_ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-import_ (
- self,
- name,
- locals=None,
- )
-
-</pre></font>
-
-<p>Do an import.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="include"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">include </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-include (
- self,
- fileOrFilename,
- locals=None,
- )
-
-</pre></font>
-
-<p>Do an include pass on a file or filename.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="installProxy"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">installProxy </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-installProxy ( self )
-
-</pre></font>
-
-<p>Install a proxy if necessary.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-Error, "interpreter stdout proxy lost"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="interact"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">interact </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-interact ( self )
-
-</pre></font>
-
-<p>Perform interaction.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="invoke"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">invoke </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-invoke (
- self,
- _name,
- **keywords,
- )
-
-</pre></font>
-
-<p>Invoke the hook(s) associated with the hook name, should they
- exist.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="invokeCallback"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">invokeCallback </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-invokeCallback ( self, contents )
-
-</pre></font>
-
-<p>Invoke the callback.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-Error, "custom markup invoked with no defined callback"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="invokeHook"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">invokeHook </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-invokeHook (
- self,
- _name,
- **keywords,
- )
-
-</pre></font>
-
-<p>Manually invoke a hook.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="literal"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">literal </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-literal ( self, text )
-
-</pre></font>
-
-<p>Process a string literal.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="meta"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">meta </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-meta ( self, exc=None )
-
-</pre></font>
-
-<p>Construct a MetaError for the interpreter's current state.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="multi"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">multi </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-multi (
- self,
- names,
- values,
- locals=None,
- )
-
-</pre></font>
-
-<p>Do a (potentially recursive) assignment.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-TypeError, "unpack non-sequence"<br>
-ValueError, "unpack tuple of wrong size"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="nullFilter"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">nullFilter </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-nullFilter ( self )
-
-</pre></font>
-
-<p>Install a filter that will consume all text.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="ok"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">ok </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-ok ( self )
-
-</pre></font>
-
-<p>Is the interpreter still active?</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="parse"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">parse </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-parse (
- self,
- scanner,
- locals=None,
- )
-
-</pre></font>
-
-<p>Parse and run as much from this scanner as possible.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="playAllDiversions"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">playAllDiversions </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-playAllDiversions ( self )
-
-</pre></font>
-
-<p>Play all existing diversions and then purge them.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="playDiversion"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">playDiversion </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-playDiversion ( self, name )
-
-</pre></font>
-
-<p>Play the given diversion and then purge it.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="pop"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">pop </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-pop ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="popContext"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">popContext </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-popContext ( self )
-
-</pre></font>
-
-<p>Pop the top context.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="purgeAllDiversions"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">purgeAllDiversions </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-purgeAllDiversions ( self )
-
-</pre></font>
-
-<p>Purge all existing diversions.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="purgeDiversion"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">purgeDiversion </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-purgeDiversion ( self, name )
-
-</pre></font>
-
-<p>Eliminate the given diversion.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="push"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">push </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-push ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="pushContext"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">pushContext </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-pushContext (
- self,
- name='<unnamed>',
- line=0,
- )
-
-</pre></font>
-
-<p>Create a new context and push it.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="quote"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">quote </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-quote ( self, data )
-
-</pre></font>
-
-<p>Quote the given string so that if it were expanded it would
- evaluate to the original.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="ready"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">ready </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-ready ( self )
-
-</pre></font>
-
-<p>Declare the interpreter ready for normal operations.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="register"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">register </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-register (
- self,
- hook,
- prepend=False,
- )
-
-</pre></font>
-
-<p>Register the provided hook.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="registerCallback"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">registerCallback </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-registerCallback ( self, callback )
-
-</pre></font>
-
-<p>Register a custom markup callback with this interpreter.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="removeHook"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">removeHook </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-removeHook ( self, hook )
-
-</pre></font>
-
-<p>Remove a preexisting hook.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="replayAllDiversions"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">replayAllDiversions </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-replayAllDiversions ( self )
-
-</pre></font>
-
-<p>Replay all existing diversions without purging them.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="replayDiversion"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">replayDiversion </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-replayDiversion ( self, name )
-
-</pre></font>
-
-<p>Replay the diversion without purging it.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="reset"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">reset </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-reset ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="resetFilter"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">resetFilter </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-resetFilter ( self )
-
-</pre></font>
-
-<p>Reset the filter so that it does no filtering.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="restore"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">restore </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-restore ( self, destructive=True )
-
-</pre></font>
-
-<p>Restore the topmost historic globals.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="restoreGlobals"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">restoreGlobals </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-restoreGlobals ( self, destructive=True )
-
-</pre></font>
-
-<p>Restore the most recently saved copy of the globals.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="retrieveDiversion"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">retrieveDiversion </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-retrieveDiversion ( self, name )
-
-</pre></font>
-
-<p>Retrieve the diversion object associated with the name.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="safe"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">safe </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-safe (
- self,
- scanner,
- final=False,
- locals=None,
- )
-
-</pre></font>
-
-<p>Do a protected parse. Catch transient parse errors; if
- final is true, then make a final pass with a terminator,
- otherwise ignore the transient parse error (more data is
- pending).</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="save"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">save </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-save ( self, deep=True )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="saveGlobals"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">saveGlobals </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-saveGlobals ( self, deep=True )
-
-</pre></font>
-
-<p>Save a copy of the globals off onto the history stack.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="serialize"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">serialize </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-serialize (
- self,
- expression,
- locals=None,
- )
-
-</pre></font>
-
-<p>Do an expansion, involving evaluating an expression, then
- converting it to a string and writing that string to the
- output if the evaluation is not None.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="setContextLine"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">setContextLine </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-setContextLine ( self, line )
-
-</pre></font>
-
-<p>Set the name of the topmost context.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="setContextName"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">setContextName </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-setContextName ( self, name )
-
-</pre></font>
-
-<p>Set the name of the topmost context.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="setFilter"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">setFilter </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-setFilter ( self, shortcut )
-
-</pre></font>
-
-<p>Set the filter.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="setGlobals"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">setGlobals </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-setGlobals ( self, globals )
-
-</pre></font>
-
-<p>Set the globals to the specified dictionary.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="setPrefix"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">setPrefix </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-setPrefix ( self, prefix )
-
-</pre></font>
-
-<p>Set the prefix.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="shutdown"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">shutdown </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-shutdown ( self )
-
-</pre></font>
-
-<p>Declare this interpreting session over; close the stream file
- object. This method is idempotent.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="significate"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">significate </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-significate (
- self,
- key,
- value=None,
- locals=None,
- )
-
-</pre></font>
-
-<p>Declare a significator.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="single"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">single </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-single (
- self,
- source,
- locals=None,
- )
-
-</pre></font>
-
-<p>Execute an expression or statement, just as if it were
- entered into the Python interactive interpreter.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="startDiversion"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">startDiversion </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-startDiversion ( self, name )
-
-</pre></font>
-
-<p>Start diverting to the given diversion name.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="stopDiverting"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">stopDiverting </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-stopDiverting ( self )
-
-</pre></font>
-
-<p>Stop any diverting.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="stream"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">stream </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-stream ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string (
- self,
- data,
- name='<string>',
- locals=None,
- )
-
-</pre></font>
-
-<p>Parse a string.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="tokenize"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">tokenize </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-tokenize ( self, name )
-
-</pre></font>
-
-<p>Take an lvalue string and return a name or a (possibly recursive)
- list of names.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "unexpected assignment token: '%s'" % garbage<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="unfix"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">unfix </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-unfix ( self )
-
-</pre></font>
-
-<p>Remove the pseudomodule (if present) from the globals.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="update"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">update </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-update ( self, other )
-
-</pre></font>
-
-<p>Update the current globals dictionary with another dictionary.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="updateGlobals"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">updateGlobals </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-updateGlobals ( self, otherGlobals )
-
-</pre></font>
-
-<p>Merge another mapping object into this interpreter's globals.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="wrap"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">wrap </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-wrap (
- self,
- callable,
- args,
- )
-
-</pre></font>
-
-<p>Wrap around an application of a callable and handle errors.
- Return whether no error occurred.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="writelines"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">writelines </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-writelines ( self, stuff )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: LineBufferedFilter</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: LineBufferedFilter</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A line-buffered filter only lets data through when it sees
- whole lines.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="BufferedFilter.html">BufferedFilter</a><br>
-<ul>
-
-<a href="Filter.html">Filter</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#write">write</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: LiteralToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: LiteralToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A literal markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: MaximallyBufferedFilter</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: MaximallyBufferedFilter</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A maximally-buffered filter only lets its data through on the final
- close. It ignores flushes.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="BufferedFilter.html">BufferedFilter</a><br>
-<ul>
-
-<a href="Filter.html">Filter</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#close">close</a><br>
-<a href="#flush">flush</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="close"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">close </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-close ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flush ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: MetaError</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: MetaError</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A wrapper around a real Python exception for including a copy of
- the context.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-Exception<br>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#__str__">__str__</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ (
- self,
- contexts,
- exc,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__str__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__str__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__str__ ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: NullFile</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: NullFile</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A simple class that supports all the file-like object methods
- but simply does nothing at all.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#close">close</a><br>
-<a href="#flush">flush</a><br>
-<a href="#write">write</a><br>
-<a href="#writelines">writelines</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="close"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">close </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-close ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flush ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="writelines"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">writelines </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-writelines ( self, lines )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: NullFilter</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: NullFilter</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A filter that never sends any output to its sink.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Filter.html">Filter</a><br>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#write">write</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: NullToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: NullToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A chunk of data not containing markups.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Token.html">Token</a><br>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#run">run</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self, data )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: ParseError</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: ParseError</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A parse error occurred.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Error.html">Error</a><br>
-<ul>
-
-Exception<br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: PrefixToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: PrefixToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A prefix markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Processor</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Processor</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An entity which is capable of processing a hierarchy of EmPy
- files and building a dictionary of document objects associated
- with them describing their significator contents.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#clear">clear</a><br>
-<a href="#directory">directory</a><br>
-<a href="#file">file</a><br>
-<a href="#identifier">identifier</a><br>
-<a href="#line">line</a><br>
-<a href="#postprocess">postprocess</a><br>
-<a href="#scan">scan</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self, factory=Document )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="clear"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">clear </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-clear ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="directory"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">directory </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-directory (
- self,
- basename,
- dirCriteria,
- fileCriteria,
- depth=None,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="file"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">file </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-file (
- self,
- document,
- file,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="identifier"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">identifier </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-identifier (
- self,
- pathname,
- filename,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="line"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">line </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-line (
- self,
- document,
- line,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="postprocess"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">postprocess </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-postprocess ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan (
- self,
- basename,
- extensions=DEFAULT_EMPY_EXTENSIONS,
- )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: ProxyFile</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: ProxyFile</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>The proxy file object that is intended to take the place of
- sys.stdout. The proxy can manage a stack of file objects it is
- writing to, and an underlying raw file object.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-
- <table border="0" cellspacing="2" cellpadding="2" width="100%">
- <tr>
- <td align="LEFT" valign="TOP">
-<a href="#__init__">__init__</a><br>
-<a href="#_testProxy">_testProxy</a><br>
-<a href="#clear">clear</a><br>
-<a href="#close">close</a><br>
-<a href="#current">current</a><br>
-</td>
-<td align="LEFT" valign="TOP">
-<a href="#flush">flush</a><br>
-<a href="#pop">pop</a><br>
-<a href="#push">push</a><br>
-<a href="#write">write</a><br>
-<a href="#writelines">writelines</a><br>
-</td>
-</tr>
- </table>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self, bottom )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="_testProxy"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">_testProxy </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-_testProxy ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="clear"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">clear </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-clear ( self, interpreter )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="close"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">close </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-close ( self )
-
-</pre></font>
-
-<p>Close the current file. If the current file is the bottom, then
- close it and dispose of it.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="current"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">current </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-current ( self )
-
-</pre></font>
-
-<p>Get the current stream to write to.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flush ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="pop"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">pop </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-pop ( self, interpreter )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="push"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">push </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-push ( self, interpreter )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="writelines"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">writelines </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-writelines ( self, lines )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: ReprToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: ReprToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A repr markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Scanner</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Scanner</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A scanner holds a buffer for lookahead parsing and has the
- ability to scan for special symbols and indicators in that
- buffer.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-
- <table border="0" cellspacing="2" cellpadding="2" width="100%">
- <tr>
- <td align="LEFT" valign="TOP">
-<a href="#__getitem__">__getitem__</a><br>
-<a href="#__getslice__">__getslice__</a><br>
-<a href="#__init__">__init__</a><br>
-<a href="#__len__">__len__</a><br>
-<a href="#__nonzero__">__nonzero__</a><br>
-<a href="#acquire">acquire</a><br>
-<a href="#advance">advance</a><br>
-<a href="#check">check</a><br>
-<a href="#chop">chop</a><br>
-</td>
-<td align="LEFT" valign="TOP">
-<a href="#complex">complex</a><br>
-<a href="#feed">feed</a><br>
-<a href="#find">find</a><br>
-<a href="#last">last</a><br>
-<a href="#nested">nested</a><br>
-<a href="#next">next</a><br>
-<a href="#one">one</a><br>
-<a href="#phrase">phrase</a><br>
-<a href="#quote">quote</a><br>
-</td>
-<td align="LEFT" valign="TOP">
-<a href="#read">read</a><br>
-<a href="#release">release</a><br>
-<a href="#rest">rest</a><br>
-<a href="#retreat">retreat</a><br>
-<a href="#set">set</a><br>
-<a href="#simple">simple</a><br>
-<a href="#sync">sync</a><br>
-<a href="#unsync">unsync</a><br>
-<a href="#word">word</a><br>
-</td>
-</tr>
- </table>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__getitem__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__getitem__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__getitem__ ( self, index )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__getslice__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__getslice__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__getslice__ (
- self,
- start,
- stop,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ (
- self,
- prefix,
- data='',
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__len__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__len__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__len__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__nonzero__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__nonzero__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__nonzero__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="acquire"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">acquire </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-acquire ( self )
-
-</pre></font>
-
-<p>Lock the scanner so it doesn't destroy data on sync.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="advance"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">advance </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-advance ( self, count=1 )
-
-</pre></font>
-
-<p>Advance the pointer count characters.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="check"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">check </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-check (
- self,
- i,
- archetype=None,
- )
-
-</pre></font>
-
-<p>Scan for the next single or triple quote, with the specified
- archetype. Return the found quote or None.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-TransientParseError, "need to scan for rest of quote"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="chop"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">chop </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-chop (
- self,
- count=None,
- slop=0,
- )
-
-</pre></font>
-
-<p>Chop the first count + slop characters off the front, and return
- the first count. If count is not specified, then return
- everything.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-TransientParseError, "not enough data to read"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="complex"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">complex </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-complex (
- self,
- enter,
- exit,
- start=0,
- end=None,
- skip=None,
- )
-
-</pre></font>
-
-<p>Scan from i for an ending sequence, respecting quotes,
- entries and exits.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-TransientParseError, "expecting end of complex expression"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="feed"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">feed </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-feed ( self, data )
-
-</pre></font>
-
-<p>Feed some more data to the scanner.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="find"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">find </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-find (
- self,
- sub,
- start=0,
- end=None,
- )
-
-</pre></font>
-
-<p>Find the next occurrence of the character, or return -1.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="last"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">last </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-last (
- self,
- char,
- start=0,
- end=None,
- )
-
-</pre></font>
-
-<p>Find the first character that is <u>not</u> the specified character.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-TransientParseError, "expecting other than %s" % char<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="nested"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">nested </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-nested (
- self,
- enter,
- exit,
- start=0,
- end=None,
- )
-
-</pre></font>
-
-<p>Scan from i for an ending sequence, respecting entries and exits
- only.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-TransientParseError, "expecting end of complex expression"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="next"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">next </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-next (
- self,
- target,
- start=0,
- end=None,
- mandatory=False,
- )
-
-</pre></font>
-
-<p>Scan for the next occurrence of one of the characters in
- the target string; optionally, make the scan mandatory.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "expecting %s, not found" % target<br>
-TransientParseError, "expecting ending character"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="one"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">one </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-one ( self )
-
-</pre></font>
-
-<p>Parse and return one token, or None if the scanner is empty.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "unknown markup: %s%s" %( self.prefix, first )<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="phrase"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">phrase </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-phrase ( self, start=0 )
-
-</pre></font>
-
-<p>Scan from i for a phrase (e.g., <code>word</code>, <code>f(a, b, c)</code>, 'a<a href="#refi">[i]</a>', or
- combinations like 'x<a href="#refi">[i]</a>(a)'.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "curly braces can't open simple expressions"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="quote"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">quote </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-quote (
- self,
- start=0,
- end=None,
- mandatory=False,
- )
-
-</pre></font>
-
-<p>Scan for the end of the next quote.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "expecting end of string literal"<br>
-TransientParseError, "expecting end of string literal"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="read"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">read </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-read (
- self,
- i=0,
- count=1,
- )
-
-</pre></font>
-
-<p>Read count chars starting from i; raise a transient error if
- there aren't enough characters remaining.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-TransientParseError, "need more data to read"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="release"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">release </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-release ( self )
-
-</pre></font>
-
-<p>Unlock the scanner.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="rest"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">rest </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-rest ( self )
-
-</pre></font>
-
-<p>Get the remainder of the buffer.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="retreat"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">retreat </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-retreat ( self, count=1 )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "can't retreat back over synced out chars"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="set"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">set </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-set ( self, data )
-
-</pre></font>
-
-<p>Start the scanner digesting a new batch of data; start the pointer
- over from scratch.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="simple"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">simple </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-simple ( self, start=0 )
-
-</pre></font>
-
-<p>Scan from i for a simple expression, which consists of one
- more phrases separated by dots.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="sync"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">sync </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-sync ( self )
-
-</pre></font>
-
-<p>Sync up the buffer with the read head.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="unsync"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">unsync </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-unsync ( self )
-
-</pre></font>
-
-<p>Undo changes; reset the read head.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="word"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">word </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-word ( self, start=0 )
-
-</pre></font>
-
-<p>Scan from i for a simple word.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-TransientParseError, "expecting end of word"<br>
-
-</td></tr>
-</table>
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: SignificatorToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: SignificatorToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A significator markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-ParseError, "no whitespace between % and key"<br>
-ParseError, "significator must have nonblank key"<br>
-TransientParseError, "significator expects newline"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: SimpleExpressionToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: SimpleExpressionToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A simple expression markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: SizeBufferedFilter</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: SizeBufferedFilter</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A size-buffered filter only in fixed size chunks (excepting the
- final chunk).</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="BufferedFilter.html">BufferedFilter</a><br>
-<ul>
-
-<a href="Filter.html">Filter</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#write">write</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self, bufferSize )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Stack</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Stack</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A simple stack that behaves as a sequence (with 0 being the top
- of the stack, not the bottom).</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-
- <table border="0" cellspacing="2" cellpadding="2" width="100%">
- <tr>
- <td align="LEFT" valign="TOP">
-<a href="#__getitem__">__getitem__</a><br>
-<a href="#__init__">__init__</a><br>
-<a href="#__len__">__len__</a><br>
-<a href="#__nonzero__">__nonzero__</a><br>
-<a href="#__repr__">__repr__</a><br>
-<a href="#clone">clone</a><br>
-</td>
-<td align="LEFT" valign="TOP">
-<a href="#filter">filter</a><br>
-<a href="#pop">pop</a><br>
-<a href="#purge">purge</a><br>
-<a href="#push">push</a><br>
-<a href="#top">top</a><br>
-</td>
-</tr>
- </table>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__getitem__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__getitem__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__getitem__ ( self, index )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self, seq=None )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__len__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__len__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__len__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__nonzero__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__nonzero__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__nonzero__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__repr__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__repr__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__repr__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="clone"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">clone </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-clone ( self )
-
-</pre></font>
-
-<p>Create a duplicate of this stack.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="filter"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">filter </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-filter ( self, function )
-
-</pre></font>
-
-<p>Filter the elements of the stack through the function.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="pop"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">pop </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-pop ( self )
-
-</pre></font>
-
-<p>Pop the top element off the stack and return it.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-StackUnderflowError, "stack is empty for pop"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="purge"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">purge </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-purge ( self )
-
-</pre></font>
-
-<p>Purge the stack.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="push"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">push </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-push ( self, object )
-
-</pre></font>
-
-<p>Push an element onto the top of the stack.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="top"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">top </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-top ( self )
-
-</pre></font>
-
-<p>Access the top element on the stack.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-StackUnderflowError, "stack is empty for top"<br>
-
-</td></tr>
-</table>
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: StackUnderflowError</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: StackUnderflowError</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A stack underflow.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Error.html">Error</a><br>
-<ul>
-
-Exception<br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: StatementToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: StatementToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A statement markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Stream</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Stream</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A wrapper around an (output) file object which supports
- diversions and filtering.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-
- <table border="0" cellspacing="2" cellpadding="2" width="100%">
- <tr>
- <td align="LEFT" valign="TOP">
-<a href="#__init__">__init__</a><br>
-<a href="#attach">attach</a><br>
-<a href="#close">close</a><br>
-<a href="#create">create</a><br>
-<a href="#divert">divert</a><br>
-<a href="#flush">flush</a><br>
-<a href="#install">install</a><br>
-<a href="#last">last</a><br>
-<a href="#purge">purge</a><br>
-</td>
-<td align="LEFT" valign="TOP">
-<a href="#purgeAll">purgeAll</a><br>
-<a href="#retrieve">retrieve</a><br>
-<a href="#revert">revert</a><br>
-<a href="#shortcut">shortcut</a><br>
-<a href="#undivert">undivert</a><br>
-<a href="#undivertAll">undivertAll</a><br>
-<a href="#write">write</a><br>
-<a href="#writelines">writelines</a><br>
-</td>
-</tr>
- </table>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self, file )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="attach"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">attach </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-attach ( self, shortcut )
-
-</pre></font>
-
-<p>Attached a solitary filter (no sequences allowed here) at the
- end of the current filter chain.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="close"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">close </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-close ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="create"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">create </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-create ( self, name )
-
-</pre></font>
-
-<p>Create a diversion if one does not already exist, but do not
- divert to it yet.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-DiversionError, "diversion name must be non-None"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="divert"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">divert </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-divert ( self, name )
-
-</pre></font>
-
-<p>Start diverting.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-DiversionError, "diversion name must be non-None"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flush ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="install"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">install </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-install ( self, shortcut=None )
-
-</pre></font>
-
-<p>Install a new filter; None means no filter. Handle all the
- special shortcuts for filters here.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="last"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">last </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-last ( self )
-
-</pre></font>
-
-<p>Find the last filter in the current filter chain, or None if
- there are no filters installed.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="purge"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">purge </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-purge ( self, name )
-
-</pre></font>
-
-<p>Purge the specified diversion.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-DiversionError, "diversion name must be non-None"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="purgeAll"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">purgeAll </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-purgeAll ( self )
-
-</pre></font>
-
-<p>Eliminate all existing diversions.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="retrieve"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">retrieve </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-retrieve ( self, name )
-
-</pre></font>
-
-<p>Retrieve the given diversion.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-DiversionError, "diversion name must be non-None"<br>
-DiversionError, "nonexistent diversion: %s" % name<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="revert"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">revert </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-revert ( self )
-
-</pre></font>
-
-<p>Reset any current diversions.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="shortcut"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">shortcut </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-shortcut ( self, shortcut )
-
-</pre></font>
-
-<p>Take a filter shortcut and translate it into a filter, returning
- it. Sequences don't count here; these should be detected
- independently.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-NotImplementedError, "mapping filters not yet supported"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="undivert"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">undivert </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-undivert (
- self,
- name,
- purgeAfterwards=False,
- )
-
-</pre></font>
-
-<p>Undivert a particular diversion.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-DiversionError, "diversion name must be non-None"<br>
-DiversionError, "nonexistent diversion: %s" % name<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="undivertAll"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">undivertAll </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-undivertAll ( self, purgeAfterwards=True )
-
-</pre></font>
-
-<p>Undivert all pending diversions.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="writelines"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">writelines </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-writelines ( self, lines )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: StringFilter</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: StringFilter</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A filter that takes a translation string (256 characters) and
- filters any incoming data through it.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Filter.html">Filter</a><br>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#write">write</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self, table )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-FilterError, "table must be 256-character string"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: StringLiteralToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: StringLiteralToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A string token markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#run">run</a><br>
-<a href="#scan">scan</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="scan"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">scan </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-scan ( self, scanner )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Subsystem</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Subsystem</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>The subsystem class defers file creation so that it can create
- Unicode-wrapped files if desired (and possible).</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#assertUnicode">assertUnicode</a><br>
-<a href="#defaultOpen">defaultOpen</a><br>
-<a href="#initialize">initialize</a><br>
-<a href="#open">open</a><br>
-<a href="#unicodeOpen">unicodeOpen</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="assertUnicode"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">assertUnicode </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-assertUnicode ( self )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-SubsystemError, "Unicode subsystem unavailable"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="defaultOpen"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">defaultOpen </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-defaultOpen (
- self,
- name,
- mode=None,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="initialize"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">initialize </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-initialize (
- self,
- inputEncoding=None,
- outputEncoding=None,
- inputErrors=None,
- outputErrors=None,
- )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-SubsystemError, "Unicode subsystem unavailable"<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="open"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">open </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-open (
- self,
- name,
- mode=None,
- )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="unicodeOpen"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">unicodeOpen </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-unicodeOpen (
- self,
- name,
- mode=None,
- )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: SubsystemError</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: SubsystemError</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An error associated with the Unicode subsystem.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Error.html">Error</a><br>
-<ul>
-
-Exception<br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: Token</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: Token</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>An element of expansion.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__str__">__str__</a><br>
-<a href="#run">run</a><br>
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__str__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__str__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__str__ ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="run"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">run </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-run (
- self,
- interpreter,
- locals,
- )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-NotImplementedError<br>
-
-</td></tr>
-</table>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Exceptions">Exceptions</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-NotImplementedError<br>
-
-</td></tr>
-</table>
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: TransientParseError</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: TransientParseError</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A parse error occurred which may be resolved by feeding more data.
- Such an error reaching the toplevel is an unexpected EOF error.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ParseError.html">ParseError</a><br>
-<ul>
-
-<a href="Error.html">Error</a><br>
-<ul>
-
-Exception<br>
-
-</ul>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: UncloseableFile</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: UncloseableFile</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A simple class which wraps around a delegate file-like object
- and lets everything through except close calls.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-<a href="#close">close</a><br>
-<a href="#flush">flush</a><br>
-<a href="#write">write</a><br>
-<a href="#writelines">writelines</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self, delegate )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="close"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">close </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-close ( self )
-
-</pre></font>
-
-<p>Eat this one.</p>
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="flush"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">flush </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-flush ( self )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="write"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">write </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-write ( self, data )
-
-</pre></font>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="writelines"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">writelines </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-writelines ( self, lines )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: VerboseHook</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: VerboseHook</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A verbose hook that reports all information received by the
- hook interface. This class dynamically scans the Hook base class
- to ensure that all hook methods are properly represented.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="Hook.html">Hook</a><br>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#__init__">__init__</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="__init__"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">__init__ </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-__init__ ( self, output=sys.stderr )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>Class: WhitespaceToken</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">Class: WhitespaceToken</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000">em.py</font>
- </th>
- </tr>
- <tr>
- <td>
-
-<p>A whitespace markup.</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Base Classes">Base Classes</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="ExpansionToken.html">ExpansionToken</a><br>
-<ul>
-
-<a href="Token.html">Token</a><br>
-
-</ul>
-
-</td></tr>
-</table>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Methods">Methods</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<a href="#string">string</a><br>
-
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="string"></a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000">string </font>
- </th>
- </tr>
- <tr>
- <td>
- <font color="#000088"><pre>
-string ( self )
-
-</pre></font>
-
-</td></tr>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="../../../../../../index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Mon Oct 27 01:29:13 2003 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
+++ /dev/null
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html40/loose.dtd">
-
-<html>
-
- <head>
- <title>empy</title>
- </head>
-
- <body bgcolor="#ffffff">
-
- <p><i><a href="index.html">Table of Contents</a></i></p>
-
- <table border="0" cellpadding="5" cellspacing="0" width="100%">
- <tr>
- <th rowspan="2"
- valign="top"
- align="left"
- width="10%"
- bgcolor="#88bbee"><font color="#000000">empy</font>
- </th>
- <th bgcolor="#88bbee"
- width="90%"
- align="right"><font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<h3>Summary</h3>
-<p> A powerful and robust templating system for Python.</p>
-<h3>Overview</h3>
-<p> EmPy is a system for embedding Python expressions and statements
- in template text; it takes an EmPy source file, processes it, and
- produces output. This is accomplished via expansions, which are
- special signals to the EmPy system and are set off by a special
- prefix (by default the at sign, <code>@</code>). EmPy can expand arbitrary
- Python expressions and statements in this way, as well as a
- variety of special forms. Textual data not explicitly delimited
- in this way is sent unaffected to the output, allowing Python to
- be used in effect as a markup language. Also supported are
- callbacks via hooks, recording and playback via diversions, and
- dynamic, chainable filters. The system is highly configurable via
- command line options and embedded commands.</p>
-<p> Expressions are embedded in text with the <code>@(...)</code> notation;
- variations include conditional expressions with <code>@(...?...!...)</code>
- and the ability to handle thrown exceptions with <code>@(...$...)</code>. As
- a shortcut, simple variables and expressions can be abbreviated as
- <code>@variable</code>, <code>@object.attribute</code>, <code>@function(arguments)</code>,
- <code>@sequence</code> <a href="#index"><a href="#refindex">[index]</a></a>, and combinations. Full-fledged statements
- are embedded with <code>@{...}</code>. Control flow in terms of conditional
- or repeated expansion is available with <code>@[...]</code>. A <code>@</code> followed
- by a whitespace character (including a newline) expands to
- nothing, allowing string concatenations and line continuations.
- Comments are indicated with <code>@#</code> and consume the rest of the line,
- up to and including the trailing newline. <code>@%</code> indicate
- "significators," which are special forms of variable assignment
- intended to specify per-file identification information in a
- format which is easy to parse externally. Context name and line
- number changes can be done with <code>@?</code> and <code>@!</code> respectively.
- '@<...>' markups are customizeable by the user and can be used for
- any desired purpose. Escape sequences analogous to those in C can
- be specified with <code>@\...</code>, and finally a <code>@@</code> sequence expands to
- a single literal at sign.</p>
-<h3>Getting the software</h3>
-<p> The current version of empy is 3.3.2.</p>
-<p> The latest version of the software is available in a tarball here:
- <a href="http://www.alcyone.com/software/empy/empy-latest.tar.gz">http://www.alcyone.com/software/empy/empy-latest.tar.gz</a>.</p>
-<p> The official URL for this Web site is
- <a href="http://www.alcyone.com/software/empy/">http://www.alcyone.com/software/empy/</a>.</p>
-<h3>Requirements</h3>
-<p> EmPy should work with any version of Python from 2.4 onward,
- including 3.x.</p>
-<h3>License</h3>
-<p> This code is released under the <a href="http://www.gnu.org/copyleft/lesser.html">LGPL</a>.</p>
-<h3>Mailing lists</h3>
-<p> There are two EmPy related mailing lists available. The first is
- a receive-only, very low volume list for important announcements
- (including releases). To subscribe, send an email to
- <a href="mailto:empy-announce-list-subscribe@alcyone.com">empy-announce-list-subscribe@alcyone.com</a>.</p>
-<p> The second is a general discussion list for topics related to
- EmPy, and is open for everyone to contribute; announcements
- related to EmPy will also be made on this list. The author of
- EmPy (and any future developers) will also be on the list, so it
- can be used not only to discuss EmPy features with other users,
- but also to ask questions of the author(s). To subscribe, send an
- email to <a href="mailto:empy-list-subscribe@alcyone.com">empy-list-subscribe@alcyone.com</a>.</p>
-<h3>Basics</h3>
-<p> EmPy is intended for embedding Python code in otherwise
- unprocessed text. Source files are processed, and the results are
- written to an output file. Normal text is sent to the output
- unchanged, but markups are processed, expanded to their results,
- and then written to the output file as strings (that is, with the
- <code>str</code> function, not <code>repr</code>). The act of processing EmPy source
- and handling markups is called "expansion."</p>
-<p> Code that is processed is executed exactly as if it were entered
- into the Python interpreter; that is, it is executed with the
- equivalent of <code>eval</code> (for expressions) and <code>exec</code> (for
- statements). EmPy is intended to be a very thin (though powerful)
- layer on top of a running Python system; Python and EmPy files can
- be mixed together (via command line options) without
- complications.</p>
-<p> By default the embedding prefix is the at sign (<code>@</code>), which
- appears neither in valid Python code nor commonly in arbitrary
- texts; it can be overridden with the -p option (or with the
- <code>empy.setPrefix</code> function). The prefix indicates to the EmPy
- interpreter that a special sequence follows and should be
- processed rather than sent to the output untouched (to indicate a
- literal at sign, it can be doubled as in <code>@@</code>).</p>
-<p> When the interpreter starts processing its target file, no modules
- are imported by default, save the <code>empy</code> pseudomodule (see below),
- which is placed in the globals; the <code>empy</code> pseudomodule is
- associated with a particular interpreter -- in fact, they are the
- same object -- and it is important that it not be removed from
- that interpreter's globals, nor that it be shared with other
- interpreters running concurrently (a name other than <code>empy</code> can be
- specified with the -m option). The globals are not cleared or
- reset in any way. It is perfectly legal to set variables or
- explicitly import modules and then use them in later markups,
- <em>e.g.</em>, <code>@{import time} ... @time.time()</code>. Scoping rules are as
- in normal Python, although all defined variables and objects are
- taken to be in the global namespace.</p>
-<p> Indentation is significant in Python, and therefore is also
- significant in EmPy. EmPy statement markups (<code>@{...}</code>), when
- spanning multiple lines, must be flush with the left margin. This
- is because (multiline) statement markups are not treated specially
- in EmPy and are simply passed to the Python interpreter, where
- indentation is significant.</p>
-<p> Activities you would like to be done before any processing of the
- main EmPy file can be specified with the -I, -D, -E, -F, and -P
- options. -I imports modules, -D executes a Python variable
- assignment, -E executes an arbitrary Python (not EmPy) statement,
- -F executes a Python (not EmPy) file, and -P processes an EmPy
- (not Python) file. These operations are done in the order they
- appear on the command line; any number of each (including, of
- course, zero) can be used.</p>
-<h3>Expansions</h3>
-<p> The following markups are supported. For concreteness below, <code>@</code>
- is taken for the sake of argument to be the prefix character,
- although this can be changed.</p>
-<dl>
-<dt> <strong><code>@# COMMENT NEWLINE</code></strong></dt>
-<dd>A comment. Comments, including the
- trailing newline, are stripped out completely. Comments should
- only be present outside of expansions. The comment itself is
- not processed in any way: It is completely discarded. This
- allows <code>@#</code> comments to be used to disable markups. <em>Note:</em> As
- special support for "bangpaths" in Unix-like operating systems,
- if the first line of a file (or indeed any context) begins with
- <code>#!</code>, and the interpreter has a <code>processBangpaths</code> option set to
- true (default), it is treated as a <code>@#</code> comment. A <code>#!</code>
- sequence appearing anywhere else will be handled literally and
- unaltered in the expansion. Example:
-<pre>
- @# This line is a comment.
- @# This will NOT be expanded: @x.
-</pre>
-</dd>
-<dt> <strong><code>@? NAME NEWLINE</code></strong></dt>
-<dd>Set the name of the current context to be
- the given string. Variables are not allowed here; the name is
- treated as a literal. (If you wish to use arbitrary
- expressions, use the <code>empy.setContextName</code> function instead.)
- Example:
-<pre>
- @?NewName
- The context name is now @empy.identify()[0] (NewName).
-</pre>
-</dd>
-<dt> <strong><code>@! INTEGER NEWLINE</code></strong></dt>
-<dd>Set the line number of the current
- context to be the given integer value; this is similar to the
- <code>#line</code> C preprocessor directive. This is done in such a way
- that the <em>next</em> line will have the specified numeric value, not
- the current one. Expressions are not allowed here; the number
- must be a literal integer. (If you wish to use arbitrary
- expressions, use the <code>empy.setContextLine</code> function instead.)
- Example:
-<pre>
- @!100
- The context line is now @empy.identify()[1] (100).
-</pre>
-</dd>
-<dt> <strong><code>@ WHITESPACE</code></strong></dt>
-<dd>A <code>@</code> followed by one whitespace character
- (a space, horizontal tab, vertical tab, carriage return, or
- newline) is expanded to nothing; it serves as a way to
- explicitly separate two elements which might otherwise be
- interpreted as being the same symbol (such as <code>@name@ s</code> to mean
- <code>@(name)s</code> -- see below). Also, since a newline qualifies as
- whitespace here, the lone <code>@</code> at the end of a line represents a
- line continuation, similar to the backslash in other languages.
- Coupled with statement expansion below, spurious newlines can be
- eliminated in statement expansions by use of the <code>@{...}@</code>
- construct. Example:
-<pre>
- This will appear as one word: salt@ water.
- This is a line continuation; @
- this text will appear on the same line.
-</pre>
-</dd>
-<dt> <strong><code>@\ ESCAPE_CODE</code></strong></dt>
-<dd>An escape code. Escape codes in EmPy are
- similar to C-style escape codes, although they all begin with
- the prefix character. Valid escape codes include:<dl>
-<dt> <code>@\0</code></dt>
-<dd>NUL, null</dd>
-<dt> <code>@\a</code></dt>
-<dd>BEL, bell</dd>
-<dt> <code>@\b</code></dt>
-<dd>BS, backspace</dd>
-<dt> <code>@\d</code></dt>
-<dd>three-digital decimal code DDD</dd>
-<dt> <code>@\e</code></dt>
-<dd>ESC, escape</dd>
-<dt> <code>@\f</code></dt>
-<dd>FF, form feed</dd>
-<dt> <code>@\h</code></dt>
-<dd>DEL, delete</dd>
-<dt> <code>@\n</code></dt>
-<dd>LF, linefeed character, newline</dd>
-<dt> <code>@\oOOO</code></dt>
-<dd>three-digit octal code OOO</dd>
-<dt> <code>@\qQQQQ</code></dt>
-<dd>four-digit quaternary code QQQQ</dd>
-<dt> <code>@\r</code></dt>
-<dd>CR, carriage return</dd>
-<dt> <code>@\s</code></dt>
-<dd>SP, space</dd>
-<dt> <code>@\t</code></dt>
-<dd>HT, horizontal tab</dd>
-<dt> <code>@\v</code></dt>
-<dd>VT, vertical tab</dd>
-<dt> <code>@\xHH</code></dt>
-<dd>two-digit hexadecimal code HH</dd>
-<dt> <code>@\z</code></dt>
-<dd>EOT, end of transmission</dd>
-<dt> <code>@^X</code></dt>
-<dd>the control character ^X</dd>
-</dl>
-<p> Unlike in C-style escape codes, escape codes taking some number
- of digits afterward always take the same number to prevent
- ambiguities. Furthermore, unknown escape codes are treated as
- parse errors to discourage potential subtle mistakes. Note
- that, while <code>@\0</code> represents the NUL character, to represent an
- octal code, one must use <code>@\o...</code>, in contrast to C. Example:
-<pre>
- This embeds a newline.@\nThis is on the following line.
- This beeps!@\a
- There is a tab here:@\tSee?
- This is the character with octal code 141: @\o141.
-</pre>
-</p>
-</dd>
-<dt> <strong><code>@@</code></strong></dt>
-<dd>A literal at sign (<code>@</code>). To embed two adjacent at
- signs, use <code>@@@@</code>, and so on. Any literal at sign that you wish
- to appear in your text must be written this way, so that it will
- not be processed by the system. <em>Note:</em> If a prefix other than
- <code>@</code> has been chosen via the command line option, one expresses
- that literal prefix by doubling it, not by appending a <code>@</code>.
- Example:
-<pre>
- The prefix character is @@.
- To get the expansion of x you would write @@x.
-</pre>
-</dd>
-<dt> <strong><code>@)</code>, <code>@]</code>, <code>@}</code></strong></dt>
-<dd>These expand to literal close parentheses,
- close brackets, and close braces, respectively; these are
- included for completeness and explicitness only. Example:
-<pre>
- This is a close parenthesis: @).
-</pre>
-</dd>
-<dt> <strong><code>@"..."</code>, <code>@"""..."""</code>, etc.</strong></dt>
-<dd>These string literals expand
- to the literals themselves, so <code>@"test"</code> expands to <code>test</code>.
- Since they are inherently no-operations, the only reason for
- their use is to override their behavior with hooks.</dd>
-<dt> <strong><code>@( EXPRESSION )</code></strong></dt>
-<dd>Evaluate an expression, and expand with
- the string (via a call to <code>str</code>) representation evaluation of
- that expression. Whitespace immediately inside the parentheses
- is ignored; <code>@( expression )</code> is equivalent to <code>@(expression)</code>.
- If the expression evaluates to <code>None</code>, nothing is expanded in
- its place; this allows function calls that depend on side
- effects (such as printing) to be called as expressions. (If you
- really <em>do</em> want a <code>None</code> to appear in the output, then use the
- Python string <code>"None"</code>.) <em>Note:</em> If an expression prints
- something to <code>sys.stdout</code> as a side effect, then that printing
- will be spooled to the output <em>before</em> the expression's return
- value is. Example:
-<pre>
- 2 + 2 is @(2 + 2).
- 4 squared is @(4**2).
- The value of the variable x is @(x).
- This will be blank: @(None).
-</pre>
-</dd>
-<dt> <strong><code>@( TEST ? THEN (! ELSE)_opt ($ EXCEPT)_opt )</code></strong></dt>
-<dd>A special
- form of expression evaluation representing conditional and
- protected evaluation. Evaluate the "test" expression; if it
- evaluates to true (in the Pythonic sense), then evaluate the
- "then" section as an expression and expand with the <code>str</code> of
- that result. If false, then the "else" section is evaluated and
- similarly expanded. The "else" section is optional and, if
- omitted, is equivalent to <code>None</code> (that is, no expansion will
- take place). <em>Note</em>: For backward compatibility, the "else"
- section delimiter, <code>!</code>, may be expressed as a <code>:</code>. This
- behavior is supported but deprecated.<p> If the "except" section is present, then if any of the prior
- expressions raises an exception when evaluated, the expansion
- will be replaced with the evaluation of the except expression.
- (If the "except" expression itself raises, then that exception
- will be propagated normally.) The except section is optional
- and, if omitted, is equivalent to <code>None</code> (that is, no expansion
- will take place). An exception (cough) to this is if one of
- these first expressions raises a SyntaxError; in that case the
- protected evaluation lets the error through without evaluating
- the "except" expression. The intent of this construct is to
- except runtime errors, and if there is actually a syntax error
- in the "try" code, that is a problem that should probably be
- diagnosed rather than hidden. Example:
-<pre>
- What is x? x is @(x ? "true" ! "false").
- Pluralization: How many words? @x word@(x != 1 ? 's').
- The value of foo is @(foo $ "undefined").
- Division by zero is @(x/0 $ "illegal").
-</pre>
-</p>
-</dd>
-<dt> <strong><code>@ SIMPLE_EXPRESSION</code></strong></dt>
-<dd>As a shortcut for the <code>@(...)</code>
- notation, the parentheses can be omitted if it is followed by a
- "simple expression." A simple expression consists of a name
- followed by a series of function applications, array
- subscriptions, or attribute resolutions, with no intervening
- whitespace. For example:
-<ul>
-<li><p>a name, possibly with qualifying attributes (<em>e.g.</em>,
- <code>@value</code>, <code>@os.environ</code>).</p></li>
-<li><p>a straightforward function call (<em>e.g.</em>, <code>@min(2, 3)</code>,
- <code>@time.ctime()</code>), with no space between the function name
- and the open parenthesis.</p></li>
-<li><p>an array subscription (<em>e.g.</em>, '@array<a href="#refindex">[index]</a>',
- '@os.environ<a href="#refname">[name]</a>', with no space between the name and
- the open bracket.</p></li>
-<li><p>any combination of the above (<em>e.g.</em>,
- '@function(args).attr<a href="#refsub">[sub]</a>.other<a href="#refi">[i]</a>(foo)').</p></li>
-
-</ul>
-<p> In essence, simple expressions are expressions that can be
- written ambiguously from text, without intervening space. Note
- that trailing dots are not considered part of the expansion
- (<em>e.g.</em>, <code>@x.</code> is equivalent to <code>@(x).</code>, not <code>@(x.)</code>, which
- would be illegal anyway). Also, whitespace is allowed within
- parentheses or brackets since it is unambiguous, but not between
- identifiers and parentheses, brackets, or dots. Explicit
- <code>@(...)</code> notation can be used instead of the abbreviation when
- concatenation is what one really wants (<em>e.g.</em>, <code>@(word)s</code> for
- simple pluralization of the contents of the variable <code>word</code>).
- As above, if the expression evaluates to the <code>None</code> object,
- nothing is expanded. Note that since a curly appearing where
- EmPy would expect an open parenthesis or bracket in is
- meaningless in Python, it is treated as a parse error (<em>e.g.</em>,
- <code>@x{1, 2}</code> results in an error). Example:
-<pre>
- The value of x is @x.
- The ith value of a is @a[i].
- The result of calling f with q is @f(q).
- The attribute a of x is @x.a.
- The current time is @time.ctime(time.time()).
- The current year is @time.localtime(time.time())[0].
- These are the same: @min(2,3) and @min(2, 3).
- But these are not the same: @min(2, 3) vs. @min (2, 3).
- The plural of @name is @(name)s, or @name@ s.
-</pre>
-</p>
-</dd>
-<dt> <strong><code>@` EXPRESSION `</code></strong></dt>
-<dd>Evaluate a expression, and expand with
- the <code>repr</code> (instead of the <code>str</code> which is the default) of the
- evaluation of that expression. This expansion is primarily
- intended for debugging and is unlikely to be useful in actual
- practice. That is, a <code>@`...`</code> is identical to <code>@(repr(...))</code>.
- Example:
-<pre>
- The repr of the value of x is @`x`.
- This print the Python repr of a module: @`time`.
- This actually does print None: @`None`.
-</pre>
-</dd>
-<dt> <strong><code>@: EXPRESSION : DUMMY :</code></strong></dt>
-<dd>Evaluate an expression and then
- expand to a <code>@:</code>, the original expression, a <code>:</code>, the evaluation
- of the expression, and then a <code>:</code>. The current contents of the
- dummy area are ignored in the new expansion. In this sense it
- is self-evaluating; the syntax is available for use in
- situations where the same text will be sent through the EmPy
- processor multiple times. Example:
-<pre>
- This construct allows self-evaluation:
- @:2 + 2:this will get replaced with 4:
-</pre>
-</dd>
-<dt> <strong><code>@{ STATEMENTS }</code></strong></dt>
-<dd>Execute a (potentially compound)
- statement; statements have no return value, so the expansion is
- not replaced with anything. Multiple statements can either be
- separated on different lines, or with semicolons; indentation is
- significant, just as in normal Python code. Statements,
- however, can have side effects, including printing; output to
- <code>sys.stdout</code> (explicitly or via a <code>print</code> statement) is
- collected by the interpreter and sent to the output (unless this
- behavior is suppressed with the -n option). The usual Python
- indentation rules must be followed, although if the statement
- consists of only one statement, leading and trailing whitespace
- is ignored (<em>e.g.</em>, <code>@{ print time.time() }</code> is equivalent to
- <code>@{print time.time()}</code>). Example:
-<pre>
- @{x = 123}
- @{a = 1; b = 2}
- @{print time.time()}
- @# Note that extra newlines will appear above because of the
- @# newlines trailing the close braces. To suppress them
- @# use a @ before the newline:
- @{
- for i in range(10):
- print "i is %d" % i
- }@
- @{print "Welcome to EmPy."}@
-</pre>
-</dd>
-<dt> <strong><code>@% KEY (WHITESPACE VALUE)_opt NEWLINE</code></strong></dt>
-<dd>Declare a
- significator. Significators consume the whole line (including
- the trailing newline), and consist of a key string containing no
- whitespace, and than optional value prefixed by whitespace. The
- key may not start with or contain internal whitespace, but the
- value may; preceding or following whitespace in the value is
- stripped. Significators are totally optional, and are intended
- to be used for easy external (that is, outside of EmPy)
- identification when used in large scale environments with many
- EmPy files to be processed. The purpose of significators is to
- provide identification information about each file in a special,
- easy-to-parse form so that external programs can process the
- significators and build databases, independently of EmPy.
- Inside of EmPy, when a significator is encountered, its key,
- value pair is translated into a simple assignment of the form
- <code>__KEY__ = VALUE</code> , where "__KEY__" is the key string with two
- underscores on either side and "VALUE" is a Python expression.
- Example:
-<pre>
- @%title "Gravitation"
- @%author "Misner", "Thorne", "Wheeler"
- @%publisher "W.H. Freeman and Company"
- @%pages 1279
- @%keywords 'physics', 'gravity', 'Einstein', 'relativity'
- @%copyright 1970, 1971
-</pre>
-</dd>
-<dt> **'@< CONTENTS >'**</dt>
-<dd>Invoke a custom markup. The custom markup
- is a special markup reserved for use by the user; it has no
- prescribed meaning on its own. If <code>contents</code> is a string
- representing what appears in between the angle brackets, then
- expanding this markup is equivalent to
- <code>empy.invokeCallback(contents)</code>. See the "Custom markup"
- section for more information.</dd>
-</dl>
-<h3>Control</h3>
-<p> EmPy version 3 and above includes the ability to direct
- conditional and repeated expansion of blocks of EmPy code with
- control markups (the obsolescent "substitution" markups are
- unavailable as of version 3.0). Control markups have analogs to
- control flow structures in Python such as <code>if/elif/else</code>, <code>for</code>, and
- <code>while</code>. Control markups are set off with the <code>@[...]</code> notation.</p>
-<p> Control markups are designed to be used in precisely the same way
- that their internal Python analogues are used, except that the
- control markups are intended to be used where there is much more
- markup than control structure.</p>
-<p> Some control markups are considered "primary," (<em>e.g.</em>, <code>if</code>,
- <code>for</code>, <code>while</code>) as they begin a control markup. Others are
- considered "secondary," since they can only appear inside control
- flow markups delineated by primary markups (<em>e.g.</em>, <code>elif</code>,
- <code>else</code>, <code>continue</code>, <code>break</code>).</p>
-<p> Since EmPy, unlike Python, cannot use indentation to determine
- where control structures begin and end, all primary control
- markups <em>must</em> be followed by a corresponding terminating control
- markup:
-<pre>
- @[PRIMARY ...]...@[end PRIMARY]
-</pre>
-</p>
-<p> (where <code>PRIMARY</code> represents one of the primary keywords). The end
- markup is mandatory, as is the space between the <code>end</code> and the
- starting keyword. For instance:
-<pre>
- @# If `person' is alive, show their age.
- @person.name is @
- @[if person.isAlive]@person.age@[else]dead@[end if].
-</pre>
-</p>
-<p> All primary markups must be terminated in this way, and the
- keyword appearing in the appropriate <code>end</code> markup must match the
- primary markup it corresponds to; if either of these conditions
- are not satisfied, the result is a parse error. Everything
- between the starting control flow marker (<code>@[PRIMARY ...]</code>) and
- the ending marker (<code>@[end PRIMARY]</code>) -- including other markups,
- even control markups -- is considered part of the markup. Control
- markups can be nested:
-<pre>
- @# Print all non-false elements on separate lines.
- @[for elem in elements]@[if elem]@elem@\n@[end if]@[end for]
-</pre>
-</p>
-<p> Three major types of primary control markups are available:
- conditional (<em>e.g.</em>, <code>if</code>, <code>try</code>), looping (<em>e.g.</em>, <code>for</code>,
- <code>while</code>), and definitional (<em>e.g.</em>, <code>def</code>, discussed below).
- Conditional control markups conditionally expand their contents,
- whereas looping control markups repeatedly expand their contents.
- The third type, definitional markups, will define new objects in
- the globals relating to their contents. Conditional and looping
- markups also differ in one substantial respect: Looping constructs
- support '@<a href="#refcontinue">[continue]</a>' and '@<a href="#refbreak">[break]</a>' markups which, like their
- Python equivalents, continue with the next iteration or break out
- of the innermost looping construct, respectively ('@<a href="#refcontinue">[continue]</a>'
- and '@<a href="#refbreak">[break]</a>' markups have no meaning inside conditional markups
- and are an error). Also like their Python equivalents,
- '@<a href="#refcontinue">[continue]</a>' and '@<a href="#refbreak">[break]</a>' may appear inside nested markups, so
- long as they ultimately are contained by at least one looping
- control markup:
-<pre>
- @# Walk a long a linked list, printing each element.
- @[while 1]@
- @node
- @{node = node.next}@
- @[if not node]@[break]@[end if]@
- @[end while]
-</pre>
-</p>
-<p> The provided markups are designed to mimic the internal Python
- control structures as closely as possible. The supported control
- markups are (the phrases in all uppercase are intended to signify
- user-selectable patterns):
-<pre>
- @[if CONDITION1]...@[elif CONDITION2]...@[else]...@[end if]
- @[try]...@[except ...]...@[except ...]...@[end try]
- @[try]...@[finally]...@[end try]
- @[for VARIABLE in SEQUENCE]...@[else]...@[end for]
- @[while CONDITION]...@[else]...@[end while]
- @[def SIGNATURE]...@[end def]
-</pre>
-</p>
-<p> All recognizable forms behave like their Python equivalents; <code>if</code>
- can contain multiple <code>elif</code> secondary markups within it; the
- <code>else</code> markups are optional (but must appear at the end), the
- <code>try</code> form with the <code>except</code> clause can contain multiple ones
- which are handled in sequence, the <code>try</code> form can either contain
- one or more <code>except</code> clauses or one <code>finally</code> clause (but not
- both), and the <code>for</code> and <code>while</code> structures can contain <code>continue</code>
- or <code>break</code> clauses internally (even if contained within other
- markups).</p>
-<p> The third type of primary control markup is "definitional," in
- that they create objects in the globals for later use (<em>e.g.</em>,
- <code>def</code>). This allows the definition of a callable object which,
- when called, will expand the contained markup (which can in turn,
- of course, contain further markups). The argument to the markup
- can be any legal Python function signature:
-<pre>
- @[def f(x, y, z=2, *args, **keywords)]...@[end def]
-</pre>
-</p>
-<p> would define a function in the globals named <code>f</code> that takes the
- given arguments. A macro markup of the form <code>@[def
- SIGNATURE]CODE@[end def]</code> is equivalent to the Python code:
-<pre>
- def SIGNATURE:
- r"""CODE""" # so it is a doc string
- empy.expand(r"""CODE""", locals())
-</pre>
-</p>
-<p> That is, it creates a Python function with the same name and
- function arguments, whose docstring is the contents of the EmPy
- markup that will be expanded when called. And, when called, it
- will expand those contents, with the locals passed in.</p>
-<h3>Unicode support</h3>
-<p> EmPy version 3.1 and above includes intrinsic Unicode support.
- EmPy's Unicode support defers to Python's internal Unicode
- support, available in Python 2.0 and up, in order to allow
- seamless and transparent translation of different encodings to the
- native Python Unicode format.</p>
-<p> Knowledge of Python's Unicode support is expected, although not
- completely required, to gain full benefit of EmPy's Unicode
- features. To enable Unicode support, start EmPy with the
- -u/--unicode option. EmPy will then transparently encode from the
- input stream, process markups internally with native Unicode, and
- then decode transparently to the output stream.</p>
-<p> By default, Python sets <code>sys.stdin</code> and <code>sys.stdout</code> with a
- default encoding which is accessible via
- 'sys.getdefaultencoding()'; encodings are represented by string
- names. These streams have encodings set by the system and
- <em>cannot</em> be changed.</p>
-<p> However, encodings for newly created files (files to be read when
- specified on the command line, and/or files to be written when
- used with the -o and -a arguments) can be specified for EmPy via
- command line options. The --unicode-encoding option
- simultaneously indicates the encoding to be used for both input
- and output, whereas the --unicode-input-encoding and
- --unicode-output-encoding options can each be used to specify
- different encodings for both input and output. (If an encoding is
- not explicitly indicated, it resorts to the system default in
- <code>sys.getdefaultencoding()</code>, which is locale dependent.)</p>
-<p> Python's Unicode implementation has the concept of error handlers,
- registered with the <code>codecs</code> module, which can be specified to
- determine what action should take place if input cannot be decoded
- into Unicode, or Unicode cannot be encoded into output. EmPy uses
- these same "errors," as they are called, and can be specified via
- command line options. The three most common error handlers are:
- <code>ignore</code>, where invalid sequences are simply ignored; <code>replace</code>,
- where invalid sequences are replaced with an encoding-specific
- indicator, usually a question mark; and <code>strict</code>, where invalid
- sequences raise an error. The --unicode-errors command line
- option specifies the same error handler to be used for both input
- and output, and the --unicode-input-errors and
- --unicode-output-errors options can specify different error
- handlers for input and output. If an error handler is not
- explicitly specified, the <code>strict</code> handler (which will raise
- errors) is used.</p>
-<p> Remember, to specify input encodings or errors that will take
- effect, one cannot take input from <code>sys.stdin</code> and must explicitly
- specify an EmPy file to process on the command line. Similarly,
- for output encodings or errors, <code>sys.stdout</code> cannot be used and an
- explicit output file must be specified with the -o or -a options.
- It is perfectly valid to enable the Unicode subsystem (-u option)
- while using <code>sys.stdin</code> and <code>sys.stdout</code>, but the encodings and
- errors of these preexisting streams cannot be changed.</p>
-<p> Combined with the --no-prefix option, which disables all markup
- processing, EmPy can act merely as an encoding translator, relying
- on Python's Unicode facilities:
-<pre>
- em.py --no-prefix \
- --unicode-input-encoding=utf-8 \
- --unicode-output-encoding=latin-1 \
- -o filename.Latin-1 filename.UTF-8
-</pre>
-</p>
-<h3>Significators</h3>
-<p> Significators, introduced in EmPy version 1.2, are intended to
- represent special assignment in a form that is easy to externally
- parse. For instance, if one has a system that contains many EmPy
- files, each of which has its own title, one could use a <code>title</code>
- significator in each file and use a simple regular expression to
- find this significator in each file and organize a database of the
- EmPy files to be built. This is an easier proposition than, for
- instance, attempting to grep for a normal Python assignment
- (inside a <code>@{...}</code> expansion) of the desired variable.</p>
-<p> Significators look like the following:
-<pre>
- @%KEY VALUE
-</pre>
-</p>
-<p> including the trailing newline, where "key" is a name and "value"
- is a Python expression, and are separated by any whitespace. This
- is equivalent to the following Python code:
-<pre>
- __KEY__ = VALUE
-</pre>
-</p>
-<p> That is to say, a significator key translates to a Python variable
- consisting of that key surrounded by double underscores on either
- side. The value may contain spaces, but the key may not. So:
-<pre>
- @%title "All Roads Lead to Rome"
-</pre>
-</p>
-<p> translates to the Python code:
-<pre>
- __title__ = "All Roads Lead to Rome"
-</pre>
-</p>
-<p> but obviously in a way that easier to detect externally than if
- this Python code were to appear somewhere in an expansion. Since
- significator keys are surrounded by double underscores,
- significator keys can be any sequence of alphanumeric and
- underscore characters; choosing <code>123</code> is perfectly valid for a
- significator (although straight), since it maps to the name
- <code>__123__</code> which is a legal Python identifier.</p>
-<p> Note the value can be any Python expression. The value can be
- omitted; if missing, it is treated as <code>None</code>.</p>
-<p> Significators are completely optional; it is completely legal for
- a EmPy file or files to be processed without containing any
- significators. Significators can appear anywhere within a file
- outside of other markups, but typically they are placed near the
- top of the file to make them easy to spot and edit by humans.</p>
-<p> A regular expression string designed to match significators (with
- the default prefix) is available as <code>empy.SIGNIFICATOR_RE_STRING</code>,
- and also is a toplevel definition in the <code>em</code> module itself.</p>
-<h3>Diversions</h3>
-<p> EmPy supports an extended form of diversions, which are a
- mechanism for deferring and recalling output on demand, similar to
- the functionality included in m4. Multiple "streams" of output
- can be diverted (deferred) and undiverted (recalled) in this
- manner. A diversion is identified with a name, which is any
- immutable object such an integer or string. When recalled,
- diverted code is <em>not</em> resent through the EmPy interpreter
- (although a filter could be set up to do this).</p>
-<p> By default, no diversions take place. When no diversion is in
- effect, processing output goes directly to the specified output
- file. This state can be explicitly requested at any time by
- calling the <code>empy.stopDiverting</code> function. It is always legal to
- call this function.</p>
-<p> When diverted, however, output goes to a deferred location which
- can then be recalled later. Output is diverted with the
- <code>empy.startDiversion</code> function, which takes an argument that is
- the name of the diversion. If there is no diversion by that name,
- a new diversion is created and output will be sent to that
- diversion; if the diversion already exists, output will be
- appended to that preexisting diversion.</p>
-<p> Output send to diversions can be recalled in two ways. The first
- is through the <code>empy.playDiversion</code> function, which takes the
- name of the diversion as an argument. This recalls the named
- diversion, sends it to the output, and then erases that
- diversion. A variant of this behavior is the
- <code>empy.replayDiversion</code>, which recalls the named diversion but does
- not eliminate it afterwards; <code>empy.replayDiversion</code> can be
- repeatedly called with the same diversion name, and will replay
- that diversion repeatedly. <code>empy.createDiversion</code> create a
- diversion without actually diverting to it, for cases where you
- want to make sure a diversion exists but do not yet want to send
- anything to it.</p>
-<p> The diversion object itself can be retrieved with
- <code>empy.retrieveDiversion</code>. Diversions act as writable
- file-objects, supporting the usual <code>write</code>, <code>writelines</code>, <code>flush</code>,
- and <code>close</code> methods. The data that has been diverted to them can
- be retrieved in one of two ways; either through the <code>asString</code>
- method, which returns the entire contents of the diversion as a
- single strong, or through the <code>asFile</code> method, which returns the
- contents of the diversion as a readable (not writable) file-like
- object.</p>
-<p> Diversions can also be explicitly deleted without recalling them
- with the <code>empy.purgeDiversion</code> function, which takes the desired
- diversion name as an argument.</p>
-<p> Additionally there are three functions which will apply the above
- operations to all existing diversions: <code>empy.playAllDiversions</code>,
- <code>empy.replayAllDiversions</code>, and <code>empy.purgeAllDiversions</code>. All
- three will do the equivalent of a <code>empy.stopDiverting</code> call before
- they do their thing.</p>
-<p> The name of the current diversion can be requested with the
- <code>empy.getCurrentDiversion</code> function; also, the names of all
- existing diversions (in sorted order) can be retrieved with
- <code>empy.getAllDiversions</code>.</p>
-<p> When all processing is finished, the equivalent of a call to
- <code>empy.playAllDiversions</code> is done.</p>
-<h3>Filters</h3>
-<p> EmPy also supports dynamic filters, introduced in version 1.3.
- Filters are put in place right "before" the final output file, and
- so are only invoked after all other processing has taken place
- (including interpreting and diverting). Filters take input, remap
- it, and then send it to the output.</p>
-<p> The current filter can be retrieved with the <code>empy.getFilter</code>
- function. The filter can be cleared (reset to no filter) with
- <code>empy.resetFilter</code> and a special "null filter" which does not send
- any output at all can be installed with <code>empy.nullFilter</code>. A
- custom filter can be set with the <code>empy.setFilter</code> function; for
- convenience, specialized shortcuts for filters preexist and can be
- used in lieu of actual <code>empy.Filter</code> instances for the
- <code>empy.setFilter</code> or <code>empy.attachFilter</code> argument:</p>
-
-<ul>
-<li><p><code>None</code> is a special filter meaning "no filter"; when installed,
- no filtering whatsoever will take place. <code>empy.setFilter(None)</code>
- is equivalent to <code>empy.resetFilter()</code>.</p></li>
-<li><p><code>0</code> (or any other numeric constant equal to zero) is another
- special filter that represents the null filter; when installed,
- no output will ever be sent to the filter's sink.</p></li>
-<li><p>A filter specified as a function (or lambda) is expected to take
- one string argument and return one string argument; this filter
- will execute the function on any input and use the return value
- as output.</p></li>
-<li><p>A filter that is a string is a 256-character table is
- substituted with the result of a call to <code>string.translate</code>
- using that table.</p></li>
-<li><p>A filter can be an instance of a subclass of <code>empy.Filter</code>.
- This is the most general form of filter. (In actuality, it can
- be any object that exhibits a <code>Filter</code> interface, which would
- include the normal file-like <code>write</code>, <code>flush</code>, and <code>close</code>
- methods, as well as <code>next</code>, <code>attach</code>, and <code>detach</code> methods for
- filter-specific behavior.)</p></li>
-<li><p>Finally, the argument to <code>empy.setFilter</code> can be a Python list
- consisting of one or more of the above objects. In that case,
- those filters are chained together in the order they appear in
- the list. An empty list is the equivalent of 'None'; all
- filters will be uninstalled.</p></li>
-
-</ul>
-<p> Filters are, at their core, simply file-like objects (minimally
- supporting <code>write</code>, <code>flush</code>, and <code>close</code> methods that behave in
- the usual way) which, after performing whatever processing they
- need to do, send their work to the next file-like object or filter
- in line, called that filter's "sink." That is to say, filters can
- be "chained" together; the action of each filter takes place in
- sequence, with the output of one filter being the input of the
- next. Additionally, filters support a <code>_flush</code> method (note the
- leading underscore) which will always flush the filter's
- underlying sink; this method should be not overridden.</p>
-<p> Filters also support three additional methods, not part of the
- traditional file interface: <code>attach</code>, which takes as an argument a
- file-like object (perhaps another filter) and sets that as the
- filter's "sink" -- that is, the next filter/file-like object in
- line. <code>detach</code> (which takes no arguments) is another method which
- flushes the filter and removes its sink, leaving it isolated.
- Finally, <code>next</code> is an accessor method which returns the filter's
- sink -- or <code>None</code>, if the filter does not yet have a sink
- attached.</p>
-<p> To create your own filter, you can create an object which supports
- the above described interface, or simply derive from the
- <code>empy.Filter</code> class and override its <code>write</code> and possibly <code>flush</code>
- methods. You can chain filters together by passing them as
- elements in a list to the <code>empy.setFilter</code> function, or you can
- chain them together manually with the <code>attach</code> method:
-<pre>
- firstFilter.attach(secondFilter)
- empy.setFilter(firstFilter)
-</pre>
-</p>
-<p> or just let EmPy do the chaining for you:
-<pre>
- empy.setFilter([firstFilter, secondFilter])
-</pre>
-</p>
-<p> In either case, EmPy will walk the filter chain and find the end
- and then hook that into the appropriate interpreter stream; you
- need not do this manually. The function <code>empy.attachFilter</code> can
- be used to attach a single filter (or shortcut, as above) to the
- end of a currently existing chain. Note that unlike its cousin
- <code>empy.setFilter</code>, one cannot pass a sequence of filters (or filter
- shortcuts) to <code>empy.attachFilter</code>. (If there is no existing
- filter chain installed, <code>empy.attachFilter</code> will behave the same
- as <code>empy.setFilter</code>.)</p>
-<p> Subclasses of <code>empy.Filter</code> are already provided with the above
- null, function, and string functionality described above; they are
- <code>NullFilter</code>, <code>FunctionFilter</code>, and <code>StringFilter</code>, respectively.
- In addition, a filter which supports buffering, <code>BufferedFilter</code>,
- is provided. Several variants are included: <code>SizeBufferedFilter</code>,
- a filter which buffers into fixed-sized chunks,
- <code>LineBufferedFilter</code>, a filter which buffers by lines, and
- <code>MaximallyBufferedFilter</code>, a filter which completely buffers its
- input.</p>
-<h3>Hooks</h3>
-<p> The EmPy system allows for the registry of hooks with a running
- EmPy interpreter. Originally introduced in version 2.0 and much
- improved in 3.2, hooks are objects, registered with an
- interpreter, whose methods represent specific callbacks. Any
- number of hook objects can be registered with an interpreter, and
- when a callback is invoked, the associated method on each one of
- those hook objects will be called by the interpreter in sequence.</p>
-<p> Hooks are simply instances, nominally derived from the <code>empy.Hook</code>
- class. The <code>empy.Hook</code> class itself defines a series of methods,
- with the expected arguments, which would be called by a running
- EmPy interpreter. This scenario, much improved from the prior
- implementation in 2.0, allows hooks to keep state and have more
- direct access to the interpreter they are running in (the
- <code>empy.Hook</code> instance contains an <code>interpreter</code> attribute).</p>
-<p> To use a hook, derive a class from <code>empy.Hook</code> and override the
- desired methods (with the same signatures as they appear in the
- base class). Create an instance of that subclass, and then
- register it with a running interpreter with the <code>empy.addHook</code>
- function. (This same hook instance can be removed with the
- <code>empy.removeHook</code> function.)</p>
-<p> More than one hook instance can be registered with an interpreter;
- in such a case, the appropriate methods are invoked on each
- instance in the order in which they were registered. To adjust
- this behavior, an optional <code>prepend</code> argument to the
- <code>empy.addHook</code> function can be used dictate that the new hook
- should placed at the <em>beginning</em> of the sequence of hooks, rather
- than at the end (which is the default).</p>
-<p> All hooks can be enabled and disabled entirely for a given
- interpreter; this is done with the <code>empy.enableHooks</code> and
- <code>empy.disableHooks</code> functions. By default hooks are enabled, but
- obviously if no hooks have been registered no hook callbacks will
- be made. Whether hooks are enabled or disabled can be determined
- by calling <code>empy.areHooksEnabled</code>. To get a (copy of) the list of
- registered hooks, call <code>empy.getHooks</code>. Finally, to invoke a hook
- manually, use <code>empy.invokeHook</code>.</p>
-<p> For a list of supported hook callbacks, see the <code>empy.Hook</code> class
- definition.</p>
-<p> As a practical example, this sample Python code would print a
- pound sign followed by the name of every file that is included
- with 'empy.include':
-<pre>
- class IncludeHook(empy.Hook):
- def beforeInclude(self, name, file, locals):
- print "# %s" % name
-
- empy.addHook(IncludeHook())
-</pre>
-</p>
-<h3>Custom markup</h3>
-<p> Since version 3.2.1, the markup '@<...>' is reserved for
- user-defined use. Unlike the other markups, this markup has no
- specified meaning on its own, and can be provided a meaning by the
- user. This meaning is provided with the use of a "custom
- callback," or just "callback," which can be set, queried, or reset
- using the pseudomodule function.</p>
-<p> The custom callback is a callable object which, when invoked, is
- passed a single argument: a string representing the contents of
- what was found inside the custom markup '@<...>'.</p>
-<p> To register a callback, call <code>empy.registerCallback</code>. To remove
- one, call <code>empy.deregisterCallback</code>. To retrieve the callback (if
- any) registered with the interpreter, use <code>empy.getCallback</code>.
- Finally, to invoke the callback just as if the custom markup were
- encountered, call <code>empy.invokeCallback</code>. For instance, '@<This
- text>' would be equivalent to the call <code>@empy.invokeCallback("This
- text")</code>.</p>
-<p> By default, to invoke a callback (either explicitly with
- <code>empy.invokeCallback</code> or by processing a '@<...>' custom markup)
- when no callback has been registered is an error. This behavior
- can be changed with the <code>CALLBACK_OPT</code> option, or the
- --no-callback-error command line option.</p>
-<h3>Pseudomodule</h3>
-<p> The <code>empy</code> pseudomodule is available only in an operating EmPy
- system. (The name of the module, by default <code>empy</code>, can be
- changed with the -m option or the <code>EMPY_PSEUDO</code> environment
- variable). It is called a pseudomodule because it is not actually
- a module, but rather exports a module-like interface. In fact,
- the pseudmodule is actually the same internal object as the
- interpreter itself.</p>
-<p> The pseudomodule contains the following functions and objects (and
- their signatures, with a suffixed <code>opt</code> indicating an optional
- argument):</p>
-<p> First, basic identification:</p>
-<dl>
-<dt> <strong><code>VERSION</code></strong></dt>
-<dd>A constant variable which contains a
- string representation of the EmPy version.</dd>
-<dt> <strong><code>SIGNIFICATOR_RE_STRING</code></strong></dt>
-<dd>A constant variable representing a
- regular expression string (using the default prefix) that can be
- used to find significators in EmPy code.</dd>
-<dt> <strong><code>SIGNIFICATOR_RE_SUFFIX</code></strong></dt>
-<dd>The portion of the significator
- regular expression string excluding the prefix, so that those
- using non-standard prefix can build their own custom regular
- expression string with <code>myPrefix + empy.SIGNIFICATOR_RE_SUFFIX</code>.</dd>
-<dt> <strong><code>interpreter</code></strong></dt>
-<dd>The instance of the interpreter that is
- currently being used to perform execution. <em>Note:</em> This is now
- obsolete; the pseudomodule is itself the interpreter. Instead
- of using <code>empy.interpreter</code>, simply use <code>empy</code>.</dd>
-<dt> <strong><code>argv</code></strong></dt>
-<dd>A list consisting of the name of the primary EmPy
- script and its command line arguments, in analogue to the
- <code>sys.argv</code> list.</dd>
-<dt> <strong><code>args</code></strong></dt>
-<dd>A list of the command line arguments following the
- primary EmPy script; this is equivalent to <code>empy.argv[1:]</code>.</dd>
-<dt> <strong><code>identify() -> string, integer</code></strong></dt>
-<dd>Retrieve identification
- information about the current parsing context. Returns a
- 2-tuple consisting of a filename and a line number; if the file
- is something other than from a physical file (<em>e.g.</em>, an
- explicit expansion with <code>empy.expand</code>, a file-like object within
- Python, or via the -E or -F command line options), a string
- representation is presented surrounded by angle brackets. Note
- that the context only applies to the <em>EmPy</em> context, not the
- Python context.</dd>
-<dt> <strong><code>atExit(callable)</code></strong></dt>
-<dd>Register a callable object (such as a
- function) taking no arguments which will be called at the end of
- a normal shutdown. Callable objects registered in this way are
- called in the reverse order in which they are added, so the
- first callable registered with <code>empy.atExit</code> is the last one to
- be called. Note that although the functionality is related to
- hooks, <code>empy.atExit</code> does no work via the hook mechanism, and
- you are guaranteed that the interpreter and stdout will be in a
- consistent state when the callable is invoked.</dd>
-</dl>
-<p> Context manipulation:</p>
-<dl>
-<dt> <strong><code>pushContext(name_opt, line_opt)</code></strong></dt>
-<dd>Create a new context with
- the given name and line and push it on the stack.</dd>
-<dt> <strong><code>popContext()</code></strong></dt>
-<dd>Pop the top context and dispose of it.</dd>
-<dt> <strong><code>setContextName(name)</code></strong></dt>
-<dd>Manually set the name of the current
- context.</dd>
-<dt> <strong><code>setContextLine(line)</code></strong></dt>
-<dd>Manually set the line number of the
- current context; line must be a numeric value. Note that
- afterward the line number will increment by one for each newline
- that is encountered, as before.</dd>
-</dl>
-<p> Globals manipulation:</p>
-<dl>
-<dt> <strong><code>getGlobals()</code></strong></dt>
-<dd>Retrieve the globals dictionary for this
- interpreter. Unlike when calling <code>globals()</code> in Python, this
- dictionary <em>can</em> be manipulated and you <em>can</em> expect changes you
- make to it to be reflected in the interpreter that holds it.</dd>
-<dt> <strong><code>setGlobals(globals)</code></strong></dt>
-<dd>Reseat the globals dictionary
- associated with this interpreter to the provided mapping type.</dd>
-<dt> <strong><code>updateGlobals(globals)</code></strong></dt>
-<dd>Merge the given dictionary into
- this interpreter's globals.</dd>
-<dt> <strong><code>clearGlobals(globals_opt)</code></strong></dt>
-<dd>Clear out the globals
- (restoring, of course, the <code>empy</code> pseudomodule). Optionally,
- instead of starting with a refresh dictionary, use the
- dictionary provided.</dd>
-<dt> <strong><code>saveGlobals(deep=True)</code></strong></dt>
-<dd>Save a copy of the globals onto an
- internal history stack from which it can be restored later. The
- optional <code>deep</code> argument indicates whether or not the copying
- should be a deep copy (default) or a shallow one. Copying is
- done with <code>copy.deepcopy</code> or <code>copy.copy</code>, respectively.</dd>
-<dt> <strong><code>restoreGlobals(destructive=True)</code></strong></dt>
-<dd>Restore the most
- recently saved globals from the history stack to as the current
- globals for this instance. The optional <code>destructive</code> argument
- indicates whether or not the restore should remove the restored
- globals from the history stack (default), or whether it should
- be left there for subsequent restores.</dd>
-</dl>
-<p> Types:</p>
-<dl>
-<dt> <strong><code>Interpreter</code></strong></dt>
-<dd>The actual interpreter class.</dd>
-</dl>
-<p> The following functions allow direct execution; optional <code>locals</code>
- arguments, if specified, are treated as the locals dictionary in
- evaluation and execution:</p>
-<dl>
-<dt> <strong><code>defined(name, locals_opt)</code></strong></dt>
-<dd>Return true if the given name
- is defined either in the (optional) locals or the interpreter
- globals; return false otherwise.</dd>
-<dt> <strong><code>evaluate(expression, locals_opt)</code></strong></dt>
-<dd>Evaluate the given
- expression.</dd>
-<dt> <strong><code>serialize(expression, locals_opt)</code></strong></dt>
-<dd>Serialize the
- expression, just as the interpreter would: If it is not None,
- convert it to a string with the <code>str</code> builtin function, and then
- write out the result. If it evaluates to None, do nothing.</dd>
-<dt> <strong><code>execute(statements, locals_opt)</code></strong></dt>
-<dd>Execute the given
- statement(s).</dd>
-<dt> <strong><code>single(source, locals_opt)</code></strong></dt>
-<dd>Interpret the "single" source
- code, just as the Python interactive interpreter would.</dd>
-<dt> <strong><code>import_(name, locals_opt)</code></strong></dt>
-<dd>Import a module.</dd>
-<dt> <strong><code>atomic(name, value, locals_opt)</code></strong></dt>
-<dd>Perform a single, atomic
- assignment. In this case name is the string denoating the name
- of the (single) variable to be assigned to, and value is a
- Python object which the name is to be bound to.</dd>
-<dt> <strong><code>assign(name, value, locals_opt)</code></strong></dt>
-<dd>Perform general
- assignment. This decays to atomic assignment (above) in the
- normal case, but supports "tuple unpacking" in the sense that if
- name string contains commas, it is treated as a sequence of
- names and memberwise assignment with each member of the value
- (still a Python object, but which must be a sequence). This
- function will raise a <code>TypeError</code> or <code>ValueError</code> just like
- Python would if tuple unpacking is not possible (that is, if the
- value is not a sequence or is of an incompatible length,
- respectively). This only supports the assignment of Python
- identifiers, not arbitrary Python lvalues.</dd>
-<dt> <strong><code>significate(key, value_opt, locals_opt)</code></strong></dt>
-<dd>Do a manual
- signification. If <code>value</code> is not specified, it is treated as
- <code>None</code>.</dd>
-</dl>
-<p> The following functions relate to source manipulation:</p>
-<dl>
-<dt> <strong><code>include(file_or_filename, locals_opt)</code></strong></dt>
-<dd>Include another
- EmPy file, by processing it in place. The argument can either
- be a filename (which is then opened with <code>open</code> in text mode) or
- a file object, which is used as is. Once the included file is
- processed, processing of the current file continues. Includes
- can be nested. The call also takes an optional locals
- dictionary which will be passed into the evaluation function.</dd>
-<dt> <strong><code>expand(string, locals_opt)</code> -> string</strong></dt>
-<dd>Explicitly invoke
- the EmPy parsing system to process the given string and return
- its expansion. This allows multiple levels of expansion,
- <em>e.g.</em>, <code>@(empy.expand("@(2 + 2)"))</code>. The call also takes an
- optional locals dictionary which will be passed into the
- evaluation function. This is necessary when text is being
- expanded inside a function definition and it is desired that the
- function arguments (or just plain local variables) are available
- to be referenced within the expansion.</dd>
-<dt> <strong><code>quote(string) -> string</code></strong></dt>
-<dd>The inverse process of
- <code>empy.expand</code>, this will take a string and return a new string
- that, when expanded, would expand to the original string. In
- practice, this means that appearances of the prefix character
- are doubled, except when they appear inside a string literal.</dd>
-<dt> <strong><code>escape(string, more_opt) -> string</code></strong></dt>
-<dd>Given a string, quote
- the nonprintable characters contained within it with EmPy
- escapes. The optional <code>more</code> argument specifies additional
- characters that should be escaped.</dd>
-<dt> <strong><code>flush()</code></strong></dt>
-<dd>Do an explicit flush on the underlying stream.</dd>
-<dt> <strong><code>string(string, name_opt, locals_opt)</code></strong></dt>
-<dd>Explicitly process a
- string-like object. This differs from <code>empy.expand</code> in that the
- string is directly processed into the EmPy system, rather than
- being evaluated in an isolated context and then returned as a
- string.</dd>
-</dl>
-<p> Changing the behavior of the pseudomodule itself:</p>
-<dl>
-<dt> <strong><code>flatten(keys_opt)</code></strong></dt>
-<dd>Perform the equivalent of <code>from empy
- import ...</code> in code (which is not directly possible because
- <code>empy</code> is a pseudomodule). If keys is omitted, it is taken as
- being everything in the <code>empy</code> pseudomodule. Each of the
- elements of this pseudomodule is flattened into the globals
- namespace; after a call to <code>empy.flatten</code>, they can be referred
- to simple as globals, <em>e.g.</em>, <code>@divert(3)</code> instead of
- <code>@empy.divert(3)</code>. If any preexisting variables are bound to
- these names, they are silently overridden. Doing this is
- tantamount to declaring an <code>from ... import ...</code> which is often
- considered bad form in Python.</dd>
-</dl>
-<p> Prefix-related functions:</p>
-<dl>
-<dt> <strong><code>getPrefix() -> char</code></strong></dt>
-<dd>Return the current prefix.</dd>
-<dt> <strong><code>setPrefix(char)</code></strong></dt>
-<dd>Set a new prefix. Immediately after this
- call finishes, the prefix will be changed. Changing the prefix
- affects only the current interpreter; any other created
- interpreters are unaffected. Setting the prefix to None or the
- null string means that no further markups will be processed,
- equivalent to specifying the --no-prefix command line argument.</dd>
-</dl>
-<p> Diversions:</p>
-<dl>
-<dt> <strong><code>stopDiverting()</code></strong></dt>
-<dd>Any diversions that are currently taking
- place are stopped; thereafter, output will go directly to the
- output file as normal. It is never illegal to call this
- function.</dd>
-<dt> <strong><code>createDiversion(name)</code></strong></dt>
-<dd>Create a diversion, but do not
- begin diverting to it. This is the equivalent of starting a
- diversion and then immediately stopping diversion; it is used in
- cases where you want to make sure that a diversion will exist
- for future replaying but may be empty.</dd>
-<dt> <strong><code>startDiversion(name)</code></strong></dt>
-<dd>Start diverting to the specified
- diversion name. If such a diversion does not already exist, it
- is created; if it does, then additional material will be
- appended to the preexisting diversions.</dd>
-<dt> <strong><code>playDiversion(name)</code></strong></dt>
-<dd>Recall the specified diversion and
- then purge it. The provided diversion name must exist.</dd>
-<dt> <strong><code>replayDiversion(name)</code></strong></dt>
-<dd>Recall the specified diversion
- without purging it. The provided diversion name must exist.</dd>
-<dt> <strong><code>purgeDiversion(name)</code></strong></dt>
-<dd>Purge the specified diversion
- without recalling it. The provided diversion name must exist.</dd>
-<dt> <strong><code>playAllDiversions()</code></strong></dt>
-<dd>Play (and purge) all existing
- diversions in the sorted order of their names. This call does
- an implicit <code>empy.stopDiverting</code> before executing.</dd>
-<dt> <strong><code>replayAllDiversions()</code></strong></dt>
-<dd>Replay (without purging) all
- existing diversions in the sorted order of their names. This
- call does an implicit <code>empy.stopDiverting</code> before executing.</dd>
-<dt> <strong><code>purgeAllDiversions()</code></strong></dt>
-<dd>Purge all existing diversions
- without recalling them. This call does an implicit
- <code>empy.stopDiverting</code> before executing.</dd>
-<dt> <strong><code>getCurrentDiversion() -> diversion</code></strong></dt>
-<dd>Return the name of the
- current diversion.</dd>
-<dt> <strong><code>getAllDiversions() -> sequence</code></strong></dt>
-<dd>Return a sorted list of
- all existing diversions.</dd>
-</dl>
-<p> Filters:</p>
-<dl>
-<dt> <strong><code>getFilter() -> filter</code></strong></dt>
-<dd>Retrieve the current filter.
- <code>None</code> indicates no filter is installed.</dd>
-<dt> <strong><code>resetFilter()</code></strong></dt>
-<dd>Reset the filter so that no filtering is
- done.</dd>
-<dt> <strong><code>nullFilter()</code></strong></dt>
-<dd>Install a special null filter, one which
- consumes all text and never sends any text to the output.</dd>
-<dt> <strong><code>setFilter(shortcut)</code></strong></dt>
-<dd>Install a new filter. A filter is
- <code>None</code> or an empty sequence representing no filter, or <code>0</code> for a
- null filter, a function for a function filter, a string for a
- string filter, or an instance of <code>empy.Filter</code> (or a workalike
- object). If filter is a list of the above things, they will be
- chained together manually; if it is only one, it will be
- presumed to be solitary or to have already been manually chained
- together. See the "Filters" section for more information.</dd>
-<dt> <strong><code>attachFilter(shortcut)</code></strong></dt>
-<dd>Attach a single filter (sequences
- are not allowed here) to the end of a currently existing filter
- chain, or if there is no current chain, install it as
- <code>empy.setFilter</code> would. As with <code>empy.setFilter</code>, the shortcut
- versions of filters are also allowed here.</dd>
-</dl>
-<p> Hooks:</p>
-<dl>
-<dt> <strong><code>areHooksEnabled()</code></strong></dt>
-<dd>Return whether or not hooks are
- presently enabled.</dd>
-<dt> <strong><code>enableHooks()</code></strong></dt>
-<dd>Enable invocation of hooks. By default
- hooks are enabled.</dd>
-<dt> <strong><code>disableHooks()</code></strong></dt>
-<dd>Disable invocation of hooks. Hooks can
- still be added, removed, and queried, but invocation of hooks
- will not occur (even explicit invocation with
- <code>empy.invokeHook</code>).</dd>
-<dt> <strong><code>getHooks()</code></strong></dt>
-<dd>Get a (copy of the) list of the hooks
- currently registered.</dd>
-<dt> <strong><code>clearHooks()</code></strong></dt>
-<dd>Clear all the hooks registered with this
- interpreter.</dd>
-<dt> <strong><code>addHook(hook, prepend_opt)</code></strong></dt>
-<dd>Add this hook to the hooks
- associated with this interpreter. By default, the hook is
- appended to the end of the existing hooks, if any; if the
- optional insert argument is present and true, it will be
- prepended to the list instead.</dd>
-<dt> <strong><code>removeHook(hook)</code></strong></dt>
-<dd>Remove this hook from the hooks
- associated with this interpreter.</dd>
-<dt> <strong><code>invokeHook(_name, ...)</code></strong></dt>
-<dd>Manually invoke a hook method.
- The remaining arguments are treated as keyword arguments and the
- resulting dictionary is passed in as the second argument to the
- hooks.</dd>
-</dl>
-<p> Custom markup callback:</p>
-<dl>
-<dt> <strong><code>getCallback() -> callback</code></strong></dt>
-<dd>Retrieve the current callback
- associated with this interpreter, or <code>None</code> if it does not yet
- have one.</dd>
-<dt> <strong><code>registerCallback(callback)</code></strong></dt>
-<dd>Register a callback to be
- called whenever a custom markup ('@<...>') is encountered. When
- encountered, <code>invokeCallback</code> is called.</dd>
-<dt> <strong><code>deregisterCallback()</code></strong></dt>
-<dd>Clear any callback previously
- registered with the interpreter for being called when a custom
- markup is encountered.</dd>
-<dt> <strong><code>invokeCallback(contents)</code></strong></dt>
-<dd>Invoke a custom callback. This
- function is called whenever a custom markup ('@<...>') is
- encountered. It in turn calls the registered callback, with a
- single argument, <code>contents</code>, which is a string representing of
- the contents of the custom markup.</dd>
-</dl>
-<h3>Invocation</h3>
-<p> Basic invocation involves running the interpreter on an EmPy file
- and some optional arguments. If no file are specified, or the
- file is named <code>-</code>, EmPy takes its input from stdin. One can
- suppress option evaluation (to, say, specify a file that begins
- with a dash) by using the canonical <code>--</code> option.</p>
-<dl>
-<dt> <strong><code>-h</code>/<code>--help</code></strong></dt>
-<dd>Print usage and exit.</dd>
-<dt> <strong><code>-H</code>/<code>--extended-help</code></strong></dt>
-<dd>Print extended usage and exit.
- Extended usage includes a rundown of all the legal expansions,
- escape sequences, pseudomodule contents, used hooks, and
- supported environment variables.</dd>
-<dt> <strong><code>-v</code>/<code>--verbose</code></strong></dt>
-<dd>The EmPy system will print all manner of
- details about what it is doing and what it is processing to
- stderr.</dd>
-<dt> <strong><code>-V</code>/<code>--version</code></strong></dt>
-<dd>Print version and exit.</dd>
-<dt> <strong><code>-a</code>/<code>--append</code> (filename)</strong></dt>
-<dd>Open the specified file for
- append instead of using stdout.</dd>
-<dt> <strong><code>-b</code>/<code>--buffered-output</code></strong></dt>
-<dd>Fully buffer processing output,
- including the file open itself. This is helpful when, should an
- error occur, you wish that no output file be generated at all
- (for instance, when using EmPy in conjunction with make). When
- specified, either the -o or -a options must be specified, and
- the -b option must precede them. This can also be specified
- through the existence of the <code>EMPY_BUFFERED_OUTPUT</code> environment
- variable.</dd>
-<dt> <strong><code>-f</code>/<code>--flatten</code></strong></dt>
-<dd>Before processing, move the contents of
- the <code>empy</code> pseudomodule into the globals, just as if
- <code>empy.flatten()</code> were executed immediately after starting the
- interpreter. That is, <em>e.g.</em>, <code>empy.include</code> can be referred to
- simply as <code>include</code> when this flag is specified on the command
- line. This can also be specified through the existence of the
- <code>EMPY_FLATTEN</code> environment variable.</dd>
-<dt> <strong><code>-i</code>/<code>--interactive</code></strong></dt>
-<dd>After the main EmPy file has been
- processed, the state of the interpreter is left intact and
- further processing is done from stdin. This is analogous to the
- Python interpreter's -i option, which allows interactive
- inspection of the state of the system after a main module is
- executed. This behaves as expected when the main file is stdin
- itself. This can also be specified through the existence of the
- <code>EMPY_INTERACTIVE</code> environment variable.</dd>
-<dt> <strong><code>-k</code>/<code>--suppress-errors</code></strong></dt>
-<dd>Normally when an error is
- encountered, information about its location is printed and the
- EmPy interpreter exits. With this option, when an error is
- encountered (except for keyboard interrupts), processing stops
- and the interpreter enters interactive mode, so the state of
- affairs can be assessed. This is also helpful, for instance,
- when experimenting with EmPy in an interactive manner. -k
- implies -i.</dd>
-<dt> <strong><code>-n</code>/<code>--no-override-stdout</code></strong></dt>
-<dd>Do not override <code>sys.stdout</code>
- with a proxy object which the EmPy system interacts with. If
- suppressed, this means that side effect printing will not be
- captured and routed through the EmPy system. However, if this
- option is specified, EmPy can support multithreading.</dd>
-<dt> <strong><code>-o</code>/<code>--output</code> (filename)</strong></dt>
-<dd>Open the specified file for
- output instead of using stdout. If a file with that name
- already exists it is overwritten.</dd>
-<dt> <strong><code>-p</code>/<code>--prefix</code> (prefix)</strong></dt>
-<dd>Change the prefix used to detect
- expansions. The argument is the one-character string that will
- be used as the prefix. Note that whatever it is changed to, the
- way to represent the prefix literally is to double it, so if <code>$</code>
- is the prefix, a literal dollar sign is represented with <code>$$</code>.
- Note that if the prefix is changed to one of the secondary
- characters (those that immediately follow the prefix to indicate
- the type of action EmPy should take), it will not be possible to
- represent literal prefix characters by doubling them (<em>e.g.</em>, if
- the prefix were inadvisedly changed to <code>#</code> then <code>##</code> would
- already have to represent a comment, so <code>##</code> could not represent
- a literal <code>#</code>). This can also be specified through the
- <code>EMPY_PREFIX</code> environment variable.</dd>
-<dt> <strong><code>-r</code>/<code>--raw-errors</code></strong></dt>
-<dd>Normally, EmPy catches Python
- exceptions and prints them alongside an error notation
- indicating the EmPy context in which it occurred. This option
- causes EmPy to display the full Python traceback; this is
- sometimes helpful for debugging. This can also be specified
- through the existence of the <code>EMPY_RAW_ERRORS</code> environment
- variable.</dd>
-<dt> <strong><code>-u</code>/<code>--unicode</code></strong></dt>
-<dd>Enable the Unicode subsystem. This option
- only need be present if you wish to enable the Unicode subsystem
- with the defaults; any other Unicode-related option (starting
- with --unicode...) will also enable the Unicode subsystem.</dd>
-<dt> <strong><code>-D</code>/<code>--define</code> (assignment)</strong></dt>
-<dd>Execute a Python assignment of
- the form <code>variable = expression</code>. If only a variable name is
- provided (<em>i.e.</em>, the statement does not contain an <code>=</code> sign),
- then it is taken as being assigned to None. The -D option is
- simply a specialized -E option that special cases the lack of an
- assignment operator. Multiple -D options can be specified.</dd>
-<dt> <strong><code>-E</code>/<code>--execute</code> (statement)</strong></dt>
-<dd>Execute the Python (not EmPy)
- statement before processing any files. Multiple -E options can
- be specified.</dd>
-<dt> <strong><code>-F</code>/<code>--execute-file</code> (filename)</strong></dt>
-<dd>Execute the Python (not
- EmPy) file before processing any files. This is equivalent to
- <code>-E execfile("filename")</code> but provides a more readable context.
- Multiple -F options can be specified.</dd>
-<dt> <strong><code>-I</code>/<code>--import</code> (module)</strong></dt>
-<dd>Imports the specified module name
- before processing any files. Multiple modules can be specified
- by separating them by commas, or by specifying multiple -I
- options.</dd>
-<dt> <strong><code>-P</code>/<code>--preprocess</code> (filename)</strong></dt>
-<dd>Process the EmPy file before
- processing the primary EmPy file on the command line.</dd>
-<dt> <strong><code>--binary</code></strong></dt>
-<dd>Treat the file as a binary file, and read in
- chunks rather than line by line. In this mode, the "line"
- indicator represents the number of bytes read, not the number of
- lines processed.</dd>
-<dt> <strong><code>--no-prefix</code></strong></dt>
-<dd>Disable the prefixing system entirely; when
- specified, EmPy will not expand any markups. This allows EmPy
- to merely act as a Unicode encoding translator..</dd>
-<dt> <strong><code>--pause-at-end</code></strong></dt>
-<dd>If present, then <code>raw_input</code> will be
- called at the end of processing. Useful in systems where the
- output window would otherwise be closed by the operating
- system/window manager immediately after EmPy exited.</dd>
-<dt> <strong><code>--relative-path</code></strong></dt>
-<dd>When present, the path the EmPy script
- being invoked is contained in will be prepended to <code>sys.path</code>.
- This is analogous to Python's internal handling of <code>sys.path</code>
- and scripts. If input is from stdin (<code>-</code> for a filename or no
- filename is specified), then nothing is added to the path.</dd>
-<dt> <strong><code>--no-callback-error</code></strong></dt>
-<dd>Do not consider it an error if the
- custom markup is invoked '@<...>' and there is no callback
- function registered for it.</dd>
-<dt> <strong><code>--chunk-size</code> (chunk)</strong></dt>
-<dd>Use the specific binary chunk size
- rather than the default; implies --binary.</dd>
-<dt> <strong><code>--unicode-encoding</code> (encoding)</strong></dt>
-<dd>Specify the Unicode
- encoding to be used for both input and output.</dd>
-<dt> <strong><code>--unicode-input-encoding</code> (encoding)</strong></dt>
-<dd>Specify the Unicode
- encoding to be used for input.</dd>
-<dt> <strong><code>--unicode-output-encoding</code> (encoding)</strong></dt>
-<dd>Specify the Unicode
- encoding to be used for output.</dd>
-<dt> <strong>'--unicode-input-errors (errors)</strong></dt>
-<dd>Specify the Unicode error
- handling to be used for input.</dd>
-<dt> <strong>'--unicode-errors (errors)</strong></dt>
-<dd>Specify the Unicode error
- handling to be used for both input and output.</dd>
-<dt> <strong>'--unicode-output-errors (errors)</strong></dt>
-<dd>Specify the Unicode error
- handling to be used for output.</dd>
-</dl>
-<h3>Environment variables</h3>
-<p> EmPy also supports a few environment variables to predefine
- certain behaviors. The settings chosen by environment variables
- can be overridden via command line arguments. The following
- environment variables have meaning to EmPy:</p>
-<dl>
-<dt> <strong><code>EMPY_OPTIONS</code></strong></dt>
-<dd>If present, the contents of this environment
- variable will be treated as options, just as if they were
- entered on the command line, <em>before</em> the actual command line
- arguments are processed. Note that these arguments are <em>not</em>
- processed by the shell, so quoting, filename globbing, and the
- like, will not work.</dd>
-<dt> <strong><code>EMPY_PREFIX</code></strong></dt>
-<dd>If present, the value of this environment
- variable represents the prefix that will be used; this is
- equivalent to the -p command line option.</dd>
-<dt> <strong><code>EMPY_PSEUDO</code></strong></dt>
-<dd>If present, the value of this environment
- variable represents the name of the pseudomodule that will be
- incorporated into every running EmPy system; this is equivalent
- to the -m command line option.</dd>
-<dt> <strong><code>EMPY_FLATTEN</code></strong></dt>
-<dd>If defined, this is equivalent to including
- -f on the command line.</dd>
-<dt> <strong><code>EMPY_RAW_ERRORS</code></strong></dt>
-<dd>If defined, this is equivalent to
- including -r on the command line.</dd>
-<dt> <strong><code>EMPY_INTERACTIVE</code></strong></dt>
-<dd>If defined, this is equivalent to
- including -i on the command line.</dd>
-<dt> <strong><code>EMPY_BUFFERED_OUTPUT</code></strong></dt>
-<dd>If defined, this is equivalent to
- including -b on the command line.</dd>
-<dt> <strong><code>EMPY_UNICODE</code></strong></dt>
-<dd>If defined, this is equivalent to including
- -u on the command line.</dd>
-<dt> <strong><code>EMPY_UNICODE_INPUT_ENCODING</code></strong></dt>
-<dd>If present, the value of this
- environment variable indicates the name of the Unicode input
- encoding to be used. This is equivalent to the
- --unicode-input-encoding command line option.</dd>
-<dt> <strong><code>EMPY_UNICODE_OUTPUT_ENCODING</code></strong></dt>
-<dd>If present, the value of
- this environment variable indicates the name of the Unicode
- output encoding to be used. This is equivalent to the
- --unicode-output-encoding command line option.</dd>
-<dt> <strong><code>EMPY_UNICODE_INPUT_ERRORS</code></strong></dt>
-<dd>If present, the value of this
- environment variable indicates the name of the error handler to
- be used for input. This is equivalent to the
- --unicode-input-errors command line option.</dd>
-<dt> <strong><code>EMPY_UNICODE_OUTPUT_ERRORS</code></strong></dt>
-<dd>If present, the value of this
- environment variable indicates the name of the error handler to
- be used for output. This is equivalent to the
- --unicode-output-errors command line option.</dd>
-</dl>
-<h3>Examples and testing EmPy</h3>
-<p> See the sample EmPy file <code>sample.em</code> which is included with the
- distribution. Run EmPy on it by typing something like:
-<pre>
- ./em.py sample.em
-</pre>
-</p>
-<p> and compare the results and the sample source file side by side.
- The sample content is intended to be self-documenting, and even an
- introduction to the basic features of EmPy while simultaneously
- exercising them.</p>
-<p> The file <code>sample.bench</code> is the benchmark output of the sample.
- Running the EmPy interpreter on the provided <code>sample.em</code> file
- should produce precisely the same results. You can run the
- provided test script to see if your EmPy environment is behaving
- as expected (presuming a Unix-like operating system):
-<pre>
- ./test.sh
-</pre>
-</p>
-<p> By default this will test with the first Python interpreter
- available in the path; if you want to test with another
- interpreter, you can provide it as the first argument on the
- command line, <em>e.g.</em>:
-<pre>
- ./test.sh python2.1
- ./test.sh /usr/bin/python1.5
- ./test.sh jython
-</pre>
-</p>
-<p> A more comprehensive test suite and set of real-world examples is
- planned for a future version.</p>
-<h3>Embedding EmPy</h3>
-<p> For atomic applications, the <code>expand</code> function is provided (the
- extra keyword arguments passed in are treated as locals):
-<pre>
- import em
- print em.expand("@x + @y is @(x + y).", x=2, y=3)
-</pre>
-</p>
-<p> One can specify a globals dictionary and all the other interpreter
- options (below) as well. One can specify a globals dictionary
- that will be used if one wants persistence:
-<pre>
- import em
- g = {}
- em.expand("@{x = 10}", g)
- print em.expand("x is @x.", g)
-</pre>
-</p>
-<p> The standalone <code>expand</code> function, however, creates and destroys an
- <code>Interpreter</code> instance each time it is called. For repeated
- expansions, this can be expensive. Instead, you will probably
- want to use the full-fledged features of embedding. An EmPy
- interpreter can be created with as code as simple as:
-<pre>
- import em
- interpreter = em.Interpreter()
- # The following prints the results to stdout:
- interpreter.string("@{x = 123}@x\n")
- # This expands to the same thing, but puts the results as a
- # string in the variable result:
- result = interpreter.expand("@{x = 123}@x\n")
- # This just prints the value of x directly:
- print interpreter.globals['x']
- # Process an actual file (and output to stdout):
- interpreter.file(open('/path/to/some/file'))
- interpreter.shutdown() # this is important; see below
-</pre>
-</p>
-<p> One can capture the output of a run in something other than stdout
- by specifying the <em>output</em> parameter:
-<pre>
- import em, StringIO
- output = StringIO.StringIO()
- interpreter = em.Interpreter(output=output)
- # Do something.
- interpreter.file(open('/path/to/some/file'))
- interpreter.shutdown() # again, this is important; see below
- print output.getvalue() # this is the result from the session
-</pre>
-</p>
-<p> When you are finished with your interpreter, it is important to
- call its shutdown method:
-<pre>
- interpreter.shutdown()
-</pre>
-</p>
-<p> This will ensure that the interpreter cleans up all its overhead,
- entries in the <code>sys.stdout</code> proxy, and so forth. It is usually
- advisable that this be used in a try...finally clause:
-<pre>
- interpreter = em.Interpreter(...)
- try:
- ...
- finally:
- interpreter.shutdown()
-</pre>
-</p>
-<p> The <code>em.Interpreter</code> constructor takes the following arguments;
- all are optional. Since options may be added in the future, it is
- highly recommended that the constructor be invoked via keyword
- arguments, rather than assuming their order. The arguments are:</p>
-<dl>
-<dt> <em>output</em></dt>
-<dd>The output file which the interpreter will be sending
- all its processed data to. This need only be a file-like object;
- it need not be an actual file. If omitted, <code>sys.__stdout__</code> is
- used.</dd>
-<dt> <em>argv</em></dt>
-<dd>An argument list analogous to <code>sys.argv</code>, consisting of
- the script name and zero or more arguments. These are available
- to executing interpreters via <code>empy.argv</code> and <code>empy.args</code>. If
- omitted, a non-descript script name is used with no arguments.</dd>
-<dt> <em>prefix</em></dt>
-<dd>The prefix (a single-character string). Defaults to
- <code>@</code>. It is an error for this to be anything other than one
- character.</dd>
-<dt> <em>pseudo</em></dt>
-<dd>The name (string) of the pseudmodule. Defaults to
- <code>empy</code>.</dd>
-<dt> <em>options</em></dt>
-<dd>A dictionary of options that can override the default
- behavior of the interpreter. The names of the options are
- constant names ending in <code>_OPT</code> and their defaults are given in
- <code>Interpreter.DEFAULT_OPTIONS</code>.</dd>
-<dt> <em>globals</em></dt>
-<dd>By default, interpreters begin with a pristine
- dictionary of globals (except, of course, for the <code>empy</code>
- pseudomodule). Specifying this argument will allow the globals
- to start with more.</dd>
-<dt> <em>hooks</em></dt>
-<dd>A sequence of hooks (or <code>None</code> for none) to register
- with the interpreter at startup. Hooks can, of course, be added
- after the fact, but this allows the hooks to intercept the
- <code>atStartup</code> event (otherwise, the startup event would already
- have occurred by the time new hooks could be registered)..</dd>
-</dl>
-<p> Many things can be done with EmPy interpreters; for the full
- developer documentation, see the generated documentation for the
- <code>em</code> module.</p>
-<h3>Interpreter options</h3>
-<p> The following options (passed in as part of the options dictionary
- to the Interpreter constructor) have the following meanings. The
- defaults are shown below and are also indicated in an
- <code>Interpreter.DEFAULT_OPTIONS</code> dictionary.</p>
-<dl>
-<dt> <strong><code>BANGPATH_OPT</code></strong></dt>
-<dd>Should a bangpath (<code>#!</code>) as the first line
- of an EmPy file be treated as if it were an EmPy comment? Note
- that <code>#!</code> sequences starting lines or appearing anywhere else in
- the file are untouched regardless of the value of this option.
- Default: true.</dd>
-<dt> <strong><code>BUFFERED_OPT</code></strong></dt>
-<dd>Should an <code>abort</code> method be called upon
- failure? This relates to the fully-buffered option, where all
- output can be buffered including the file open; this option only
- relates to the interpreter's behavior <em>after</em> that proxy file
- object has been created. Default: false.</dd>
-<dt> <strong><code>RAW_OPT</code></strong></dt>
-<dd>Should errors be displayed as raw Python errors
- (that is, the exception is allowed to propagate through to the
- toplevel so that the user gets a standard Python traceback)?
- Default: false.</dd>
-<dt> <strong><code>EXIT_OPT</code></strong></dt>
-<dd>Upon an error, should execution continue
- (although the interpreter stacks will be purged)? Note that
- even in the event this is set, the interpreter will halt upon
- receiving a <code>KeyboardInterrupt</code>. Default: true.</dd>
-<dt> <strong><code>FLATTEN_OPT</code></strong></dt>
-<dd>Upon initial startup, should the <code>empy</code>
- pseudomodule namespace be flattened, <em>i.e.</em>, should
- <code>empy.flatten</code> be called? Note this option only has an effect
- when the interpreter is first created; thereafter it is
- ignored. Default: false.</dd>
-<dt> <strong><code>OVERRIDE_OPT</code></strong></dt>
-<dd>Should the <code>sys.stdout</code> object be overridden
- with a proxy object? If not, side effect output cannot be
- captured by the EmPy system, but EmPy will support
- multithreading. Default: true.</dd>
-<dt> <strong><code>CALLBACK_OPT</code></strong></dt>
-<dd>If a callback is invoked when none has yet
- been registered, should an error be raised or should the
- situation be ignored? Default: true.</dd>
-</dl>
-<h3>Data flow</h3>
-<p> <strong>input -> interpreter -> diversions -> filters -> output</strong></p>
-<p> Here, in summary, is how data flows through a working EmPy system:</p>
-
-<ol>
-<li><p> Input comes from a source, such an .em file on the command
- line, or via an <code>empy.include</code> statement.</p></li>
-<li><p> The interpreter processes this material as it comes in,
- expanding EmPy expansions as it goes.</p></li>
-<li><p> After interpretation, data is then sent through the diversion
- layer, which may allow it directly through (if no diversion is
- in progress) or defer it temporarily. Diversions that are
- recalled initiate from this point.</p></li>
-<li><p> Any filters in place are then used to filter the data and
- produce filtered data as output.</p></li>
-<li><p> Finally, any material surviving this far is sent to the output
- stream. That stream is stdout by default, but can be changed
- with the -o or -a options, or may be fully buffered with the -b
- option (that is, the output file would not even be opened until
- the entire system is finished).</p></li>
-
-</ol>
-<h3>Author's notes</h3>
-<p> I originally conceived EmPy as a replacement for my <a href="http://www.alcyone.com/max/info/m4.html">Web
- templating system</a> which
- uses <a href="http://www.seindal.dk/rene/gnu/">m4</a> (a general
- macroprocessing system for Unix).</p>
-<p> Most of my Web sites include a variety of m4 files, some of which
- are dynamically generated from databases, which are then scanned
- by a cataloging tool to organize them hierarchically (so that,
- say, a particular m4 file can understand where it is in the
- hierarchy, or what the titles of files related to it are without
- duplicating information); the results of the catalog are then
- written in database form as an m4 file (which every other m4 file
- implicitly includes), and then GNU make converts each m4 to an
- HTML file by processing it.</p>
-<p> As the Web sites got more complicated, the use of m4 (which I had
- originally enjoyed for the challenge and abstractness) really
- started to become an impediment to serious work; while I am very
- knowledgeable about m4 -- having used it for for so many years --
- getting even simple things done with it is awkward and difficult.
- Worse yet, as I started to use Python more and more over the
- years, the cataloging programs which scanned the m4 and built m4
- databases were migrated to Python and made almost trivial, but
- writing out huge awkward tables of m4 definitions simply to make
- them accessible in other m4 scripts started to become almost
- farcical -- especially when coupled with the difficulty in getting
- simple things done in m4.</p>
-<p> It occurred to me what I really wanted was an all-Python solution.
- But replacing what used to be the m4 files with standalone Python
- programs would result in somewhat awkward programs normally
- consisting mostly of unprocessed text punctuated by small portions
- where variables and small amounts of code need to be substituted.
- Thus the idea was a sort of inverse of a Python interpreter: a
- program that normally would just pass text through unmolested, but
- when it found a special signifier would execute Python code in a
- normal environment. I looked at existing Python templating
- systems, and didn't find anything that appealed to me -- I wanted
- something where the desired markups were simple and unobtrusive.
- After considering between choices of signifiers, I settled on <code>@</code>
- and EmPy was born.</p>
-<p> As I developed the tool, I realized it could have general appeal,
- even to those with widely varying problems to solve, provided the
- core tool they needed was an interpreter that could embed Python
- code inside templated text. As I continue to use the tool, I have
- been adding features as unintrusively as possible as I see areas
- that can be improved.</p>
-<p> A design goal of EmPy is that its feature set should work on
- several levels; at each level, if the user does not wish or need
- to use features from another level, they are under no obligation
- to do so. If you have no need of diversions, for instance, you
- are under no obligation to use them. If significators will not
- help you organize a set of EmPy scripts globally, then you need
- not use them. New features that are being added are whenever
- possible transparently backward compatible; if you do not need
- them, their introduction should not affect you in any way. The
- use of unknown prefix sequences results in errors, guaranteeing
- that they are reserved for future use.</p>
-<h3>Glossary</h3>
-<dl>
-<dt> <strong>control</strong></dt>
-<dd>A control markup, used to direct high-level control
- flow within an EmPy session. Control markups are expressed with
- the <code>@[...]</code> notation.</dd>
-<dt> <strong>diversion</strong></dt>
-<dd>A process by which output is deferred, and can be
- recalled later on demand, multiple times if necessary.</dd>
-<dt> <strong>document</strong></dt>
-<dd>The abstraction of an EmPy document as used by a
- processor.</dd>
-<dt> <strong>escape</strong></dt>
-<dd>A markup designed to expand to a single (usually
- non-printable) character, similar to escape sequences in C or
- other languages.</dd>
-<dt> <strong>expansion</strong></dt>
-<dd>The process of processing EmPy markups and
- producing output.</dd>
-<dt> <strong>expression</strong></dt>
-<dd>An expression markup represents a Python
- expression to be evaluated, and replaced with the <code>str</code> of its
- value. Expression markups are expressed with the <code>@(...)</code>
- notation.</dd>
-<dt> <strong>filter</strong></dt>
-<dd>A file-like object which can be chained to other
- objects (primarily the final stream) and can buffer, alter, or
- manipulate in any way the data sent. Filters can also be
- chained together in arbitrary order.</dd>
-<dt> <strong>globals</strong></dt>
-<dd>The dictionary (or dictionary-like object) which
- resides inside the interpreter and holds the currently-defined
- variables.</dd>
-<dt> <strong>hook</strong></dt>
-<dd>A callable object that can be registered in a
- dictionary, and which will be invoked before, during, or after
- certain internal operations, identified by name with a string.</dd>
-<dt> <strong>interpreter</strong></dt>
-<dd>The application (or class instance) which
- processes EmPy markup.</dd>
-<dt> <strong>markup</strong></dt>
-<dd>EmPy substitutions set off with a prefix and
- appropriate delimeters.</dd>
-<dt> <strong>output</strong></dt>
-<dd>The final destination of the result of processing an
- EmPy file.</dd>
-<dt> <strong>prefix</strong></dt>
-<dd>The ASCII character used to set off an expansions.
- By default, <code>@</code>.</dd>
-<dt> <strong>processor</strong></dt>
-<dd>An extensible system which processes a group of
- EmPy files, usually arranged in a filesystem, and scans them for
- significators.</dd>
-<dt> <strong>pseudomodule</strong></dt>
-<dd>The module-like object named <code>empy</code> which is
- exposed internally inside every EmPy system.</dd>
-<dt> <strong>shortcut</strong></dt>
-<dd>A special object which takes the place of an
- instance of the <code>Filter</code> class, to represent a special form of
- filter. These include 0 for a null filter, a callable (function
- or lambda) to represent a callable filter, or a 256-character
- string which represents a translation filter.</dd>
-<dt> <strong>significator</strong></dt>
-<dd>A special form of an assignment markup in EmPy
- which can be easily parsed externally, primarily designed for
- representing uniform assignment across a collection of files.
- Significators are indicated with the <code>@%</code> markup.</dd>
-<dt> <strong>statement</strong></dt>
-<dd>A line of code that needs to be executed;
- statements do not have return values. In EmPy, statements are
- set off with <code>@{...}</code>.</dd>
-</dl>
-<h3>Acknowledgements</h3>
-<p> Questions, suggestions, bug reports, evangelism, and even
- complaints from many people have helped make EmPy what it is
- today. Some, but by no means all, of these people are (in
- alphabetical order by surname):</p>
-
-<ul>
-<li><p>Biswapesh Chattopadhyay</p></li>
-<li><p>Beni Cherniavsky</p></li>
-<li><p>Dr. S. Candelaria de Ram</p></li>
-<li><p>Eric Eide</p></li>
-<li><p>Dinu Gherman</p></li>
-<li><p>Grzegorz Adam Hankiewicz</p></li>
-<li><p>Bohdan Kushnir</p></li>
-<li><p>Robert Kroeger</p></li>
-<li><p>Kouichi Takahashi</p></li>
-<li><p>Ville Vainio</p></li>
-
-</ul>
-<h3>Known issues and caveats</h3>
-
-<ul>
-<li><p>EmPy was primarily intended for static processing of documents,
- rather than dynamic use, and hence speed of processing was not
- the primary consideration in its design.</p></li>
-<li><p>EmPy is not threadsafe by default. This is because of the need
- for EmPy to override the <code>sys.stdout</code> file with a proxy object
- which can capture effects of <code>print</code> and other spooling to
- stdout. This proxy can be suppressed with the -n option, which
- will result in EmPy being unable to do anything meaningful with
- this output, but will allow EmPy to be threadsafe.</p></li>
-<li><p>To function properly, EmPy must override <code>sys.stdout</code> with a
- proxy file object, so that it can capture output of side effects
- and support diversions for each interpreter instance. It is
- important that code executed in an environment <em>not</em> rebind
- <code>sys.stdout</code>, although it is perfectly legal to invoke it
- explicitly (<em>e.g.</em>, <code>@sys.stdout.write("Hello world\n")</code>). If
- one really needs to access the "true" stdout, then use
- <code>sys.__stdout__</code> instead (which should also not be rebound).
- EmPy uses the standard Python error handlers when exceptions are
- raised in EmPy code, which print to <code>sys.stderr</code>.</p></li>
-<li><p>Due to Python's curious handling of the <code>print</code> statement --
- particularly the form with a trailing comma to suppress the
- final newline -- mixing statement expansions using prints inline
- with unexpanded text will often result in surprising behavior,
- such as extraneous (sometimes even deferred!) spaces. This is a
- Python "feature," and occurs in non-EmPy applications as well;
- for finer control over output formatting, use <code>sys.stdout.write</code>
- or <code>empy.interpreter.write</code> directly.</p></li>
-<li><p>The <code>empy</code> "module" exposed through the EmPy interface (<em>e.g.</em>,
- <code>@empy</code>) is an artificial module. It cannot be imported with
- the <code>import</code> statement (and shouldn't -- it is an artifact of
- the EmPy processing system and does not correspond to any
- accessible .py file).</p></li>
-<li><p>For an EmPy statement expansion all alone on a line, <em>e.g.</em>,
- <code>@{a = 1}</code>, note that this will expand to a blank line due to
- the newline following the closing curly brace. To suppress this
- blank line, use the symmetric convention <code>@{a = 1}@</code>.</p></li>
-<li><p>When using EmPy with make, note that partial output may be
- created before an error occurs; this is a standard caveat when
- using make. To avoid this, write to a temporary file and move
- when complete, delete the file in case of an error, use the -b
- option to fully buffer output (including the open), or (with GNU
- make) define a <code>.DELETE_ON_ERROR</code> target.</p></li>
-<li><p><code>empy.identify</code> tracks the context of executed <em>EmPy</em> code, not
- Python code. This means that blocks of code delimited with <code>@{</code>
- and <code>}</code> will identify themselves as appearing on the line at
- which the <code>}</code> appears, and that pure Python code executed via
- the -D, -E and -F command line arguments will show up as all taking
- place on line 1. If you're tracking errors and want more
- information about the location of the errors from the Python
- code, use the -r command line option, which will provide you
- with the full Python traceback.</p></li>
-<li><p>The conditional form of expression expansion <code>@(...?...!...)</code>
- allows the use of a colon instead of an exclamation point,
- <em>e.g.</em>, <code>@(...?...:...)</code>. This behavior is supported for
- backward compatibility, but is deprecated. Due to an oversight,
- the colon was a poor choice since colons can appear legally in
- expressions (<em>e.g.</em>, dictionary literals or lambda expressions).</p></li>
-<li><p>The '@<a href="#reftry">[try]</a>' construct only works with Python exceptions derived
- from <code>Exception</code>. It is not able to catch string exceptions.</p></li>
-<li><p>The '@<a href="#reffor">[for]</a>' variable specification supports tuples for tuple
- unpacking, even recursive tuples. However, it is limited in
- that the names included may only be valid Python identifiers,
- not arbitrary Python lvalues. Since the internal Python
- mechanism is very rarely used for this purpose (<em>e.g.</em>, 'for (x,
- l<a href="#ref0">[0]</a>, q.a) in sequence'), it is not thought to be a significant
- limitation.</p></li>
-
-</ul>
-<h3>Wish list</h3>
-<p> Here are some random ideas for future revisions of EmPy. If any
- of these are of particular interest to you, your input would be
- appreciated.</p>
-
-<ul>
-<li><p>Some real-world examples should really be included for
- demonstrating the power and expressiveness of EmPy first-hand.</p></li>
-<li><p>More extensive help (rather than a ridiculously long README),
- probably inherently using the EmPy system itself for building to
- HTML and other formats, thereby acting as a help facility and a
- demonstration of the working system.</p></li>
-<li><p>A "trivial" mode, where all the EmPy system does is scan for
- simple symbols to replace them with evaluations/executions,
- rather than having to do the contextual scanning it does now.
- This has the down side of being much less configurable and
- powerful but the upside of being extremely efficient.</p></li>
-<li><p>A "debug" mode, where EmPy prints the contents of everything
- it's about to evaluate (probably to stderr) before it does?</p></li>
-<li><p>The ability to funnel all code through a configurable <code>RExec</code>
- for user-controlled security control. This would probably
- involve abstracting the execution functionality outside of the
- interpreter. [This suggestion is on hold until the
- rexec/Bastion exploits are worked out.]</p></li>
-<li><p>Optimized handling of processing would be nice for the
- possibility of an Apache module devoted to EmPy processing.</p></li>
-<li><p>An EmPy emacs mode.</p></li>
-<li><p>An optimization of offloading diversions to files when they
- become truly huge. (This is made possible by the abstraction of
- the <code>Diversion</code> class.)</p></li>
-<li><p>Support for mapping filters (specified by dictionaries).</p></li>
-<li><p>Support for some sort of batch processing, where several EmPy
- files can be listed at once and all of them evaluated with the
- same initial (presumably expensive) environment.
- <code>empy.saveGlobals</code> and <code>empy.restoreGlobals</code> have been
- introduced as a partial solution, but they need to be made more
- robust.</p></li>
-<li><p>A more elaborate interactive mode, perhaps with a prompt and
- readline support.</p></li>
-<li><p>A StructuredText and/or reStructuredText filter would be quite
- useful, as would SGML/HTML/XML/XHTML, s-expression, Python,
- etc. auto-indenter filters.</p></li>
-<li><p>An indexing filter, which can process text and pick out
- predefined keywords and thereby setup links to them.</p></li>
-<li><p>The ability to rerun diverted material back through the
- interpreter. (This can be done, awkwardly, by manually creating
- a filter which itself contains an interpreter, but it might be
- helpful if this was an all-in-one operation.)</p></li>
-<li><p>A caching system that stores off the compilations of repeated
- evaluations and executions so that in a persistent environment
- the same code does not have to be repeatedly evaluated/executed.
- This would probably be a necessity in an Apache module-based
- solution. Perhaps caching even to the point of generating pure
- PyWM bytecode?</p></li>
-<li><p>An option to change the format of the standard EmPy errors in a
- traceback.</p></li>
-<li><p>Support for some manner of implicitly processed /etc/empyrc
- and/or ~/.empyrc file, and of course an option to inhibit its
- processing. This can already be accomplished (and with greater
- control) via use of EMPY_OPTIONS, though.</p></li>
-<li><p>More uniform handling of the preprocessing directives (-I, -D,
- -E, -F, and -P), probably mapping directly to methods in the
- <code>Interpreter</code> class.</p></li>
-<li><p>Support for integration with mod_python.</p></li>
-<li><p>In simple expressions, a <code>{...}</code> suffix has no meaning in Python
- (<em>e.g.</em>, in Python, <code>@x(...)</code> is a call, <code>@x[...]</code> is
- subscription, but <code>@x{...}</code> is illegal). This could be
- exploited by having a <code>{...}</code> suffix in a simple expression
- representing an encapsulation of an expanded string; <em>e.g.</em>,
- <code>@bullet{There are @count people here}</code> would be equivalent to
- <code>@bullet(empy.expand("There are @count people here",
- locals()))}</code>.</p></li>
-<li><p>A tool to collect significator information from a hierarchy of
- .em files and put them in a database form available for
- individual scripts would be extremely useful -- this tool should
- be extensible so that users can use it to, say, build ordered
- hierarchies of their EmPy files by detecting contextual
- information like application-specific links to other EmPy
- documents.</p></li>
-<li><p>Extensions of the basic EmPy concepts to projects for other
- interpreted languages, such as Java, Lua, Ruby, and/or Perl.</p></li>
-<li><p>Ignore <code>SystemExit</code> when doing error handling, letting the
- exception progagate up? So far no one seems to worry about
- this; deliberately exiting early in a template seems to be an
- unlikely occurrence. (Furthermore, there are the <code>os.abort</code> and
- <code>os._exit</code> facilities for terminating without exception
- propagation.)</p></li>
-<li><p>A new markup which is the equivalent of <code>$...:...$</code> in source
- control systems, where the left-hand portion represents a
- keyword and the right-hand portion represents its value which is
- substituted in by the EmPy system.</p></li>
-<li><p>The ability to obtain the filename (if relevant) and mode of the
- primary output file.</p></li>
-<li><p>The ability to redirect multiple streams of output; not
- diversions, but rather the ability to write to one file and then
- another. Since output would be under the EmPy script's control,
- this would imply a useful --no-output option, where by default
- no output is written. This would also suggest the usefulness of
- all the output file delegates (diversions, filters, abstract
- files, etc.) passing unrecognized method calls all the way down
- to underlying file object.</p></li>
-<li><p>In addition to the em.py script, an additional support library
- (non-executable) should be included which includes ancillary
- functionality for more advanced features, but which is not
- necessary to use EmPy in its basic form as a standalone
- executable. Such features would include things like
- significator processing, metadata scanning, and advanced
- prompting systems.</p></li>
-
-</ul>
-<h3>Release history</h3>
-
-<ul>
-<li><p>3.3.2; 2014 Jan 24. Additional fix for source compatibility
- between 2.x and 3.0.</p></li>
-<li><p>3.3.1; 2014 Jan 22. Source compatibility for 2.x and 3.0;
- 1.x and Jython compatibility dropped.
-<li><p>3.3; 2003 Oct 27. Custom markup '@<...>'; remove separate
- pseudomodule instance for greater transparency; deprecate
- <code>interpreter</code> attribute of pseudomodule; deprecate auxiliary
- class name attributes associated with pseudomodule in
- preparation for separate support library in 4.0; add
- --no-callback-error and --no-bangpath-processing command line
- options; add <code>atToken</code> hook.</p></li>
-<li><p>3.2; 2003 Oct 7. Reengineer hooks support to use hook
- instances; add -v option; add --relative-path option; reversed
- PEP 317 style; modify Unicode support to give less confusing
- errors in the case of unknown encodings and error handlers;
- relicensed under LGPL.</p></li>
-<li><p>3.1.1; 2003 Sep 20. Add literal <code>@"..."</code> markup; add
- --pause-at-end command line option; fix improper globals
- collision error via the <code>sys.stdout</code> proxy.</p></li>
-<li><p>3.1; 2003 Aug 8. Unicode support (Python 2.0 and above); add
- Document and Processor helper classes for processing
- significators; add --no-prefix option for suppressing all
- markups.</p></li>
-<li><p>3.0.4; 2003 Aug 7. Implement somewhat more robust lvalue
- parsing for '@<a href="#reffor">[for]</a>' construct (thanks to Beni Cherniavsky for
- inspiration).</p></li>
-<li><p>3.0.3; 2003 Jul 9. Fix bug regarding recursive tuple unpacking
- using '@<a href="#reffor">[for]</a>'; add <code>empy.saveGlobals</code>, <code>empy.restoreGlobals</code>,
- and <code>empy.defined</code> functions.</p></li>
-<li><p>3.0.2; 2003 Jun 19. <code>@?</code> and <code>@!</code> markups for changing the
- current context name and line, respectively; add <code>update</code> method
- to interpreter; new and renamed context operations,
- <code>empy.setContextName</code>, <code>empy.setContextLine</code>,
- <code>empy.pushContext</code>, <code>empy.popContext</code>.</p></li>
-<li><p>3.0.1; 2003 Jun 9. Fix simple bug preventing command line
- preprocessing directives (-I, -D, -E, -F, -P) from executing
- properly; defensive PEP 317 compliance <a href="#defunct"><a href="#refdefunct">[defunct]</a></a>.</p></li>
-<li><p>3.0; 2003 Jun 1. Control markups with '@<a href="#ref...">[...]</a>'; remove
- substitutions (use control markups instead); support
- <code>@(...?...!...)</code> for conditional expressions in addition to the
- now-deprecated <code>@(...?...:...)</code> variety; add acknowledgements
- and glossary sections to documentation; rename buffering option
- back to -b; add -m option and <code>EMPY_PSEUDO</code> environment variable
- for changing the pseudomodule name; add -n option and
- <code>EMPY_NO_OVERRIDE</code> environment variable for suppressing
- <code>sys.stdout</code> proxy; rename main error class to 'Error'; add
- standalone <code>expand</code> function; add --binary and --chunk-size
- options; reengineer parsing system to use Tokens for easy
- extensibility; safeguard curly braces in simple expressions
- (meaningless in Python and thus likely a typographical error) by
- making them a parse error; fix bug involving custom Interpreter
- instances ignoring globals argument; distutils support.</p></li>
-<li><p>2.3; 2003 Feb 20. Proper and full support for concurrent and
- recursive interpreters; protection from closing the true stdout
- file object; detect edge cases of interpreter globals or
- <code>sys.stdout</code> proxy collisions; add globals manipulation
- functions <code>empy.getGlobals</code>, <code>empy.setGlobals</code>, and
- <code>empy.updateGlobals</code> which properly preserve the <code>empy</code>
- pseudomodule; separate usage info out into easily accessible
- lists for easier presentation; have -h option show simple usage
- and -H show extened usage; add <code>NullFile</code> utility class.</p></li>
-<li><p>2.2.6; 2003 Jan 30. Fix a bug in the <code>Filter.detach</code> method
- (which would not normally be called anyway).</p></li>
-<li><p>2.2.5; 2003 Jan 9. Strip carriage returns out of executed code
- blocks for DOS/Windows compatibility.</p></li>
-<li><p>2.2.4; 2002 Dec 23. Abstract Filter interface to use methods
- only; add <code>@[noop: ...]</code> substitution for completeness and block
- commenting <a href="#defunct"><a href="#refdefunct">[defunct]</a></a>.</p></li>
-<li><p>2.2.3; 2002 Dec 16. Support compatibility with Jython by
- working around a minor difference between CPython and Jython in
- string splitting.</p></li>
-<li><p>2.2.2; 2002 Dec 14. Include better docstrings for pseudomodule
- functions; segue to a dictionary-based options system for
- interpreters; add <code>empy.clearAllHooks</code> and 'empy.clearGlobals';
- include a short documentation section on embedding interpreters;
- fix a bug in significator regular expression.</p></li>
-<li><p>2.2.1; 2002 Nov 30. Tweak test script to avoid writing
- unnecessary temporary file; add <code>Interpreter.single</code> method;
- expose <code>evaluate</code>, <code>execute</code>, <code>substitute</code> <a href="#defunct"><a href="#refdefunct">[defunct]</a></a>, and
- <code>single</code> methods to the pseudomodule; add (rather obvious)
- <code>EMPY_OPTIONS</code> environment variable support; add
- <code>empy.enableHooks</code> and 'empy.disableHooks'; include optimization
- to transparently disable hooks until they are actually used.</p></li>
-<li><p>2.2; 2002 Nov 21. Switched to -V option for version
- information; <code>empy.createDiversion</code> for creating initially empty
- diversion; direct access to diversion objects with
- 'empy.retrieveDiversion'; environment variable support; removed
- --raw long argument (use --raw-errors instead); added quaternary
- escape code (well, why not).</p></li>
-<li><p>2.1; 2002 Oct 18. <code>empy.atExit</code> registry separate from hooks to
- allow for normal interpreter support; include a benchmark sample
- and test.sh verification script; expose <code>empy.string</code> directly;
- -D option for explicit defines on command line; remove
- ill-conceived support for <code>@else:</code> separator in <code>@[if ...]</code>
- substitution <a href="#defunct"><a href="#refdefunct">[defunct]</a></a> ; handle nested substitutions properly
- <a href="#defunct"><a href="#refdefunct">[defunct]</a></a> ; <code>@[macro ...]</code> substitution for creating recallable
- expansions <a href="#defunct"><a href="#refdefunct">[defunct]</a></a>.</p></li>
-<li><p>2.0.1; 2002 Oct 8. Fix missing usage information; fix
- after_evaluate hook not getting called; add <code>empy.atExit</code> call
- to register values.</p></li>
-<li><p>2.0; 2002 Sep 30. Parsing system completely revamped and
- simplified, eliminating a whole class of context-related bugs;
- builtin support for buffered filters; support for registering
- hooks; support for command line arguments; interactive mode with
- -i; significator value extended to be any valid Python
- expression.</p></li>
-<li><p>1.5.1; 2002 Sep 24. Allow <code>@]</code> to represent unbalanced close
- brackets in <code>@[...]</code> markups <a href="#defunct"><a href="#refdefunct">[defunct]</a></a>.</p></li>
-<li><p>1.5; 2002 Sep 18. Escape codes (<code>@\...</code>); conditional and
- repeated expansion substitutions <a href="#defunct"><a href="#refdefunct">[defunct]</a></a> ; replaced with control
- markups]; fix a few bugs involving files which do not end in
- newlines.</p></li>
-<li><p>1.4; 2002 Sep 7. Fix bug with triple quotes; collapse
- conditional and protected expression syntaxes into the single
- generalized <code>@(...)</code> notation; <code>empy.setName</code> and <code>empy.setLine</code>
- functions <a href="#deprecated"><a href="#refdeprecated">[deprecated]</a></a> ; true support for multiple concurrent
- interpreters with improved sys.stdout proxy; proper support for
- <code>empy.expand</code> to return a string evaluated in a subinterpreter
- as intended; merged Context and Parser classes together, and
- separated out Scanner functionality.</p></li>
-<li><p>1.3; 2002 Aug 24. Pseudomodule as true instance; move toward
- more verbose (and clear) pseudomodule functions; fleshed out
- diversion model; filters; conditional expressions; protected
- expressions; preprocessing with -P (in preparation for
- possible support for command line arguments).</p></li>
-<li><p>1.2; 2002 Aug 16. Treat bangpaths as comments; <code>empy.quote</code> for
- the opposite process of 'empy.expand'; significators (<code>@%...</code>
- sequences); -I option; -f option; much improved documentation.</p></li>
-<li><p>1.1.5; 2002 Aug 15. Add a separate <code>invoke</code> function that can be
- called multiple times with arguments to simulate multiple runs.</p></li>
-<li><p>1.1.4; 2002 Aug 12. Handle strings thrown as exceptions
- properly; use getopt to process command line arguments; cleanup
- file buffering with AbstractFile; very slight documentation and
- code cleanup.</p></li>
-<li><p>1.1.3; 2002 Aug 9. Support for changing the prefix from within
- the <code>empy</code> pseudomodule.</p></li>
-<li><p>1.1.2; 2002 Aug 5. Renamed buffering option <a href="#defunct"><a href="#refdefunct">[defunct]</a></a>, added -F
- option for interpreting Python files from the command line,
- fixed improper handling of exceptions from command line options
- (-E, -F).</p></li>
-<li><p>1.1.1; 2002 Aug 4. Typo bugfixes; documentation clarification.</p></li>
-<li><p>1.1; 2002 Aug 4. Added option for fully buffering output
- (including file opens), executing commands through the command
- line; some documentation errors fixed.</p></li>
-<li><p>1.0; 2002 Jul 23. Renamed project to EmPy. Documentation and
- sample tweaks; added <code>empy.flatten</code>. Added -a option.</p></li>
-<li><p>0.3; 2002 Apr 14. Extended "simple expression" syntax,
- interpreter abstraction, proper context handling, better error
- handling, explicit file inclusion, extended samples.</p></li>
-<li><p>0.2; 2002 Apr 13. Bugfixes, support non-expansion of Nones,
- allow choice of alternate prefix.</p></li>
-<li><p>0.1.1; 2002 Apr 12. Bugfixes, support for Python 1.5.x, add -r
- option.</p></li>
-<li><p>0.1; 2002 Apr 12. Initial early access release.</p></li>
-
-</ul>
-<h3>Author</h3>
-<p> This module was written by <a href="http://www.alcyone.com/max/">Erik Max Francis</a>. If you use this software, have
- suggestions for future releases, or bug reports, <a href="mailto:software@alcyone.com">I'd love to hear
- about it</a>.</p>
-<p> Even if you try out EmPy for a project and find it unsuitable, I'd
- like to know what stumbling blocks you ran into so they can
- potentially be addressed in a future version.</p>
-<h3>Version</h3>
-<p> Version 3.3.2 $Date: 2004-01-25 $ $Author: max $</p>
-<table border="0" cellpadding="5" cellspacing="0" width="100%">
-
- <tr>
- <th bgcolor="#99ccff"
- rowspan="2"
- valign="top"
- align="left"
- width="20%"
- >
- <font color="#000000">
- <a name="Modules and Packages">Modules and Packages</a>
- </font>
- </th>
- <th bgcolor="#99ccff"
- valign="top"
- align="left"
- width="80%"
- >
- <font color="#000000"> </font>
- </th>
- </tr>
- <tr>
- <td>
-
-<table border="0" cellpadding="3" cellspacing="0">
-<tr><td valign="top" align="left"><p><a href="home/max/projects/empy/doc/em.html">em</a></p></td><td valign="top" align="left">
-<p>A system for processing Python as markup embedded in text.</p>
-</td></tr>
-</table>
-</td></tr>
-</table>
-
- </td>
- </tr>
- </table>
-
- <hr>
-
- <p><i><a href="index.html">Table of Contents</a></i></p>
-
- <font size="-2"><i>This document was automatically generated
- on Wed Jan 22 00:00:00 2014 by
- <a href="http://happydoc.sourceforge.net">HappyDoc</a> version
- 2.1</i></font>
-
- </body>
- </html>
-
\ No newline at end of file
-#!/usr/bin/env python
-#
-# $Id: em.py 5364 2014-01-24 21:39:38Z max $ $Date: 2014-01-24 13:39:38 -0800 (Fri, 24 Jan 2014) $
+#!/usr/bin/env python3
"""
-A system for processing Python as markup embedded in text.
+A system for processing Python via markup embeded in text.
"""
+__project__ = "EmPy"
+__program__ = "empy"
+__module__ = "em"
+__version__ = "4.0.1"
+__url__ = "http://www.alcyone.com/software/empy/"
+__author__ = "Erik Max Francis <max@alcyone.com>"
+__contact__ = "software@alcyone.com"
+__copyright__ = "Copyright (C) 2002-2023 Erik Max Francis"
+__license__ = "BSD"
-__program__ = 'empy'
-__version__ = '3.3.2'
-__url__ = 'http://www.alcyone.com/software/empy/'
-__author__ = 'Erik Max Francis <max@alcyone.com>'
-__copyright__ = 'Copyright (C) 2002-2014 Erik Max Francis'
-__license__ = 'LGPL'
-
+#
+# imports
+#
+import codecs
import copy
import getopt
-import inspect
import os
import re
import sys
-import types
+import unicodedata
-# 2.x/3.0 compatbility
-try:
- from StringIO import StringIO
-except ImportError:
- from io import StringIO
+#
+# compatibility
+#
-try:
- _unicode = unicode # bytes will be undefined in 3.x releases
- _str = str
- _unichr = unichr
- _input = raw_input
- def _exec(code, globals, locals=None):
+# Initializes the following global names based on Python 2.x vs. 3.x:
+#
+# - major Detected major Python version
+# - minor Detected minor Python version
+# - minimum Minimum supported Python version (major, minor)
+# - compat List of Python backward-compatibility features applied
+# - narrow Was this Python built with narrow Unicode (UTF-16 natively)?
+# - nativeStr The native str type (str in Python 3.x; str in Python 2.x)
+# - str (_unicode) The str type (str in Python 3.x; unicode in Python 2.x)
+# - bytes (_str) The bytes type (bytes in Python 3.x; str in Python 2.x)
+# - strType The str type (Python 3.x) or the bytes and str types (2.x)
+# - chr The chr function (unichr in Python 2.x)
+# - input The input function (raw_input in Python 2.x)
+# - evalFunc The eval function
+# - execFunc The exec function
+# - BaseException The base exception class for all exceptions
+# - StringIO The StringIO class
+# - isIdentifier Is this string a valid Python identifier?
+# - uliteral Return a version-specific wide Unicode literal ('\U...')
+# - toString Convert an arbitrary object to a Unicode-compatible string
+
+# The major version of Python (2 or 3).
+major = sys.version_info[0]
+# The minor version of Python.
+minor = sys.version_info[1]
+# A list of Python backward-compatibility features which were applied.
+compat = []
+# The native str type/function.
+nativeStr = str
+# The eval function.
+evalFunc = eval
+if major == 2:
+ # We're using Python 2.x! Make sure there are Python 3.x-like names for
+ # the basic types and functions; hereafter, use str for unicode and bytes
+ # for str, respectively.
+ bytes = _str = str
+ str = _unicode = unicode
+ strType = (bytes, str)
+ chr = unichr
+ input = raw_input
+ # In Python 2.x, StringIO is contained in the cStringIO module.
+ try:
+ from cStringIO import StringIO
+ except ImportError:
+ # If cStringIO is not present for some reason, try to use the slower
+ # StringIO module.
+ from StringIO import StringIO
+ if minor < 5:
+ # Starting with Python 2.5, a new BaseException class serves as the
+ # base class of all exceptions; prior to that, it was just Exception.
+ # So create a name for it if necessary.
+ compat.append('BaseException')
+ BaseException = Exception
+ # In Python 2.x, exec is a statement; in Python 3.x, it's a function. Make
+ # a new function that will simulate the Python 3.x form but work in Python
+ # 2.x.
+ def execFunc(code, globals=None, locals=None):
if globals is None:
exec("""exec code""")
else:
exec("""exec code in globals""")
else:
exec("""exec code in globals, locals""")
-except NameError:
- _unicode = str
- _str = bytes
- _unichr = chr
- _input = input
+ def toString(value):
+ """Convert value to a (Unicode) string."""
+ if isinstance(value, _unicode):
+ # Good to go.
+ return value
+ elif isinstance(value, _str):
+ # It's already a str (bytes), convert it to a unicode (str).
+ return _unicode(value)
+ else:
+ # In Python 2.x, __str__ returns a str, not a unicode. Convert the
+ # object to a str (bytes), then convert it to a unicode (str).
+ return _unicode(_str(value))
+ def isIdentifier(string, first=True):
+ """Is this string a valid identifier? If first is true, make
+ sure the first character is a valid starting identifier character."""
+ for char in string:
+ if first:
+ if not (char.isalpha() or char == '_'):
+ return False
+ first = False
+ else:
+ if not (char.isalpha() or char.isdigit() or char == '_'):
+ return False
+ return True
+ def uliteral(i):
+ """Return a wide Unicode string literal."""
+ return r"u'\U%08x'" % i
+elif major >= 3:
+ # We're using Python 3.x! Add Python 2.x-like names for the basic types
+ # and functions. The name duplication is so that there will always be a
+ # definition of both str and types in the globals (as opposed to the
+ # builtins).
+ bytes = _str = bytes
+ str = _unicode = str
+ strType = str
+ chr = chr
+ input = input
+ # In Python 3.x, the module containing StringIO is io.
+ from io import StringIO
+ # In Python 3.x, exec is a function, but attempting to reference it as such
+ # in Python 2.x generates an error. Since this needs to also compile in
+ # Python 2.x, defer the evaluation past the parsing phase.
try:
- _exec = __builtins__.__dict__['exec']
- except AttributeError:
- _exec = __builtins__['exec']
-
-# Some basic defaults.
-FAILURE_CODE = 1
-DEFAULT_PREFIX = '@'
-DEFAULT_PSEUDOMODULE_NAME = 'empy'
-DEFAULT_SCRIPT_NAME = '?'
-SIGNIFICATOR_RE_SUFFIX = r"%(\S+)\s*(.*)\s*$"
-SIGNIFICATOR_RE_STRING = DEFAULT_PREFIX + SIGNIFICATOR_RE_SUFFIX
-BANGPATH = '#!'
-DEFAULT_CHUNK_SIZE = 8192
-DEFAULT_ERRORS = 'strict'
+ execFunc = evalFunc('exec')
+ except NameError:
+ execFunc = evalFunc('__builtins__.exec')
+ def toString(value):
+ """Convert value to a (Unicode) string."""
+ return str(value)
+ def isIdentifier(string, first=True):
+ """Is this string a valid identifier? If first is true, make
+ sure the first character is a valid starting identifier character."""
+ if first:
+ return string.isidentifier()
+ else:
+ return ('_' + string).isidentifier()
+ def uliteral(i):
+ """Return a wide Unicode string literal."""
+ return r"'\U%08x'" % i
+
+# Was this Python interpreter built with narrow Unicode? That is, does it use
+# a UTF-16 encoding (with surrgoate pairs) vs. UTF-32 internally?
+if hasattr(sys, 'maxunicode'):
+ narrow = sys.maxunicode < 0x10000
+else:
+ narrow = len(evalFunc(uliteral(0x10000))) > 1
+if narrow:
+ # Narrow Python builds will raise a ValueError when calling chr (unichr) on
+ # a code point value outside of the Basic Multilingual Plane (U+0000
+ # .. U+FFFF). See if it needs to be replaced.
+ _chr = chr
+ if major == 2:
+ if minor >= 6:
+ # Versions 2.6 and up can use this struct/decode trick.
+ compat.append('chr/decode')
+ def chr(i, _chr=_chr):
+ if i < 0x10000:
+ return _chr(i)
+ else:
+ import struct
+ try:
+ return struct.pack('i', i).decode('utf-32')
+ except UnicodeDecodeError:
+ raise ValueError("chr() arg not in range")
+ else:
+ # Earlier versions (2.5 and below) need to evaluate a literal.
+ compat.append('chr/uliteral')
+ def chr(i, _chr=_chr):
+ if i < 0x10000:
+ return _chr(i)
+ else:
+ try:
+ return evalFunc(uliteral(i))
+ except (SyntaxError, UnicodeDecodeError):
+ raise ValueError("chr() arg not in range")
+ compat.append('narrow')
+
+#
+# constants
+#
# Character information.
-IDENTIFIER_FIRST_CHARS = '_abcdefghijklmnopqrstuvwxyz' \
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-IDENTIFIER_CHARS = IDENTIFIER_FIRST_CHARS + '0123456789.'
-ENDING_CHARS = {'(': ')', '[': ']', '{': '}'}
+UNDERSCORE_CHAR = '_'
+DOT_CHAR = '.'
+BACKSLASH_CHAR = '\\'
+CARET_CHAR = '^'
+STROKE_CHAR = '|'
+OCTOTHORPE_CHAR = '#'
+ASTERISK_CHAR = '*'
+QUESTION_CHAR = '?'
+EXCLAMATION_CHAR = '!'
+PERCENT_CHAR = '%'
+OPEN_PARENTHESIS_CHAR = '('
+OPEN_BRACE_CHAR = '{'
+OPEN_BRACKET_CHAR = '['
+OPEN_ANGLE_CHAR = '<'
+BACKQUOTE_CHAR = '`'
+DOLLAR_CHAR = '$'
+COLON_CHAR = ':'
+WHITESPACE_CHARS = ' \t\v\f\r\n'
+CARRIAGE_RETURN_CHAR = '\r'
+NEWLINE_CHAR = '\n'
+OPENING_CHARS = '([{<'
+PHRASE_OPENING_CHARS = '(['
+CLOSING_CHARS = ')]}>'
+QUOTE_CHARS = '\'\"'
+ENDING_CHAR_MAP = {'(': ')', '[': ']', '{': '}', '<': '>'}
# Environment variable names.
OPTIONS_ENV = 'EMPY_OPTIONS'
+CONFIG_ENV = 'EMPY_CONFIG'
PREFIX_ENV = 'EMPY_PREFIX'
PSEUDO_ENV = 'EMPY_PSEUDO'
FLATTEN_ENV = 'EMPY_FLATTEN'
-RAW_ENV = 'EMPY_RAW_ERRORS'
+RAW_ERRORS_ENV = 'EMPY_RAW_ERRORS'
INTERACTIVE_ENV = 'EMPY_INTERACTIVE'
-BUFFERED_ENV = 'EMPY_BUFFERED_OUTPUT'
-NO_OVERRIDE_ENV = 'EMPY_NO_OVERRIDE'
-UNICODE_ENV = 'EMPY_UNICODE'
-INPUT_ENCODING_ENV = 'EMPY_UNICODE_INPUT_ENCODING'
-OUTPUT_ENCODING_ENV = 'EMPY_UNICODE_OUTPUT_ENCODING'
-INPUT_ERRORS_ENV = 'EMPY_UNICODE_INPUT_ERRORS'
-OUTPUT_ERRORS_ENV = 'EMPY_UNICODE_OUTPUT_ERRORS'
-
-# Interpreter options.
-BANGPATH_OPT = 'processBangpaths' # process bangpaths as comments?
-BUFFERED_OPT = 'bufferedOutput' # fully buffered output?
-RAW_OPT = 'rawErrors' # raw errors?
-EXIT_OPT = 'exitOnError' # exit on error?
-FLATTEN_OPT = 'flatten' # flatten pseudomodule namespace?
-OVERRIDE_OPT = 'override' # override sys.stdout with proxy?
-CALLBACK_OPT = 'noCallbackError' # is no custom callback an error?
-
-# Usage info.
-OPTION_INFO = [
-("-V --version", "Print version and exit"),
-("-h --help", "Print usage and exit"),
-("-H --extended-help", "Print extended usage and exit"),
-("-k --suppress-errors", "Do not exit on errors; go interactive"),
-("-p --prefix=<char>", "Change prefix to something other than @"),
-(" --no-prefix", "Do not do any markup processing at all"),
-("-m --module=<name>", "Change the internal pseudomodule name"),
-("-f --flatten", "Flatten the members of pseudmodule to start"),
-("-r --raw-errors", "Show raw Python errors"),
-("-i --interactive", "Go into interactive mode after processing"),
-("-n --no-override-stdout", "Do not override sys.stdout with proxy"),
-("-o --output=<filename>", "Specify file for output as write"),
-("-a --append=<filename>", "Specify file for output as append"),
-("-b --buffered-output", "Fully buffer output including open"),
-(" --binary", "Treat the file as a binary"),
-(" --chunk-size=<chunk>", "Use this chunk size for reading binaries"),
-("-P --preprocess=<filename>", "Interpret EmPy file before main processing"),
-("-I --import=<modules>", "Import Python modules before processing"),
-("-D --define=<definition>", "Execute Python assignment statement"),
-("-E --execute=<statement>", "Execute Python statement before processing"),
-("-F --execute-file=<filename>", "Execute Python file before processing"),
-(" --pause-at-end", "Prompt at the ending of processing"),
-(" --relative-path", "Add path of EmPy script to sys.path"),
-(" --no-callback-error", "Custom markup without callback is error"),
-(" --no-bangpath-processing", "Suppress bangpaths as comments"),
-("-u --unicode", "Enable Unicode subsystem (Python 2+ only)"),
-(" --unicode-encoding=<e>", "Set both input and output encodings"),
-(" --unicode-input-encoding=<e>", "Set input encoding"),
-(" --unicode-output-encoding=<e>", "Set output encoding"),
-(" --unicode-errors=<E>", "Set both input and output error handler"),
-(" --unicode-input-errors=<E>", "Set input error handler"),
-(" --unicode-output-errors=<E>", "Set output error handler"),
-]
+DELETE_ON_ERROR_ENV = 'EMPY_DELETE_ON_ERROR'
+NO_PROXY_ENV = 'EMPY_NO_PROXY'
+BUFFERING_ENV = 'EMPY_BUFFERING'
+BINARY_ENV = 'EMPY_BINARY'
+ENCODING_ENV = 'EMPY_ENCODING'
+INPUT_ENCODING_ENV = 'EMPY_INPUT_ENCODING'
+OUTPUT_ENCODING_ENV = 'EMPY_OUTPUT_ENCODING'
+ERRORS_ENV = 'EMPY_ERRORS'
+INPUT_ERRORS_ENV = 'EMPY_INPUT_ERRORS'
+OUTPUT_ERRORS_ENV = 'EMPY_OUTPUT_ERRORS'
+
+# A regular expression string suffix which will match singificators; prepend
+# the interpreter prefix to make a full regular expression string. A
+# successful match will yield six groups, arranged in two clusters of three.
+# Each cluster contains the following three named groups in index order:
+#
+# - string: A `!` to represent a stringized significator, or blank
+# - key: The significator key
+# - value: The significator value; can be blank
+#
+# The value should be stripped before being tested. If it is blank and if the
+# significator is not stringized, then the resulting significator value will be
+# None.
+#
+# The first cluster (with group names ending in 2: string2, key2, value2)
+# matches multiline significators; the second (with group names ending in 1:
+# string1, key1, value1) matches singleline ones. Only one of these clusters
+# will be set.
+#
+# The regular expression should be compiled with the following flags:
+# re.MULTILINE|re.DOTALL|re.VERBOSE. To get a compiled regular expression
+# object for a given config, call `config.significatorRe()`.
+SIGNIFICATOR_RE_STRING_SUFFIX = r"""
+ # Flags: re.MULTILINE|re.DOTALL|re.VERBOSE
+% # Opening `%`
+(?: # Start non-grouping choice: Multiline
+ % # A second `%`
+ (?P<string2>!?) # An optional `!` [string2]
+ [ \t\v\f\r]* # Zero or more non-newline whitespace
+ (?P<key2>\S+) # One or more non-whitespace [key2]
+ \s* # Zero or more whitespace
+ (?P<value2>[^%]*) # Zero or more non-`%` characters [value2]
+ \s* # Zero or more whitespace
+ %% # Closing `%%`
+| # Next non-grouping choice: Singleline
+ (?P<string1>!?) # An optional `!` [string1]
+ [ \t\v\f\r]* # Zero or more non-newline whitespace
+ (?P<key1>\S+) # One or more non-whitespace [key1]
+ [ \t\v\f\r]* # Zero or more non-newline whitespace
+ (?P<value1>[^\n]*) # Zero or more non-newline characters [value1]
+ [ \t\v\f\r]* # Zero or more non-newline whitespace
+) # End choice
+$ # End string
+"""
-USAGE_NOTES = """\
-Notes: Whitespace immediately inside parentheses of @(...) are
-ignored. Whitespace immediately inside braces of @{...} are ignored,
-unless ... spans multiple lines. Use @{ ... }@ to suppress newline
-following expansion. Simple expressions ignore trailing dots; `@x.'
-means `@(x).'. A #! at the start of a file is treated as a @#
-comment."""
-
-MARKUP_INFO = [
-("@# ... NL", "Comment; remove everything up to newline"),
-("@? NAME NL", "Set the current context name"),
-("@! INTEGER NL", "Set the current context line number"),
-("@ WHITESPACE", "Remove following whitespace; line continuation"),
-("@\\ ESCAPE_CODE", "A C-style escape sequence"),
-("@@", "Literal @; @ is escaped (duplicated prefix)"),
-("@), @], @}", "Literal close parenthesis, bracket, brace"),
-("@ STRING_LITERAL", "Replace with string literal contents"),
-("@( EXPRESSION )", "Evaluate expression and substitute with str"),
-("@( TEST [? THEN [! ELSE]] )", "If test is true, evaluate then, otherwise else"),
-("@( TRY $ CATCH )", "Expand try expression, or catch if it raises"),
-("@ SIMPLE_EXPRESSION", "Evaluate simple expression and substitute;\n"
- "e.g., @x, @x.y, @f(a, b), @l[i], etc."),
-("@` EXPRESSION `", "Evaluate expression and substitute with repr"),
-("@: EXPRESSION : [DUMMY] :", "Evaluates to @:...:expansion:"),
-("@{ STATEMENTS }", "Statements are executed for side effects"),
-("@[ CONTROL ]", "Control markups: if E; elif E; for N in E;\n"
- "while E; try; except E, N; finally; continue;\n"
- "break; end X"),
-("@%% KEY WHITESPACE VALUE NL", "Significator form of __KEY__ = VALUE"),
-("@< CONTENTS >", "Custom markup; meaning provided by user"),
-]
+#
+# Error ...
+#
-ESCAPE_INFO = [
-("@\\0", "NUL, null"),
-("@\\a", "BEL, bell"),
-("@\\b", "BS, backspace"),
-("@\\dDDD", "three-digit decimal code DDD"),
-("@\\e", "ESC, escape"),
-("@\\f", "FF, form feed"),
-("@\\h", "DEL, delete"),
-("@\\n", "LF, linefeed, newline"),
-("@\\N{NAME}", "Unicode character named NAME"),
-("@\\oOOO", "three-digit octal code OOO"),
-("@\\qQQQQ", "four-digit quaternary code QQQQ"),
-("@\\r", "CR, carriage return"),
-("@\\s", "SP, space"),
-("@\\t", "HT, horizontal tab"),
-("@\\uHHHH", "16-bit hexadecimal Unicode HHHH"),
-("@\\UHHHHHHHH", "32-bit hexadecimal Unicode HHHHHHHH"),
-("@\\v", "VT, vertical tab"),
-("@\\xHH", "two-digit hexadecimal code HH"),
-("@\\z", "EOT, end of transmission"),
-]
+class Error(Exception):
-PSEUDOMODULE_INFO = [
-("VERSION", "String representing EmPy version"),
-("SIGNIFICATOR_RE_STRING", "Regular expression matching significators"),
-("SIGNIFICATOR_RE_SUFFIX", "The above stub, lacking the prefix"),
-("interpreter", "Currently-executing interpreter instance"),
-("argv", "The EmPy script name and command line arguments"),
-("args", "The command line arguments only"),
-("identify()", "Identify top context as name, line"),
-("setContextName(name)", "Set the name of the current context"),
-("setContextLine(line)", "Set the line number of the current context"),
-("atExit(callable)", "Invoke no-argument function at shutdown"),
-("getGlobals()", "Retrieve this interpreter's globals"),
-("setGlobals(dict)", "Set this interpreter's globals"),
-("updateGlobals(dict)", "Merge dictionary into interpreter's globals"),
-("clearGlobals()", "Start globals over anew"),
-("saveGlobals([deep])", "Save a copy of the globals"),
-("restoreGlobals([pop])", "Restore the most recently saved globals"),
-("defined(name, [loc])", "Find if the name is defined"),
-("evaluate(expression, [loc])", "Evaluate the expression"),
-("serialize(expression, [loc])", "Evaluate and serialize the expression"),
-("execute(statements, [loc])", "Execute the statements"),
-("single(source, [loc])", "Execute the 'single' object"),
-("atomic(name, value, [loc])", "Perform an atomic assignment"),
-("assign(name, value, [loc])", "Perform an arbitrary assignment"),
-("significate(key, [value])", "Significate the given key, value pair"),
-("include(file, [loc])", "Include filename or file-like object"),
-("expand(string, [loc])", "Explicitly expand string and return"),
-("string(data, [name], [loc])", "Process string-like object"),
-("quote(string)", "Quote prefixes in provided string and return"),
-("flatten([keys])", "Flatten module contents into globals namespace"),
-("getPrefix()", "Get current prefix"),
-("setPrefix(char)", "Set new prefix"),
-("stopDiverting()", "Stop diverting; data sent directly to output"),
-("createDiversion(name)", "Create a diversion but do not divert to it"),
-("retrieveDiversion(name)", "Retrieve the actual named diversion object"),
-("startDiversion(name)", "Start diverting to given diversion"),
-("playDiversion(name)", "Recall diversion and then eliminate it"),
-("replayDiversion(name)", "Recall diversion but retain it"),
-("purgeDiversion(name)", "Erase diversion"),
-("playAllDiversions()", "Stop diverting and play all diversions in order"),
-("replayAllDiversions()", "Stop diverting and replay all diversions"),
-("purgeAllDiversions()", "Stop diverting and purge all diversions"),
-("getFilter()", "Get current filter"),
-("resetFilter()", "Reset filter; no filtering"),
-("nullFilter()", "Install null filter"),
-("setFilter(shortcut)", "Install new filter or filter chain"),
-("attachFilter(shortcut)", "Attach single filter to end of current chain"),
-("areHooksEnabled()", "Return whether or not hooks are enabled"),
-("enableHooks()", "Enable hooks (default)"),
-("disableHooks()", "Disable hook invocation"),
-("getHooks()", "Get all the hooks"),
-("clearHooks()", "Clear all hooks"),
-("addHook(hook, [i])", "Register the hook (optionally insert)"),
-("removeHook(hook)", "Remove an already-registered hook from name"),
-("invokeHook(name_, ...)", "Manually invoke hook"),
-("getCallback()", "Get interpreter callback"),
-("registerCallback(callback)", "Register callback with interpreter"),
-("deregisterCallback()", "Deregister callback from interpreter"),
-("invokeCallback(contents)", "Invoke the callback directly"),
-("Interpreter", "The interpreter class"),
-]
+ def __init__(self, *args, **kwargs):
+ # super does not work here for old versions of Python 2.x.
+ Exception.__init__(self, *args)
+ self.__dict__.update(kwargs)
-ENVIRONMENT_INFO = [
-(OPTIONS_ENV, "Specified options will be included"),
-(PREFIX_ENV, "Specify the default prefix: -p <value>"),
-(PSEUDO_ENV, "Specify name of pseudomodule: -m <value>"),
-(FLATTEN_ENV, "Flatten empy pseudomodule if defined: -f"),
-(RAW_ENV, "Show raw errors if defined: -r"),
-(INTERACTIVE_ENV, "Enter interactive mode if defined: -i"),
-(BUFFERED_ENV, "Fully buffered output if defined: -b"),
-(NO_OVERRIDE_ENV, "Do not override sys.stdout if defined: -n"),
-(UNICODE_ENV, "Enable Unicode subsystem: -n"),
-(INPUT_ENCODING_ENV, "Unicode input encoding"),
-(OUTPUT_ENCODING_ENV, "Unicode output encoding"),
-(INPUT_ERRORS_ENV, "Unicode input error handler"),
-(OUTPUT_ERRORS_ENV, "Unicode output error handler"),
-]
+class ConsistencyError(Error): pass
+class DiversionError(Error): pass
+class FilterError(Error): pass
+class StackUnderflowError(Error): pass
+class StringError(Error): pass
-class Error(Exception):
- """The base class for all EmPy errors."""
- pass
+class InvocationError(Error): pass
+class ConfigurationError(Error): pass
+class ConfigurationFileNotFoundError(ConfigurationError): pass
+class CompatibilityError(ConfigurationError): pass
-EmpyError = EmPyError = Error # DEPRECATED
+class ParseError(Error): pass
+class TransientParseError(ParseError): pass
-class DiversionError(Error):
- """An error related to diversions."""
- pass
+class BadKeyError(Error, KeyError): pass
+class UnknownEmojiError(BadKeyError): pass
-class FilterError(Error):
- """An error related to filters."""
- pass
+#
+# Flow ...
+#
-class StackUnderflowError(Error):
- """A stack underflow."""
- pass
+class Flow(Exception): pass
+class ContinueFlow(Flow): pass
+class BreakFlow(Flow): pass
-class SubsystemError(Error):
- """An error associated with the Unicode subsystem."""
- pass
+#
+# Root
+#
-class FlowError(Error):
- """An exception related to control flow."""
- pass
+class Root(object):
-class ContinueFlow(FlowError):
- """A continue control flow."""
- pass
+ """The root class of all EmPy class hierarchies. It defines a default
+ __repr__ method which will work appropriately whether or not the subclass
+ defines a __str__ method. Very old versions of Python 2.x won't
+ print the proper __str__ form, but so be it."""
-class BreakFlow(FlowError):
- """A break control flow."""
- pass
+ def __repr__(self):
+ if (hasattr(self, '__str__') and hasattr(type(self), '__str__') and
+ getattr(type(self), '__str__') is not getattr(Root, '__str__')):
+ return '%s(%s)' % (self.__class__.__name__, toString(self))
+ else:
+ return '<%s @ 0x%x>' % (self.__class__.__name__, id(self))
-class ParseError(Error):
- """A parse error occurred."""
- pass
+#
+# Module
+#
-class TransientParseError(ParseError):
- """A parse error occurred which may be resolved by feeding more data.
- Such an error reaching the toplevel is an unexpected EOF error."""
- pass
+class Module(Root):
+
+ """The abstraction of an emoji module that may or may not be available
+ for usage."""
+
+ def __init__(self, name, attribute, format):
+ self.name = name
+ self.attribute = attribute
+ self.format = format
+ self.ok = False
+ self.initialize()
+
+ def __str__(self):
+ return self.name
+
+ def initialize(self):
+ """Attempt to initialize this emoji module. Set ok to true if
+ successful."""
+ try:
+ self.module = __import__(self.name)
+ self.function = getattr(self.module, self.attribute, None)
+ except ImportError:
+ self.module = self.function = None
+ if self.function is not None:
+ self.ok = True
+
+ def substitute(self, text):
+ """Substitute text using this module. Return None if
+ unsuccessful."""
+ assert self.ok
+ wrapped = self.format % text
+ try:
+ result = self.function(wrapped)
+ except KeyError:
+ return None
+ if wrapped == result:
+ return None
+ else:
+ return result
+
+
+#
+# Configuration
+#
+
+class Configuration(Root):
+
+ """The configuration encapsulates all the defaults and parameterized
+ behavior of an interpreter. When created, an interpreter is assigned
+ a configuration; multiple configurations can be shared between different
+ interpreters. To override the defaults of an interpreter, create a
+ Configuration instance and then modify its attributes."""
+
+ # Constants.
+ version = __version__
+ bangpath = '#!'
+ unknownScriptName = '<->'
+ significatorReStringSuffix = SIGNIFICATOR_RE_STRING_SUFFIX
+ fullBuffering = -1
+ noBuffering = 0
+ lineBuffering = 1
+ unwantedGlobalsKeys = [None, '__builtins__'] # None = pseudomodule name
+ unflattenableGlobalsKeys = ['globals']
+ priorityVariables = ['checkVariables']
+ emojiModuleInfos = [
+ # module name, attribute name, wrapping format
+ ('emoji', 'emojize', ':%s:'),
+ ('emojis', 'encode', ':%s:'),
+ ('emoji_data_python', 'replace_colons', ':%s:'),
+ ('unicodedata', 'lookup', '%s'),
+ ]
-class MetaError(Exception):
+ # Defaults.
+
+ defaultName = 'default'
+ defaultPrefix = '@'
+ defaultPseudomoduleName = 'empy'
+ defaultRoot = '<root>'
+ defaultBuffering = 16384
+ defaultContextFormat = '%(name)s:%(line)d:%(column)d'
+ defaultNormalizationForm = 'NFKC'
+ defaultErrors = 'strict'
+ defaultConfigVariableName = '_'
+ defaultStdout = sys.stdout
+ defaultSuccessCode = 0
+ defaultFailureCode = 1
+ defaultUnknownCode = 2
+ defaultSignificatorDelimiters = ('__', '__')
+ defaultEmptySignificator = None
+ defaultAutoValidateIcons = True
+ defaultEmojiModuleNames = [
+ 'emoji',
+ 'emojis',
+ 'emoji_data_python',
+ 'unicodedata',
+ ]
+ defaultNoEmojiModuleNames = [
+ 'unicodedata',
+ ]
- """A wrapper around a real Python exception for including a copy of
- the context."""
-
- def __init__(self, contexts, exc):
- Exception.__init__(self, exc)
- self.contexts = contexts
- self.exc = exc
+ # Statics.
+
+ baseException = BaseException
+ topLevelErrors = (ConfigurationError,)
+ fallThroughErrors = (SyntaxError,)
+ proxyWrapper = None
+ useContextFormatMethod = None
+ emojiModules = None
+ iconsSignature = None
+ verboseFile = sys.stderr
+ factory = None
+ ignorableErrorAttributes = ['args', 'message', 'add_note', 'with_traceback']
+
+ tokens = None # list of token factories; intialized below
+
+ _initialized = False # change only in instances
+
+ # Dictionaries.
+
+ controls = {
+ 'NUL': (0x0000, "null"),
+ 'SOH': (0x0001, "start of heading"),
+ 'STX': (0x0002, "start of text"),
+ 'ETX': (0x0003, "end of text"),
+ 'EOT': (0x0004, "end of transmission, end of data"),
+ 'ENQ': (0x0005, "enquiry"),
+ 'ACK': (0x0006, "acknowledge"),
+ 'BEL': (0x0007, "bell, alert"),
+ 'BS': (0x0008, "backspace"),
+ 'HT': (0x0009, "horizontal tabulation, tab"),
+ 'LF': (0x000a, "linefeed, newline"),
+ 'NL': (0x000a, "linefeed, newline"),
+ 'LT': (0x000b, "line tabulation, vertical tab"),
+ 'VT': (0x000b, "line tabulation, vertical tab"),
+ 'FF': (0x000c, "form feed"),
+ 'CR': (0x000d, "carriage return"),
+ 'SO': (0x000e, "shift out"),
+ 'SI': (0x000f, "shift in"),
+ 'DLE': (0x0010, "data link escape"),
+ 'DC1': (0x0011, "device control one, xon"),
+ 'XON': (0x0011, "device control one, xon"),
+ 'DC2': (0x0012, "device control two"),
+ 'XOFF': (0x0013, "device control three, xoff"),
+ 'DC3': (0x0013, "device control three, xoff"),
+ 'DC4': (0x0014, "device control four"),
+ 'NAK': (0x0015, "negative acknowledge"),
+ 'SYN': (0x0016, "synchronous idle"),
+ 'ETB': (0x0017, "end of transmission block"),
+ 'CAN': (0x0018, "cancel"),
+ 'EM': (0x0019, "end of medium"),
+ 'SUB': (0x001a, "substitute"),
+ 'ESC': (0x001b, "escape"),
+ 'FS': (0x001c, "file separator, information separator four"),
+ 'IS4': (0x001c, "file separator, information separator four"),
+ 'GS': (0x001d, "group separator, information separator three"),
+ 'IS3': (0x001d, "group separator, information separator three"),
+ 'RS': (0x001e, "record separator, information separator two"),
+ 'IS2': (0x001e, "record separator, information separator two"),
+ 'US': (0x001f, "unit separator, information separator one"),
+ 'IS1': (0x001f, "unit separator, information separator one"),
+ 'SP': (0x0020, "space"),
+ 'DEL': (0x007f, "delete"),
+ 'PAD': (0x0080, "padding character"),
+ 'HOP': (0x0081, "high octet preset"),
+ 'BPH': (0x0082, "break permitted here"),
+ 'NBH': (0x0083, "no break here"),
+ 'IND': (0x0084, "index"),
+ 'NEL': (0x0085, "next line"),
+ 'SSA': (0x0086, "start of selected area"),
+ 'ESA': (0x0087, "end of selected area"),
+ 'HTS': (0x0088, "character tabulation set"),
+ 'HTJ': (0x0089, "character tabulation with justification"),
+ 'VTS': (0x008a, "line tabulation set"),
+ 'PLD': (0x008b, "partial line forward"),
+ 'PLU': (0x008c, "partial line backward"),
+ 'RI': (0x008d, "reverse line feed"),
+ 'SS2': (0x008e, "single shift two"),
+ 'SS3': (0x008f, "single shift three"),
+ 'DCS': (0x0090, "device control string"),
+ 'PV1': (0x0091, "private use one"),
+ 'PV2': (0x0092, "private use two"),
+ 'STS': (0x0093, "set transmission state"),
+ 'CHC': (0x0094, "cancel character"),
+ 'MW': (0x0095, "message waiting"),
+ 'SPA': (0x0096, "start guarded area"),
+ 'EPA': (0x0097, "end guarded area"),
+ 'SOS': (0x0098, "start of string"),
+ 'SCI': (0x009a, "single character introducer"),
+ 'CSI': (0x009b, "control sequence introducer"),
+ 'ST': (0x009c, "string terminator"),
+ 'OSC': (0x009d, "operating system command"),
+ 'PM': (0x009e, "privacy message"),
+ 'APC': (0x009f, "application program command"),
+ 'NBSP': (0x00a0, "no-break space"),
+ 'SHY': (0x00ad, "soft hyphen, discretionary hyphen"),
+ 'CGJ': (0x034f, "combining grapheme joiner"),
+ 'NQSP': (0x2000, "en quad"),
+ 'MQSP': (0x2001, "em quad, mutton quad"),
+ 'ENSP': (0x2002, "en space, nut"),
+ 'EMSP': (0x2003, "em space, mutton"),
+ '3MSP': (0x2004, "three-per-em space, thick space"),
+ '4MSP': (0x2005, "four-per-em space, mid space"),
+ '6MSP': (0x2006, "six-per-em space"),
+ 'FSP': (0x2007, "figure space"),
+ 'PSP': (0x2008, "punctuation space"),
+ 'THSP': (0x2009, "thin space"),
+ 'HSP': (0x200a, "hair space"),
+ 'ZWSP': (0x200b, "zero width space"),
+ 'ZWNJ': (0x200c, "zero width non-joiner"),
+ 'ZWJ': (0x200d, "zero width joiner"),
+ 'LRM': (0x200e, "left-to-right mark"),
+ 'RLM': (0x200f, "right-to-left mark"),
+ 'NBH': (0x2011, "non-breaking hyphen"),
+ 'LSEP': (0x2028, "line separator"),
+ 'PSEP': (0x2029, "paragraph separator"),
+ 'LRE': (0x202a, "left-to-right encoding"),
+ 'RLE': (0x202b, "right-to-left encoding"),
+ 'PDF': (0x202c, "pop directional formatting"),
+ 'LRO': (0x202d, "left-to-right override"),
+ 'RLO': (0x202e, "right-to-left override"),
+ 'NNBSP': (0x202f, "narrow no-break space"),
+ 'MMSP': (0x205f, "medium mathematical space"),
+ 'WJ': (0x2060, "word joiner"),
+ 'FA': (0x2061, "function application (`f()`)"),
+ 'IT': (0x2062, "invisible times (`x`)"),
+ 'IS': (0x2063, "invisible separator (`,`)"),
+ 'ISS': (0x206a, "inhibit symmetric swapping"),
+ 'ASS': (0x206b, "activate symmetric swapping"),
+ 'IAFS': (0x206c, "inhibit arabic form shaping"),
+ 'AAFS': (0x206d, "activate arabic form shaping"),
+ 'NADS': (0x206e, "national digit shapes"),
+ 'NODS': (0x206f, "nominal digit shapes"),
+ 'IDSP': (0x3000, "ideographic space"),
+ 'IVI': (0x303e, "ideographic variation indicator"),
+ 'VS1': (0xfe00, "variation selector 1"),
+ 'VS2': (0xfe01, "variation selector 2"),
+ 'VS3': (0xfe02, "variation selector 3"),
+ 'VS4': (0xfe03, "variation selector 4"),
+ 'VS5': (0xfe04, "variation selector 5"),
+ 'VS6': (0xfe05, "variation selector 6"),
+ 'VS7': (0xfe06, "variation selector 7"),
+ 'VS8': (0xfe07, "variation selector 8"),
+ 'VS9': (0xfe08, "variation selector 9"),
+ 'VS10': (0xfe09, "variation selector 10"),
+ 'VS11': (0xfe0a, "variation selector 11"),
+ 'VS12': (0xfe0b, "variation selector 12"),
+ 'VS13': (0xfe0c, "variation selector 13"),
+ 'VS14': (0xfe0d, "variation selector 14"),
+ 'VS15': (0xfe0e, "variation selector 15, text display"),
+ 'TEXT': (0xfe0e, "variation selector 15, text display"),
+ 'VS16': (0xfe0f, "variation selector 16, emoji display"),
+ 'EMOJI': (0xfe0f, "variation selector 16, emoji display"),
+ 'BOM': (0xfeff, "zero width no-break space, byte order mark"),
+ 'ZWNBSP': (0xfeff, "zero width no-break space, byte order mark"),
+ 'IAA': (0xfff9, "interlinear annotation anchor"),
+ 'IAS': (0xfffa, "interlinear annotation separator"),
+ 'IAT': (0xfffb, "interlinear annotation terminator"),
+ 'ORC': (0xfffc, "object replacement character"),
+ 'RC': (0xfffd, "replacement character"),
+ }
+
+ diacritics = {
+ '`': (0x0300, "grave"),
+ "'": (0x0301, "acute"),
+ '^': (0x0302, "circumflex accent"),
+ '~': (0x0303, "tilde"),
+ '-': (0x0304, "macron"),
+ '_': (0x0305, "overline"),
+ '(': (0x0306, "breve"),
+ '.': (0x0307, "dot"),
+ ':': (0x0308, "diaeresis"),
+ '?': (0x0309, "hook above"),
+ 'o': (0x030a, "ring above"),
+ '"': (0x030b, "double acute accent"),
+ 'v': (0x030c, "caron"),
+ 's': (0x030d, "vertical line above"),
+ 'S': (0x030e, "double vertical line above"),
+ '[': (0x030f, "double grave accent"),
+ '@': (0x0310, "candrabinu"),
+ ')': (0x0311, "inverted breve"),
+ '1': (0x0312, "turned comma above"),
+ '2': (0x0313, "comma above"),
+ '3': (0x0314, "reversed comma above"),
+ '4': (0x0315, "comma above right"),
+ ']': (0x0316, "grave accent below"),
+ '[': (0x0317, "acute accent below"),
+ '<': (0x0318, "left tack below"),
+ '>': (0x0319, "right tack below"),
+ 'A': (0x031a, "left angle above"),
+ 'h': (0x031b, "horn"),
+ 'r': (0x031c, "left half ring below"),
+ 'u': (0x031d, "up tack below"),
+ 'd': (0x031e, "down tack below"),
+ '+': (0x031f, "plus sign below"),
+ 'm': (0x0320, "minus sign below"),
+ 'P': (0x0321, "palatalized hook below"),
+ 'R': (0x0322, "retroflex hook below"),
+ 'D': (0x0323, "dot below"),
+ 'E': (0x0324, "diaeresis below"),
+ 'O': (0x0325, "ring below"),
+ 'c': (0x0326, "comma below"),
+ ',': (0x0327, "cedilla"),
+ 'K': (0x0328, "ogonek"),
+ 'V': (0x0329, "vertical line below"),
+ '$': (0x032a, "bridge below"),
+ 'W': (0x032b, "inverted double arch below"),
+ 'H': (0x032c, "caron below"),
+ 'C': (0x032d, "circumflex accent below"),
+ 'B': (0x032e, "breve below"),
+ 'N': (0x032f, "inverted breve below"),
+ 'T': (0x0330, "tilde below"),
+ 'M': (0x0331, "macron below"),
+ 'l': (0x0332, "low line"),
+ 'L': (0x0333, "double low line"),
+ '&': (0x0334, "tilde overlay"),
+ '!': (0x0335, "short stroke overlay"),
+ '|': (0x0336, "long stroke overlay"),
+ '%': (0x0337, "short solidays overlay"),
+ '/': (0x0338, "long solidus overlay"),
+ 'g': (0x0339, "right half ring below"),
+ '*': (0x033a, "inverted bridge below"),
+ '#': (0x033b, "square below"),
+ 'G': (0x033c, "seagull below"),
+ 'x': (0x033d, "x above"),
+ ';': (0x033e, "vertical tilde"),
+ '=': (0x033f, "double overline"),
+ }
+
+ icons = {
+ '!': ([0x2757, 0xfe0f], "exclamation mark"),
+ '$': (0x1f4b2, "heavy dollar sign"),
+ '%%': (0x1f3b4, "flower playing cards"),
+ '%': None,
+ '%c': ([0x2663, 0xfe0f], "club suit"),
+ '%d': ([0x2666, 0xfe0f], "diamond suit"),
+ '%e': (0x1f9e7, "red gift envelope"),
+ '%h': ([0x2665, 0xfe0f], "heart suit"),
+ '%j': (0x1f0cf, "joker"),
+ '%r': (0x1f004, "Mahjong red dragon"),
+ '%s': ([0x2660, 0xfe0f], "spade suit"),
+ '&!': ([0x1f396, 0xfe0f], "military medal"),
+ '&$': (0x1f3c6, "trophy"),
+ '&': None,
+ '&0': (0x1f3c5, "sports medal"),
+ '&1': (0x1f947, "first place medal"),
+ '&2': (0x1f948, "second place medal"),
+ '&3': (0x1f949, "third place medal"),
+ '*': None,
+ '**': ([0x2716, 0xfe0f], "heavy multiplication sign"),
+ '*+': ([0x2795, 0xfe0f], "heavy plus sign"),
+ '*-': ([0x2796, 0xfe0f], "heavy minus sign"),
+ '*/': ([0x2797, 0xfe0f], "heavy division sign"),
+ '+': (0x1f53a, "red triangle pointed up"),
+ ',': None,
+ ',+': (0x1f44d, "thumbs up"),
+ ',-': (0x1f44e, "thumbs down"),
+ ',a': ([0x261d, 0xfe0f], "point above"),
+ ',d': (0x1f447, "point down"),
+ ',f': (0x1f44a, "oncoming fist"),
+ ',l': (0x1f448, "point left"),
+ ',o': (0x1faf5, "point out"),
+ ',r': (0x1f449, "point right"),
+ ',s': (0x1f91d, "handshake"),
+ ',u': (0x1f446, "point up"),
+ '-': (0x1f53b, "red triangle pointed down"),
+ '.': None,
+ '.d': ([0x2b07, 0xfe0f], "down arrow"),
+ '.l': ([0x2b05, 0xfe0f], "left arrow"),
+ '.r': ([0x27a1, 0xfe0f], "right arrow"),
+ '.u': ([0x2b06, 0xfe0f], "up arrow"),
+ '/': ([0x2714, 0xfe0f], "check mark"),
+ ':$': (0x1f911, "money-mouth face"),
+ ':': None,
+ ':(': (0x1f61e, "disappointed face"),
+ ':)': (0x1f600, "grinning face"),
+ ':*': (0x1f618, "face blowing a kiss"),
+ ':/': (0x1f60f, "smirking face"),
+ ':0': (0x1f636, "face without mouth"),
+ ':1': (0x1f914, "thinking face"),
+ ':2': (0x1f92b, "shushing face"),
+ ':3': (0x1f617, "kissing face"),
+ ':4': (0x1f605, "grinning face with sweat"),
+ ':5': (0x1f972, "smiling face with tear"),
+ ':6': (0x1f602, "face with tears of joy"),
+ ':7': (0x1f917, "smiling face with open hands"),
+ ':8': (0x1f910, "zipper-mouth face"),
+ ':9': (0x1f923, "rolling on the floor laughing"),
+ ':D': (0x1f601, "beaming face with smiling eyes"),
+ ':O': (0x1f62f, "hushed face"),
+ ':P': (0x1f61b, "face with tongue"),
+ ':S': (0x1fae1, "saluting face"),
+ ':T': (0x1f62b, "tired face"),
+ ':Y': (0x1f971, "yawning face"),
+ ':Z': (0x1f634, "sleeping face"),
+ ':[': (0x1f641, "frowning face"),
+ ':\\': (0x1f615, "confused face"),
+ ':]': ([0x263a, 0xfe0f], "smiling face"),
+ ':|': (0x1f610, "neutral face"),
+ ';': None,
+ ';)': (0x1f609, "winking face"),
+ '<': None,
+ '<3': ([0x2764, 0xfe0f], "red heart"),
+ '?': ([0x2753, 0xfe0f], "question mark"),
+ 'B': None,
+ 'B)': (0x1f60e, "smiling face with sunglasses"),
+ 'E': (0x2130, "script capital E"),
+ 'F': (0x2131, "script capital F"),
+ 'M': (0x2133, "script capital M"),
+ '\"': None,
+ '\"(': (0x201c, "left double quotation mark"),
+ '\")': (0x201d, "right double quotation mark"),
+ '\"\"': (0x0022, "quotation mark"),
+ '\'': None,
+ '\'(': (0x2018, "left single quotation mark"),
+ '\')': (0x2019, "right single quotation mark"),
+ '\'/': (0x00b4, "acute accent"),
+ '\'\'': (0x0027, "apostrophe"),
+ '\'\\': (0x0060, "grave accent"),
+ '\\': ([0x274c, 0xfe0f], "cross mark"),
+ '^': ([0x26a0, 0xfe0f], "warning sign"),
+ '{!!': None,
+ '{!!}': ([0x203c, 0xfe0f], "double exclamation mark"),
+ '{!': None,
+ '{!?': None,
+ '{!?}': ([0x2049, 0xfe0f], "exclamation question mark"),
+ '{': None,
+ '{(': None,
+ '{()': None,
+ '{()}': (0x1f534, "red circle"),
+ '{[': None,
+ '{[]': None,
+ '{[]}': (0x1f7e5, "red square"),
+ '{{': None,
+ '{{}': None,
+ '{{}}': ([0x2b55, 0xfe0f], "hollow red circle"),
+ '|': (0x1f346, "aubergine"),
+ '~': ([0x3030, 0xfe0f], "wavy dash"),
+ }
+
+ emojis = {}
+
+ def __init__(self, **kwargs):
+ # Meta variables.
+ self._names = []
+ self._specs = {}
+ self._initials = {}
+ self._descriptions = {}
+ self._nones = {}
+ self._functions = {}
+ # Initialize.
+ self.initialize()
+ # Mark initialized.
+ self._initialized = True
+ # Update with any keyword arguments, if specified.
+ self.update(**kwargs)
+
+ def __setattr__(self, name, value):
+ self.set(name, value)
+
+ def __contains__(self, name):
+ return name in self.__dict__
+
+ def __bool__(self): return self._initialized # 3.x
+ def __nonzero__(self): return self._initialized # 2.x
+
+ def __iter__(self):
+ return iter(self._names)
def __str__(self):
- backtrace = [str(x) for x in self.contexts]
- return "%s: %s (%s)" % (self.exc.__class__, self.exc,
- (', '.join(backtrace)))
-
-
-class Subsystem:
-
- """The subsystem class defers file creation so that it can create
- Unicode-wrapped files if desired (and possible)."""
-
- def __init__(self):
- self.useUnicode = False
- self.inputEncoding = None
- self.outputEncoding = None
- self.errors = None
-
- def initialize(self, inputEncoding=None, outputEncoding=None,
- inputErrors=None, outputErrors=None):
- self.useUnicode = True
- defaultEncoding = sys.getdefaultencoding()
- if inputEncoding is None:
- inputEncoding = defaultEncoding
- self.inputEncoding = inputEncoding
- if outputEncoding is None:
- outputEncoding = defaultEncoding
- self.outputEncoding = outputEncoding
- if inputErrors is None:
- inputErrors = DEFAULT_ERRORS
- self.inputErrors = inputErrors
- if outputErrors is None:
- outputErrors = DEFAULT_ERRORS
- self.outputErrors = outputErrors
-
- def assertUnicode(self):
- if not self.useUnicode:
- raise SubsystemError("Unicode subsystem unavailable")
-
- def open(self, name, mode=None):
- if self.useUnicode:
- return self.unicodeOpen(name, mode)
- else:
- return self.defaultOpen(name, mode)
-
- def defaultOpen(self, name, mode=None):
+ results = []
+ for name in self._names:
+ results.append("%s=%s" % (name, repr(self.get(name))))
+ return ', '.join(results)
+
+ # Initialization.
+
+ def initialize(self):
+ """Setup the declarations and definitions for the defined
+ attributes."""
+ self.define('name', strType, self.defaultName, "The name of this configuration (optional)")
+ self.define('notes', None, None, "Notes for this configuration (optional)")
+ self.define('prefix', strType, self.defaultPrefix, "The prefix", none=True, env=PREFIX_ENV)
+ self.define('pseudomoduleName', strType, self.defaultPseudomoduleName, "The pseudomodule name", env=PSEUDO_ENV)
+ self.define('verbose', bool, False, "Verbose processing (for debugging)?")
+ self.define('rawErrors', bool, None, "Print Python stacktraces on error?", env=RAW_ERRORS_ENV)
+ self.define('exitOnError', bool, True, "Exit after an error?")
+ self.define('ignoreErrors', bool, False, "Ignore errors?")
+ self.define('contextFormat', strType, self.defaultContextFormat, "Context format")
+ self.define('goInteractive', bool, None, "Go interactive after done processing?", env=INTERACTIVE_ENV)
+ self.define('deleteOnError', bool, None, "Delete output file on error?", env=DELETE_ON_ERROR_ENV)
+ self.define('doFlatten', bool, None, "Flatten pseudomodule members at start?", env=FLATTEN_ENV)
+ self.define('useProxy', bool, None, "Install a stdout proxy?", env=NO_PROXY_ENV, invert=True)
+ self.define('relativePath', bool, False, "Add EmPy script path to sys.path?")
+ self.define('buffering', int, self.defaultBuffering, "Specify buffering strategy for files:\n0 (none), 1 (line), -1 (full), or N", env=BUFFERING_ENV, func=self.setBuffering)
+ self.define('noCallbackIsError', bool, True, "Is custom markup with no callback an error?")
+ self.define('replaceNewlines', bool, True, "Replace newlines with spaces in expressions?")
+ self.define('ignoreBangpaths', bool, True, "Treat bangpaths as comments?")
+ self.define('noneSymbol', (strType, None), None, "String to write when expanding None")
+ self.define('missingConfigIsError', bool, True, "Is a missing configuration file an error?")
+ self.define('pauseAtEnd', bool, False, "Prompt at the end of processing?")
+ self.define('startingLine', int, 1, "Line number to start with")
+ self.define('startingColumn', int, 1, "Column number to start with")
+ self.define('significatorDelimiters', tuple, self.defaultSignificatorDelimiters, "Significator variable delimiters")
+ self.define('emptySignificator', object, self.defaultEmptySignificator, "Value to use for empty significators", none=True)
+ self.define('autoValidateIcons', bool, self.defaultAutoValidateIcons, "Automatically validate icons before each use?")
+ self.define('emojiModuleNames', list, self.defaultEmojiModuleNames, "List of emoji modules to try to use\n", none=True)
+ self.define('emojiNotFoundIsError', bool, True, "Is an unknown emoji an error?")
+ self.define('useBinary', bool, False, "Open files as binary (Python 2.x Unicode)?", env=BINARY_ENV)
+ defaultEncoding = self.environment(ENCODING_ENV, self.getDefaultEncoding())
+ self.define('inputEncoding', strType, defaultEncoding, "Set input Unicode encoding", none=True, env=INPUT_ENCODING_ENV, helpFunction=lambda x: x == 'utf_8' and 'utf-8' or x)
+ self.define('outputEncoding', strType, defaultEncoding, "Set output Unicode encoding", none=True, env=OUTPUT_ENCODING_ENV, helpFunction=lambda x: x == 'utf_8' and 'utf-8' or x)
+ defaultErrors = self.environment(ERRORS_ENV, self.defaultErrors)
+ self.define('inputErrors', strType, defaultErrors, "Set input Unicode error handler", none=True, env=INPUT_ERRORS_ENV)
+ self.define('outputErrors', strType, defaultErrors, "Set output Unicode error handler", none=True, env=OUTPUT_ERRORS_ENV)
+ self.define('normalizationForm', strType, self.defaultNormalizationForm, "Specify Unicode normalization form", none=True)
+ self.define('autoPlayDiversions', bool, True, "Auto-play diversions on exit?")
+ self.define('expandUserConstructions', bool, True, "Expand ~ and ~user constructions")
+ self.define('configVariableName', strType, self.defaultConfigVariableName, "Configuration variable name while loading")
+ self.define('successCode', int, self.defaultSuccessCode, "Exit code to return on script success")
+ self.define('failureCode', int, self.defaultFailureCode, "Exit code to return on script failure")
+ self.define('unknownCode', int, self.defaultUnknownCode, "Exit code to return on bad configuration")
+ self.define('checkVariables', bool, True, "Check configuration variables on assignment?")
+ self.define('pathSeparator', strType, sys.platform.startswith('win') and ';' or ':', "Path separator for configuration file paths")
+
+ # Redefine static configuration variables so they're in the help.
+ self.define('controls', dict, self.controls, "Controls dictionary")
+ self.define('diacritics', dict, self.diacritics, "Diacritics dictionary")
+ self.define('icons', dict, self.icons, "Icons dictionary")
+ self.define('emojis', dict, self.emojis, "Emojis dictionary")
+ # If the encoding or error handling has changed, enable binary
+ # implicitly, just as if it had been specified on the command line.
+ if (self.inputEncoding != defaultEncoding or
+ self.outputEncoding != defaultEncoding or
+ self.inputErrors != defaultErrors or
+ self.outputErrors != defaultErrors):
+ self.enableBinary(major, minor)
+
+ def isInitialized(self):
+ """Is this configuration initialized and ready for use?"""
+ return self._initialized
+
+ def check(self, inputFilename, outputFilename):
+ """Do a sanity check on the configuration settings."""
+ if self.prefix == '' or self.prefix == 'none' or self.prefix == 'None':
+ self.prefix = None
+ if self.buffering is None:
+ self.buffering = self.defaultBuffering
+ if isinstance(self.prefix, strType) and len(self.prefix) != 1:
+ raise ConfigurationError("prefix must be single-character string")
+ if not self.pseudomoduleName:
+ raise ConfigurationError("pseudomodule name must be non-empty string")
+ if self.deleteOnError and outputFilename is None:
+ raise ConfigurationError("-d only makes sense with -o, -a, -O or -A arguments")
+ if self.hasNoBuffering() and not self.hasBinary():
+ raise ConfigurationError("no buffering requires file open in binary mode; try adding -u option")
+
+ # Access.
+
+ def declare(self, name, specs, initial, description,
+ none=False, helpFunction=None):
+ """Declare the configuration attribute."""
+ self._names.append(name)
+ self._specs[name] = specs
+ self._initials[name] = initial
+ self._descriptions[name] = description
+ self._nones[name] = none
+ self._functions[name] = helpFunction
+
+ def define(self, name, specs, value, description, none=False,
+ env=None, func=None, blank=None, invert=False, helpFunction=None):
+ """Define a configuration attribute with the given name, type
+ specification, initial value, and description. If none is true, None
+ is a legal value. Also, allow an optional corresponding environment
+ variable, and, if present, an optional blank variable to set the
+ value to if the environment variable is defined but is blank. If
+ both env and func are present, call the function to set the
+ environment variable. Finally, if invert is true, invert the
+ (bool) environment variable. Additionally, if the type specification
+ is or contains toString, convert the value to a proper string."""
+ if isinstance(specs, tuple):
+ isString = str in specs or bytes in specs
+ else:
+ isString = str is specs or bytes is specs
+ if value is not None and specs is not None:
+ assert isinstance(value, specs)
+ if env is not None:
+ if func is not None:
+ if self.hasEnvironment(env):
+ value = func(self.environment(env, value))
+ elif isString:
+ value = self.environment(env, value, blank)
+ elif specs is bool:
+ value = self.hasEnvironment(env)
+ if invert:
+ value = not value
+ elif not isinstance(specs, tuple):
+ value = specs(self.environment(env, value, blank))
+ else:
+ assert False, "environment attribute type must be bool or str: %s" % name
+ if isString and value is not None:
+ value = toString(value)
+ self.declare(name, specs, value, description, none, helpFunction)
+ self.set(name, value)
+
+ def has(self, name):
+ """Is this name a valid configuration attribute?"""
+ return name in self.__dict__ or name in self.__class__.__dict__
+
+ def get(self, name, default=None):
+ """Get this (valid, existing) configuration attribute."""
+ return getattr(self, name, default)
+
+ def set(self, name, value):
+ """Set the (valid) configuration attribute, checking its type
+ if necessary."""
+ if self._initialized and self.checkVariables:
+ if not name.startswith('_'):
+ # If this attribute is not already present, it's invalid.
+ if not self.has(name):
+ raise ConfigurationError("unknown configuration attribute: %s" % name)
+ # If there's a registered type for this attribute, check it.
+ specs = self._specs.get(name)
+ if specs is not None:
+ if value is None:
+ if not self._nones[name]:
+ raise ConfigurationError("configuration value cannot be None: %s: %s; %s" % (name, value, specs))
+ elif not isinstance(value, specs):
+ raise ConfigurationError("configuration value has invalid type: %s: %s; %s" % (name, value, specs))
+ self.__dict__[name] = value
+
+ def update(self, **kwargs):
+ """Update the configuration by keyword arguments."""
+ for name, value in kwargs.items():
+ if not self.has(name):
+ raise ConfigurationError("unknown configuration attribute: %s" % name)
+ self.set(name, value)
+
+ def clone(self, deep=False):
+ """Create a distinct copy of this configuration. Make it deep if
+ desired."""
+ if deep:
+ copyMethod = copy.deepcopy
+ else:
+ copyMethod = copy.copy
+ return copyMethod(self)
+
+ # Configuration file loading.
+
+ def run(self, statements):
+ """Run some configuration variable assignment statements."""
+ locals = {self.configVariableName: self}
+ execFunc(statements, globals(), locals)
+ keys = list(locals.keys())
+ # Put the priority variables first.
+ for priority in self.priorityVariables:
+ if priority in locals:
+ keys.remove(priority)
+ keys.insert(0, priority)
+ for key in keys:
+ if not key.startswith('_') and key != self.configVariableName:
+ setattr(self, key, locals[key])
+ return True
+
+ def load(self, filename, required=None):
+ """Update the configuration by loading from a resource
+ file. If required is true, raise an exception; if false,
+ ignore; if None, use the default in this configuration.
+ Return whether or not the load succeeded."""
+ if required is None:
+ required = self.missingConfigIsError
+ try:
+ file = self.open(filename, 'r')
+ except IOError:
+ if required:
+ raise ConfigurationFileNotFoundError("cannot open configuration file: %s" % filename, filename)
+ return False
+ locals = {self.configVariableName: self}
+ try:
+ contents = file.read()
+ return self.run(contents)
+ finally:
+ file.close()
+
+ def path(self, path, required=None):
+ """Attempt to load several resource paths, either as a
+ list of paths or a delimited string of paths. If required
+ is true, raise an exception; if false, ignore; if None,
+ use the default in this configuration."""
+ if isinstance(path, list):
+ filenames = path
+ else:
+ filenames = path.split(self.pathSeparator)
+ for filename in filenames:
+ self.load(filename, required)
+
+ # Environment.
+
+ def hasEnvironment(self, name):
+ """Is the current environment variable defined in the environment?
+ The value does not matter."""
+ return name in os.environ
+
+ def environment(self, name, default=None, blank=None):
+ """Get the value of the given environment variable, or default
+ if it is not set. If a variable is set to an empty value and
+ blank is non-None, return blank instead."""
+ if name in os.environ:
+ value = os.environ[name]
+ if not value and blank is not None:
+ return blank
+ else:
+ return value
+ else:
+ return default
+
+ # Convenience.
+
+ def escaped(self, ord, prefix='\\'):
+ """Write a valid Python string escape sequence for the given
+ character ordinal."""
+ if ord <= 0xff:
+ return '%sx%02x' % (prefix, ord)
+ elif ord <= 0xffff:
+ return '%su%04x' % (prefix, ord)
+ else:
+ return '%sU%08x' % (prefix, ord)
+
+ def hasDefaultPrefix(self):
+ """Is this configuration's prefix the default or
+ non-existent?"""
+ return self.prefix is None or self.prefix == self.defaultPrefix
+
+ # Buffering.
+
+ def hasFullBuffering(self): return self.buffering <= self.fullBuffering
+ def hasNoBuffering(self): return self.buffering == self.noBuffering
+ def hasLineBuffering(self): return self.buffering == self.lineBuffering
+ def hasFixedBuffering(self):
+ return self.buffering is not None and self.buffering > self.lineBuffering
+
+ def setBuffering(self, name):
+ """Set the buffering by name or value."""
+ if isinstance(name, int):
+ self.buffering = name
+ elif name == 'none':
+ self.buffering = self.noBuffering
+ elif name == 'line':
+ self.buffering = self.lineBuffering
+ elif name == 'full':
+ self.buffering = self.fullBuffering
+ elif name is None or name == 'default' or name == '':
+ self.buffering = self.defaultBuffering
+ else:
+ try:
+ self.buffering = int(name)
+ except ValueError:
+ raise ConfigurationError("invalid buffering name: %s" % name)
+ if self.buffering < self.fullBuffering:
+ self.buffering = self.fullBuffering
+ return self.buffering
+
+ # Token factories.
+
+ def createFactory(self, tokens=None):
+ """Create a token factory and return it."""
+ if tokens is None:
+ tokens = self.tokens
+ return Factory(tokens)
+
+ def adjustFactory(self):
+ """Adjust the factory to take into account a non-default
+ prefix."""
+ self.factory.adjust(self)
+
+ def getFactory(self, tokens=None, force=False):
+ """Get a factory (creating one if one has not yet been
+ created). If force is true, always create a new one."""
+ if self.factory is None or force:
+ self.factory = self.createFactory(tokens)
+ self.adjustFactory()
+ return self.factory
+
+ def resetFactory(self):
+ """Clear the current factory."""
+ self.factory = None
+
+ # Binary/Unicode.
+
+ def hasBinary(self):
+ """Is binary/Unicode file open support enabled?"""
+ return self.useBinary
+
+ def enableBinary(self, major=None, minor=None):
+ """Enable binary/Unicode file open support. This is needed in
+ Python 2.x for Unicode support. If major/minor is present, only
+ enable it implicitly if this is in fact Python 2.x."""
+ if major is None or major == 2:
+ self.useBinary = True
+
+ def disableBinary(self):
+ """Disable binary/Unicode support for this configuration."""
+ self.useBinary = False
+
+ # File I/O.
+
+ def isDefaultEncodingErrors(self, encoding=None, errors=None, asInput=True):
+ """Are both of the encoding/errors combinations the default?
+ If either passed value is None the value in this configuration
+ is what is checked. Check for input if asInput is true;
+ otherwise check output."""
+ if encoding is None:
+ if asInput:
+ encoding = self.inputEncoding
+ else:
+ encoding = self.outputEncoding
+ if encoding is not None and encoding != self.getDefaultEncoding():
+ return False
+ if errors is None:
+ if asInput:
+ errors = self.inputErrors
+ else:
+ errors = self.outputErrors
+ if errors is not None and errors != self.defaultErrors:
+ return False
+ return True
+
+ def getDefaultEncoding(self, default='unknown'):
+ """What is the default encoding?"""
+ try:
+ return sys.getdefaultencoding()
+ except AttributeError:
+ return default
+
+ def open(self, filename,
+ mode=None, buffering=-1, encoding=None, errors=None,
+ expand=None):
+ """Open a new file, handling whether or not binary
+ (Unicode) should be employed. Raise if the selection
+ cannot be complied with. Arguments:
+
+ - filename: The filename to open;
+ - mode: The file open mode, None for read;
+ - buffering: The buffering setting (int);
+ - encoding: The encoding to use, None for default;
+ - errors: The error handler to use, None for default;
+ - expand: Expand user constructions? (~ and ~user)"""
+ if expand is None:
+ expand = self.expandUserConstructions
+ if expand:
+ filename = os.path.expanduser(filename)
if mode is None:
+ # Default to read.
mode = 'r'
- return open(name, mode)
+ if self.useBinary and 'b' not in mode:
+ # Make it binary if it needs to be.
+ mode += 'b'
+ # Figure out the encoding and error handler.
+ if 'w' in mode or 'a' in mode:
+ if encoding is None:
+ encoding = self.outputEncoding
+ if errors is None:
+ errors = self.outputErrors
+ else:
+ if encoding is None:
+ encoding = self.inputEncoding
+ if errors is None:
+ errors = self.inputErrors
+ if self.useBinary:
+ # Use binary mode, so call codecs.open.
+ return codecs.open(filename, mode, encoding, errors, buffering)
+ else:
+ # If it's not binary mode, them use the standard open call.
+ if major >= 3:
+ # If it's Python 3.x, just pass the arguments through.
+ return open(filename, mode, buffering, encoding, errors)
+ else:
+ # For Python 2.x, open doesn't take encoding and error handler
+ # arguments. Check to make sure non-default encodings and
+ # error handlers haven't been chosen, because we can't comply.
+ if not self.isDefaultEncodingErrors(encoding, errors):
+ raise ConfigurationError("cannot comply with non-default Unicode encoding/errors selected in Python 2.x; use -u option: %s/%s" % (encoding, errors))
+ return open(filename, mode, buffering)
+
+ # Significators.
+
+ def significatorReString(self):
+ """Return a string that can be compiled into a regular
+ expression representing a significator. If multi is true,
+ it will match multiline significators."""
+ return self.prefix + self.significatorReStringSuffix
+
+ def significatorRe(self, flags=re.MULTILINE|re.DOTALL,
+ baseFlags=re.VERBOSE):
+ """Return a regular expression object with the given
+ flags that is suitable for parsing significators."""
+ return re.compile(self.significatorReString(), flags|baseFlags)
+
+ def significatorFor(self, key):
+ """Return the significator name for this key."""
+ prefix, suffix = self.significatorDelimiters
+ return prefix + toString(key) + suffix
+
+ # Contexts.
+
+ def setContextFormat(self, rawFormat):
+ """Set the context format, auto-detecting which
+ mechanism to use."""
+ useFormatMethod = None
+ format = rawFormat
+ if format.startswith('format:'):
+ useFormatMethod = True
+ format = format.split(':', 1)[1]
+ elif format.startswith('operator:'):
+ useFormatMethod = False
+ format = format.split(':', 1)[1]
+ elif format.startswith('variable:'):
+ useFormatMethod = False
+ format = format.split(':', 1)[1]
+ format = format.replace('$NAME', '%(name)s')
+ format = format.replace('$LINE', '%(line)d')
+ format = format.replace('$COLUMN', '%(column)d')
+ format = format.replace('$CHARS', '%(chars)d')
+ else:
+ useFormatMethod = '%' not in format
+ self.contextFormat = format
+ self.useContextFormatMethod = useFormatMethod
+
+ def renderContext(self, context):
+ """Render the context as a string according to this
+ configuration."""
+ if self.useContextFormatMethod is None:
+ self.setContextFormat(self.contextFormat)
+ return context.render(self.contextFormat, self.useContextFormatMethod)
+
+ # Icons.
+
+ def calculateIconsSignature(self, icons=None):
+ """Calculate a signature of the icons dict. If the value
+ changes, it's likely (but not certain) that the underlying
+ dict has changed. The signature will always differ from
+ None."""
+ if icons is None:
+ icons = self.icons
+ length = len(icons)
+ try:
+ # Include the size of the dictionary, if possible. If it's not
+ # available, that's okay.
+ sizeof = sys.getsizeof(icons)
+ except (AttributeError, TypeError):
+ sizeof = -1
+ return length, sizeof
+
+ def signIcons(self, icons=None):
+ """Sign the icons dict."""
+ self.iconsSignature = self.calculateIconsSignature(icons)
+ return self.iconsSignature
+
+ def transmogrifyIcons(self, icons=None):
+ """Process the icons and make sure any keys' prefixes are
+ backfilled with Nones. Call this method after modifying
+ icons."""
+ if icons is None:
+ icons = self.icons
+ additions = {}
+ for parent in icons.keys():
+ key = parent
+ while len(key) > 1:
+ key = key[:-1]
+ if key in icons:
+ value = icons[key]
+ if value is None:
+ continue
+ else:
+ raise ConfigurationError("icon '%s' makes icon '%s' inaccessible" % (key, parent))
+ else:
+ additions[key] = None
+ icons.update(additions)
+ return icons
+
+ def validateIcons(self, icons=None):
+ """If the icons have not been transmogrified yet, do so
+ and store their signature for future reference."""
+ if icons is None:
+ icons = self.icons
+ if icons is None:
+ raise ConfigurationError("icons not configured")
+ if not self.autoValidateIcons:
+ return icons
+ if self.iconsSignature is None:
+ self.transmogrifyIcons(icons)
+ self.signIcons(icons)
+ return icons
+
+ # Emojis.
+
+ def initializeEmojiModules(self, moduleNames=None):
+ """Initialize the emoji modules. If moduleNames is not
+ specified, check the defaults. Idempotent."""
+ if self.emojiModules is None:
+ okNames = []
+ # Use the config default if not specified.
+ if moduleNames is None:
+ moduleNames = self.emojiModuleNames
+ # If it's still blank, specify no modules.
+ if moduleNames is None:
+ moduleNames = []
+ # Create a map of module names for fast lookup. (This would be a
+ # set, but sets aren't available in early versions of Python 2.x.)
+ nameMap = {}
+ for moduleName in moduleNames:
+ nameMap[moduleName] = None
+ # Now iterate over each potential module.
+ self.emojiModules = {}
+ for info in self.emojiModuleInfos:
+ moduleName = info[0]
+ if moduleName in nameMap:
+ module = Module(*info)
+ if module.ok:
+ okNames.append(moduleName)
+ self.emojiModules[moduleName] = module
+ # Finally, replace the requested module names with the ones
+ # actually present.
+ self.emojiModuleNames = okNames
+ if not self.emojiModules and not self.emojis:
+ raise ConfigurationError("no emoji lookup methods available; install modules and set emoji modules or set emojis dictionary in configuration")
+
+ def substituteEmoji(self, text):
+ """Substitute emojis from the provided string. Return
+ the resulting substitution or None."""
+ if self.replaceNewlines:
+ text = text.replace('\n', ' ')
+ self.initializeEmojiModules()
+ for moduleName in self.emojiModuleNames:
+ module = self.emojiModules[moduleName]
+ result = module.substitute(text)
+ if result is not None:
+ return result
+
+ # Exit codes and errors.
+
+ def isSuccessCode(self, code):
+ """Does this exit code indicate success?"""
+ return code == self.successCode
+
+ def isExitError(self, error):
+ """Is this error a SystemExit?"""
+ return isinstance(error, SystemExit)
+
+ def errorToExitCode(self, error):
+ """Determine the exit code (can be a string) from the
+ error. If the error is None, then it is success."""
+ if error is None:
+ return self.successCode
+ isExit = self.isExitError(error)
+ if isExit:
+ if len(error.args) == 0:
+ return self.successCode
+ else:
+ # This can be a string which is okay.
+ return error.args[0]
+ else:
+ return self.failureCode
- def unicodeOpen(self, name, mode=None):
- import codecs
- if mode is None:
- mode = 'rb'
- if mode.find('w') >= 0 or mode.find('a') >= 0:
- encoding = self.outputEncoding
- errors = self.outputErrors
+ def isNotAnError(self, error):
+ """Is this error None (no error) or does it indicate a
+ successful exit?"""
+ if error is None:
+ return True
else:
- encoding = self.inputEncoding
- errors = self.inputErrors
- return codecs.open(name, mode, encoding, errors)
+ return self.isSuccessCode(self.errorToExitCode(error))
+
+ def formatError(self, error, prefix=None, suffix=None):
+ """Format an error into a string for printing."""
+ parts = []
+ if prefix is not None:
+ parts.append(prefix)
+ parts.append(error.__class__.__name__)
+ # Check for arguments.
+ if len(error.args) > 0:
+ parts.append(": ")
+ parts.append(", ".join([toString(x) for x in error.args]))
+ # Check for keyword arguments.
+ pairs = []
+ for attrib in dir(error):
+ if (attrib not in self.ignorableErrorAttributes and
+ not attrib.startswith('_')):
+ pairs.append((attrib, getattr(error, attrib)))
+ if pairs:
+ parts.append("; ")
+ pairs.sort()
+ args = []
+ for key, value in pairs:
+ args.append("%s=%s" % (key, value))
+ parts.append(', '.join(args))
+ # Fold the arguments together.
+ if suffix is not None:
+ parts.append(suffix)
+ return ''.join(parts)
+
+ # Debugging.
+
+ def printTraceback(self, file=sys.stderr):
+ import types, traceback
+ tb = None
+ depth = 0
+ while True:
+ try:
+ frame = sys._getframe(depth)
+ depth += 1
+ except ValueError:
+ break
+ tb = types.TracebackType(tb, frame, frame.f_lasti, frame.f_lineno)
+ traceback.print_tb(tb, file=file)
-theSubsystem = Subsystem()
+#
+# Version
+#
+
+class Version(Root):
+
+ """An enumerated type representing version detail levels."""
+
+ NONE, VERSION, INFO, BASIC, PYTHON, SYSTEM, PLATFORM, RELEASE, ALL = range(9)
+ DATA = BASIC
+
+#
+# Stack
+#
+class Stack(Root):
-class Stack:
-
- """A simple stack that behaves as a sequence (with 0 being the top
- of the stack, not the bottom)."""
+ """A simple stack that is implemented as a sequence."""
def __init__(self, seq=None):
if seq is None:
seq = []
self.data = seq
+ def __bool__(self): return len(self.data) != 0 # 3.x
+ def __nonzero__(self): return len(self.data) != 0 # 2.x
+
+ def __len__(self): return len(self.data)
+ def __getitem__(self, index): return self.data[-(index + 1)]
+
+ def __str__(self):
+ return '[%s]' % ', '.join([repr(x) for x in self.data])
+
def top(self):
"""Access the top element on the stack."""
- try:
+ if self.data:
return self.data[-1]
- except IndexError:
+ else:
raise StackUnderflowError("stack is empty for top")
-
+
def pop(self):
"""Pop the top element off the stack and return it."""
- try:
+ if self.data:
return self.data.pop()
- except IndexError:
+ else:
raise StackUnderflowError("stack is empty for pop")
-
+
def push(self, object):
"""Push an element onto the top of the stack."""
self.data.append(object)
+ def replace(self, object):
+ """Replace the top element of the stack with another one."""
+ if self.data:
+ self.data[-1] = object
+ else:
+ raise StackUnderflowError("stack is empty for replace")
+
def filter(self, function):
"""Filter the elements of the stack through the function."""
self.data = list(filter(function, self.data))
- def purge(self):
- """Purge the stack."""
- self.data = []
+ def purge(self, function=None):
+ """Purge the stack, calling an optional function on each element
+ first from top to bottom."""
+ if function is None:
+ self.data = []
+ else:
+ while self.data:
+ element = self.data.pop()
+ function(element)
def clone(self):
"""Create a duplicate of this stack."""
return self.__class__(self.data[:])
- def __nonzero__(self): return len(self.data) != 0 # 2.x
- def __bool__(self): return len(self.data) != 0 # 3.x
- def __len__(self): return len(self.data)
- def __getitem__(self, index): return self.data[-(index + 1)]
+#
+# File ...
+#
- def __repr__(self):
- return ('<%s instance at 0x%x [%s]>' %
- (self.__class__, id(self),
- ', '.join(repr(x) for x in self.data)))
-
-
-class AbstractFile:
-
- """An abstracted file that, when buffered, will totally buffer the
- file, including even the file open."""
-
- def __init__(self, filename, mode='w', buffered=False):
- # The calls below might throw, so start off by marking this
- # file as "done." This way destruction of a not-completely-
- # initialized AbstractFile will generate no further errors.
- self.done = True
- self.filename = filename
- self.mode = mode
- self.buffered = buffered
- if buffered:
- self.bufferFile = StringIO()
- else:
- self.bufferFile = theSubsystem.open(filename, mode)
- # Okay, we got this far, so the AbstractFile is initialized.
- # Flag it as "not done."
- self.done = False
+class File(Root):
- def __del__(self):
- self.close()
+ """An abstract filelike object."""
+
+ def write(self, data): raise NotImplementedError
+ def writelines(self, lines): raise NotImplementedError
+ def flush(self): raise NotImplementedError
+ def close(self): raise NotImplementedError
+
+
+class NullFile(File):
+
+ """A simple class that supports all the file-like object methods
+ but simply does nothing at all."""
+
+ def write(self, data): pass
+ def writelines(self, lines): pass
+ def flush(self): pass
+ def close(self): pass
+
+
+class DelegatingFile(File):
+
+ """A simple class which wraps around a delegate file-like object
+ and lets everything through."""
+
+ def __init__(self, delegate):
+ self.delegate = delegate
+
+ def __repr__(self):
+ return '<%s : %s @ 0x%x>' % (
+ self.__class__.__name__,
+ repr(self.delegate),
+ id(self))
def write(self, data):
- self.bufferFile.write(data)
+ self.delegate.write(data)
- def writelines(self, data):
- self.bufferFile.writelines(data)
+ def writelines(self, lines):
+ self.delegate.writelines(data)
def flush(self):
- self.bufferFile.flush()
+ self.delegate.flush()
def close(self):
- if not self.done:
- self.commit()
- self.done = True
+ self.delegate.close()
+ self.unlink()
- def commit(self):
- if self.buffered:
- file = theSubsystem.open(self.filename, self.mode)
- file.write(self.bufferFile.getvalue())
- file.close()
+ def unlink(self):
+ """Unlink from the delegate."""
+ self.delegate = None
+
+
+class UncloseableFile(DelegatingFile):
+
+ """A delegating file class that lets through everything except
+ close calls, which it turns into a flush."""
+
+ def close(self):
+ self.flush()
+
+
+class ProxyFile(File):
+
+ """The proxy file object that is intended to take the place of
+ sys.stdout. The proxy can manage a stack of interpreters (and
+ their file object streams) it is writing to, and an underlying
+ bottom file object."""
+
+ def __init__(self, bottom, wrapper=None):
+ """Create a new proxy file object with bottom as the
+ underlying stream. If wrapper is not None (and is an instance
+ of (a subclass of) a DelegatingFile), we should wrap and
+ unwrap the bottom file with it for protection."""
+ assert bottom is not None
+ self._EmPy_original = sys.stdout
+ self._EmPy_count = 0
+ self._EmPy_stack = Stack()
+ self._EmPy_bottom = bottom
+ self._EmPy_wrapper = wrapper
+ self._EmPy_wrap()
+
+ def __getattr__(self, attribute):
+ return getattr(self._EmPy_bottom, attribute)
+
+ def __repr__(self):
+ return '<%s [count %d, depth %d] : %s @ 0x%x>' % (
+ self.__class__.__name__,
+ self._EmPy_count,
+ len(self._EmPy_stack),
+ repr(self._EmPy_bottom),
+ id(self))
+
+ # File methods.
+
+ def write(self, data):
+ top = self._EmPy_top()
+ assert top is not None
+ top.write(data)
+
+ def writelines(self, lines):
+ top = self._EmPy_top()
+ assert top is not None
+ top.writelines(lines)
+
+ def flush(self):
+ top = self._EmPy_top()
+ assert top is not None
+ top.flush()
+
+ def close(self):
+ """Close the current file. If the current file is the bottom,
+ then flush it (don't close it) and dispose of it."""
+ top = self.top()
+ assert top is not None
+ if top is self._EmPy_bottom:
+ # If it's the bottom stream, flush it, don't close it, and mark
+ # this proxy done.
+ top.flush()
+ self._EmPy_bottom = None
else:
- self.bufferFile.close()
+ top.close()
- def abort(self):
- if self.buffered:
- self.bufferFile = None
+ # Stack management.
+
+ def _EmPy_top(self):
+ """Get the current stream (not interpreter) to write to."""
+ if self._EmPy_stack:
+ return self._EmPy_stack.top().top()
else:
- self.bufferFile.close()
- self.bufferFile = None
- self.done = True
+ return self._EmPy_bottom
+
+ def _EmPy_push(self, interpreter):
+ self._EmPy_stack.push(interpreter)
+
+ def _EmPy_pop(self, interpreter):
+ top = self._EmPy_stack.pop()
+ if interpreter.error is not None and interpreter is not top:
+ # Only check if an error is not in progress; otherwise, when there
+ # are interpreters and subinterpreters and full dispatchers,
+ # interpreters can get popped out of order.
+ raise ConsistencyError("interpreter popped off of proxy stack out of order")
+
+ def _EmPy_clear(self, interpreter):
+ self._EmPy_stack.filter(lambda x, i=interpreter: x is not i)
+
+ # Bottom file protection.
+
+ def _EmPy_shouldWrap(self):
+ """Should the bottom file be wrapped and unwrapped?"""
+ return self._EmPy_wrapper is not None
+
+ def _EmPy_wrap(self):
+ """Wrap the bottom file in a delegate."""
+ if self._EmPy_shouldWrap():
+ assert issubclass(self._EmPy_wrapper, DelegatingFile)
+ self._EmPy_bottom = self._EmPy_wrapper(self._EmPy_bottom)
+
+ def _EmPy_unwrap(self):
+ """Unwrap the bottom file from the delegate, and unlink the
+ delegate."""
+ if self._EmPy_shouldWrap():
+ wrapped = self._EmPy_bottom
+ self._EmPy_bottom = wrapped.delegate
+ wrapped.unlink()
+
+ # Special.
+
+ def _EmPy_evocare(self, increment):
+ """Do the EmPy magic: Increment or decrement the reference
+ count. Either way, return the current reference count.
+ Beware of Exodus!"""
+ if increment > 0:
+ self._EmPy_count += increment
+ elif increment < 0:
+ self._EmPy_count += increment # note: adding a negative number
+ if self._EmPy_count <= 0:
+ assert self._EmPy_original is not None
+ self._EmPy_unwrap()
+ sys.stdout = self._EmPy_original
+ return self._EmPy_count
+#
+# Diversion
+#
-class Diversion:
+class Diversion(File):
"""The representation of an active diversion. Diversions act as
(writable) file objects, and then can be recalled either as pure
strings or (readable) file objects."""
- def __init__(self):
+ def __init__(self, name):
+ self.name = name
self.file = StringIO()
- # These methods define the writable file-like interface for the
- # diversion.
+ def __str__(self):
+ return self.name
+
+ # These methods define the writable file-like interface for the diversion.
def write(self, data):
self.file.write(data)
# These methods are specific to diversions.
+ def preferFile(self):
+ """Would this particular diversion prefer to be treated as a
+ file (true) or a string (false)? This allows future
+ optimization of diversions into actual files if they get
+ overly large."""
+ return False
+
def asString(self):
"""Return the diversion as a string."""
return self.file.getvalue()
"""Return the diversion as a file."""
return StringIO(self.file.getvalue())
+ def spool(self, output, chunkSize=Configuration.defaultBuffering):
+ """Spool the diversion to the given output file."""
+ if self.preferFile():
+ # Either write it a chunk at a time ...
+ input = self.asFile()
+ while True:
+ chunk = input.read(chunkSize)
+ if not chunk:
+ break
+ output.write(chunk)
+ else:
+ # ... or write it all at once.
+ output.write(self.asString())
+
+#
+# Stream
+#
+
+class Stream(File):
-class Stream:
-
"""A wrapper around an (output) file object which supports
diversions and filtering."""
-
- def __init__(self, file):
+
+ # File methods.
+
+ def __init__(self, file, diversions):
+ assert file is not None
self.file = file
- self.currentDiversion = None
- self.diversions = {}
+ self.current = None
+ self.diversions = diversions
self.filter = file
self.done = False
+ def __repr__(self):
+ return '<%s : %s @ 0x%x>' % (
+ self.__class__.__name__,
+ repr(self.file),
+ id(self))
+
def write(self, data):
- if self.currentDiversion is None:
- self.filter.write(data)
+ if self.current is None:
+ self.filter.write(toString(data))
else:
- self.diversions[self.currentDiversion].write(data)
-
+ self.diversions[self.current].write(toString(data))
+
def writelines(self, lines):
for line in lines:
self.write(line)
def close(self):
if not self.done:
- self.undivertAll(True)
self.filter.close()
self.done = True
- def shortcut(self, shortcut):
- """Take a filter shortcut and translate it into a filter, returning
- it. Sequences don't count here; these should be detected
- independently."""
- if shortcut == 0:
- return NullFilter()
- elif (isinstance(shortcut, types.FunctionType) or
- inspect.ismethoddescriptor(shortcut) or
- isinstance(shortcut, types.BuiltinFunctionType) or
- isinstance(shortcut, types.BuiltinMethodType) or
- isinstance(shortcut, types.LambdaType)):
- return FunctionFilter(shortcut)
- elif isinstance(shortcut, _str) or isinstance(shortcut, _unicode):
- return StringFilter(filter)
- elif isinstance(shortcut, dict):
- raise NotImplementedError("mapping filters not yet supported")
- else:
- # Presume it's a plain old filter.
- return shortcut
+ # Filters.
+
+ def count(self):
+ """Count the number of filters."""
+ thisFilter = self.filter
+ result = 0
+ while thisFilter is not None and thisFilter is not self.file:
+ thisFilter = thisFilter.follow()
+ result += 1
+ return result
def last(self):
"""Find the last filter in the current filter chain, or None if
thisFilter, lastFilter = self.filter, None
while thisFilter is not None and thisFilter is not self.file:
lastFilter = thisFilter
- thisFilter = thisFilter.next()
+ thisFilter = thisFilter.follow()
return lastFilter
- def install(self, shortcut=None):
- """Install a new filter; None means no filter. Handle all the
- special shortcuts for filters here."""
- # Before starting, execute a flush.
+ def install(self, filters=None):
+ """Install a list of filters as a chain, replacing the current
+ chain."""
self.filter.flush()
- if shortcut is None or shortcut == [] or shortcut == ():
- # Shortcuts for "no filter."
+ if filters is None:
+ filters = []
+ if len(filters) == 0:
+ # An empty sequence means no filter.
self.filter = self.file
else:
- if isinstance(shortcut, list) or isinstance(shortcut, tuple):
- shortcuts = list(shortcut)
- else:
- shortcuts = [shortcut]
- # Run through the shortcut filter names, replacing them with
- # full-fledged instances of Filter.
- filters = []
- for shortcut in shortcuts:
- filters.append(self.shortcut(shortcut))
- if len(filters) > 1:
- # If there's more than one filter provided, chain them
- # together.
- lastFilter = None
- for filter in filters:
- if lastFilter is not None:
- lastFilter.attach(filter)
- lastFilter = filter
- lastFilter.attach(self.file)
- self.filter = filters[0]
- else:
- # If there's only one filter, assume that it's alone or it's
- # part of a chain that has already been manually chained;
- # just find the end.
- filter = filters[0]
- lastFilter = filter.last()
- lastFilter.attach(self.file)
- self.filter = filter
-
- def attach(self, shortcut):
- """Attached a solitary filter (no sequences allowed here) at the
+ # If there's more than one filter provided, chain them together.
+ lastFilter = None
+ for filter in filters:
+ if lastFilter is not None:
+ lastFilter.attach(filter)
+ lastFilter = filter
+ lastFilter.attach(self.file)
+ self.filter = filters[0]
+
+ def prepend(self, filter):
+ """Attach a solitary filter (no sequences allowed here)
+ at the beginning of the current filter chain."""
+ self.filter.flush()
+ firstFilter = self.filter
+ if firstFilter is None:
+ # Just install it from scratch if there is no active filter.
+ self.install([filter])
+ else:
+ # Attach this filter to the current one, and set this as the main
+ # filter.
+ filter.attach(firstFilter)
+ self.filter = filter
+
+ def append(self, filter):
+ """Attach a solitary filter (no sequences allowed here) at the
end of the current filter chain."""
+ self.filter.flush()
lastFilter = self.last()
if lastFilter is None:
# Just install it from scratch if there is no active filter.
- self.install(shortcut)
+ self.install([filter])
else:
# Attach the last filter to this one, and this one to the file.
- filter = self.shortcut(shortcut)
lastFilter.attach(filter)
filter.attach(self.file)
+ # Diversions.
+
+ def names(self):
+ """Return a sorted sequence of diversion names."""
+ keys = list(self.diversions.keys())
+ keys.sort()
+ return keys
+
+ def has(self, name):
+ """Does this stream have a diversion with the given name?"""
+ return name in self.diversions
+
def revert(self):
"""Reset any current diversions."""
- self.currentDiversion = None
+ self.current = None
def create(self, name):
"""Create a diversion if one does not already exist, but do not
- divert to it yet."""
+ divert to it yet. Return the diversion."""
if name is None:
raise DiversionError("diversion name must be non-None")
- if name not in self.diversions:
- self.diversions[name] = Diversion()
-
- def retrieve(self, name):
- """Retrieve the given diversion."""
+ diversion = None
+ if not self.has(name):
+ diversion = Diversion(name)
+ self.diversions[name] = diversion
+ return diversion
+
+ def retrieve(self, name, *defaults):
+ """Retrieve the given diversion. If an additional argument is
+ provided, return that instead of raising on a nonexistent
+ diversion."""
if name is None:
raise DiversionError("diversion name must be non-None")
- if name in self.diversions:
+ if self.has(name):
return self.diversions[name]
else:
- raise DiversionError("nonexistent diversion: %s" % name)
+ if defaults:
+ return defaults[0]
+ else:
+ raise DiversionError("nonexistent diversion: %s" % name)
def divert(self, name):
"""Start diverting."""
if name is None:
raise DiversionError("diversion name must be non-None")
self.create(name)
- self.currentDiversion = name
+ self.current = name
- def undivert(self, name, purgeAfterwards=False):
+ def undivert(self, name, dropAfterwards=False):
"""Undivert a particular diversion."""
if name is None:
raise DiversionError("diversion name must be non-None")
- if name in self.diversions:
+ if self.has(name):
diversion = self.diversions[name]
- self.filter.write(diversion.asString())
- if purgeAfterwards:
- self.purge(name)
+ diversion.spool(self.filter)
+ if dropAfterwards:
+ self.drop(name)
else:
raise DiversionError("nonexistent diversion: %s" % name)
- def purge(self, name):
- """Purge the specified diversion."""
+ def drop(self, name):
+ """Drop the specified diversion."""
if name is None:
raise DiversionError("diversion name must be non-None")
- if name in self.diversions:
+ if self.has(name):
del self.diversions[name]
- if self.currentDiversion == name:
- self.currentDiversion = None
+ if self.current == name:
+ self.current = None
- def undivertAll(self, purgeAfterwards=True):
+ def undivertAll(self, dropAfterwards=True):
"""Undivert all pending diversions."""
if self.diversions:
self.revert() # revert before undiverting!
- names = sorted(self.diversions.keys())
- for name in names:
- self.undivert(name)
- if purgeAfterwards:
- self.purge(name)
-
- def purgeAll(self):
+ for name in self.names():
+ self.undivert(name, dropAfterwards)
+
+ def dropAll(self):
"""Eliminate all existing diversions."""
if self.diversions:
- self.diversions = {}
- self.currentDiversion = None
-
+ self.diversions.clear()
+ self.current = None
-class NullFile:
+#
+# Context
+#
- """A simple class that supports all the file-like object methods
- but simply does nothing at all."""
+class Context(Root):
- def __init__(self): pass
- def write(self, data): pass
- def writelines(self, lines): pass
- def flush(self): pass
- def close(self): pass
+ """A simple interpreter context, storing only the current data.
+ It is not intended to be modified."""
+ format = Configuration.defaultContextFormat
-class UncloseableFile:
+ def __init__(self, name, line, column, chars=0,
+ startingLine=None, startingColumn=None):
+ self.name = name
+ self.line = line
+ self.column = column
+ self.chars = chars
+ if startingLine is None:
+ startingLine = line
+ self.startingLine = startingLine
+ if startingColumn is None:
+ startingColumn = column
+ self.startingColumn = startingColumn
+ self.pendingLines = 0
+ self.pendingColumns = 0
+ self.pendingChars = 0
- """A simple class which wraps around a delegate file-like object
- and lets everything through except close calls."""
+ def __str__(self):
+ return self.render(self.format)
- def __init__(self, delegate):
- self.delegate = delegate
+ def reset(self):
+ """Reset the context to the start."""
+ self.line = self.startingLine
+ self.column = self.startingColumn
+ self.chars = 0
+
+ def track(self, string, start, end):
+ """Track the information for the substring in [start, end) in
+ the context and mark it pending."""
+ assert end >= start
+ if end > start:
+ length = end - start
+ self.pendingLines += string.count(NEWLINE_CHAR, start, end)
+ loc = string.rfind(NEWLINE_CHAR, start, end)
+ if loc == -1:
+ self.pendingColumns += length
+ else:
+ self.pendingColumns = self.startingColumn + end - loc - 1
+ self.pendingChars += length
+
+ def accumulate(self):
+ """Accumulate the pending information and incorporate it into
+ the total."""
+ self.line += self.pendingLines
+ if self.pendingLines > 0:
+ self.column = self.pendingColumns # replaced, not added
+ else:
+ self.column += self.pendingColumns
+ self.chars += self.pendingChars
+ self.pendingLines = 0
+ self.pendingColumns = 0
+ self.pendingChars = 0
+
+ def save(self, strict=False):
+ """Take a snapshot of the current context."""
+ if strict and self.pendingChars == 0:
+ raise ConsistencyError("context %s has pending chars" % toString(self))
+ return Context(self.name, self.line, self.column, self.chars)
+
+ def restore(self, other, strict=False):
+ """Restore from another context."""
+ if strict and self.pendingChars == 0:
+ raise ConsistencyError("context %s has pending chars" % toString(self))
+ self.name = other.name
+ self.line = other.line
+ self.column = other.column
+ self.chars = other.chars
+
+ def render(self, format, useFormatMethod=None):
+ """Render the context with the given format. If
+ useFormatMethod is true, use the format method; if false, use
+ the % operator. If useFormatMethod is None, try to trivially
+ auto-detect given the format."""
+ record = {
+ 'name': self.name,
+ 'line': self.line,
+ 'column': self.column,
+ 'chars': self.chars,
+ }
+ if useFormatMethod is None:
+ # If it contains a percent sign, it looks like it's not using the
+ # format method.
+ useFormatMethod = '%' not in format
+ if useFormatMethod:
+ return format.format(**record)
+ else:
+ return format % record
- def write(self, data):
- self.delegate.write(data)
+ def identify(self):
+ return self.name, self.line, self.column, self.chars
- def writelines(self, lines):
- self.delegate.writelines(data)
+#
+# Token ...
+#
- def flush(self):
- self.delegate.flush()
+class Token(Root):
- def close(self):
- """Eat this one."""
- pass
+ """An element resulting from parsing."""
+ def __init__(self, current):
+ self.current = current
-class ProxyFile:
+ def __str__(self):
+ return self.string()
- """The proxy file object that is intended to take the place of
- sys.stdout. The proxy can manage a stack of file objects it is
- writing to, and an underlying raw file object."""
+ def string(self):
+ raise NotImplementedError
- def __init__(self, bottom):
- self.stack = Stack()
- self.bottom = bottom
+ def run(self, interpreter, locals):
+ raise NotImplementedError
- def current(self):
- """Get the current stream to write to."""
- if self.stack:
- return self.stack[-1][1]
- else:
- return self.bottom
- def push(self, interpreter):
- self.stack.push((interpreter, interpreter.stream()))
+class TextToken(Token):
- def pop(self, interpreter):
- result = self.stack.pop()
- assert interpreter is result[0]
+ """A chunk of text not containing markups."""
- def clear(self, interpreter):
- self.stack.filter(lambda x, i=interpreter: x[0] is not i)
+ def __init__(self, current, data):
+ super(TextToken, self).__init__(current)
+ self.data = data
- def write(self, data):
- self.current().write(data)
+ def string(self):
+ return self.data
- def writelines(self, lines):
- self.current().writelines(lines)
+ def run(self, interpreter, locals):
+ interpreter.write(self.data)
- def flush(self):
- self.current().flush()
- def close(self):
- """Close the current file. If the current file is the bottom, then
- close it and dispose of it."""
- current = self.current()
- if current is self.bottom:
- self.bottom = None
- current.close()
+class ExpansionToken(Token):
- def _testProxy(self): pass
+ """A token that involves an expansion."""
+ last = None # subclasses should always define a first class attribute
-class Filter:
+ def __init__(self, current, config, first):
+ super(ExpansionToken, self).__init__(current)
+ self.config = config
+ # Only record a local copy of first/last if it's ambiguous.
+ if self.first is None or len(self.first) != 1:
+ self.first = first
+ self.last = ENDING_CHAR_MAP.get(first)
- """An abstract filter."""
+ def scan(self, scanner):
+ pass
- def __init__(self):
- if self.__class__ is Filter:
- raise NotImplementedError
- self.sink = None
+ def run(self, interpreter, locals):
+ pass
- def next(self):
- """Return the next filter/file-like object in the sequence, or None."""
- return self.sink
- def __next__(self): return self.next()
+class CommentToken(ExpansionToken):
- def write(self, data):
- """The standard write method; this must be overridden in subclasses."""
- raise NotImplementedError
+ """The abstract base class for the comment tokens."""
- def writelines(self, lines):
- """Standard writelines wrapper."""
- for line in lines:
- self.write(line)
+ pass
- def _flush(self):
- """The _flush method should always flush the sink and should not
- be overridden."""
- self.sink.flush()
- def flush(self):
- """The flush method can be overridden."""
- self._flush()
+class LineCommentToken(CommentToken):
- def close(self):
- """Close the filter. Do an explicit flush first, then close the
- sink."""
- self.flush()
- self.sink.close()
+ """A line comment markup: ``@# ... NL``"""
- def attach(self, filter):
- """Attach a filter to this one."""
- if self.sink is not None:
- # If it's already attached, detach it first.
- self.detach()
- self.sink = filter
+ first = OCTOTHORPE_CHAR
- def detach(self):
- """Detach a filter from its sink."""
- self.flush()
- self._flush() # do a guaranteed flush to just to be safe
- self.sink = None
+ def scan(self, scanner):
+ loc = scanner.find(NEWLINE_CHAR)
+ if loc >= 0:
+ self.comment = scanner.chop(loc, 1)
+ else:
+ raise TransientParseError("comment expects newline")
- def last(self):
- """Find the last filter in this chain."""
- this, last = self, self
- while this is not None:
- last = this
- this = this.next()
- return last
+ def string(self):
+ return '%s%s%s\n' % (self.config.prefix, self.first, self.comment)
-class NullFilter(Filter):
+ def run(self, interpreter, locals):
+ interpreter.invoke('preLineComment', comment=self.comment)
- """A filter that never sends any output to its sink."""
- def write(self, data): pass
+class InlineCommentToken(CommentToken):
-class FunctionFilter(Filter):
+ first = ASTERISK_CHAR
- """A filter that works simply by pumping its input through a
- function which maps strings into strings."""
-
- def __init__(self, function):
- Filter.__init__(self)
- self.function = function
+ """An inline comment markup: ``@* ... *``"""
- def write(self, data):
- self.sink.write(self.function(data))
+ def scan(self, scanner):
+ # Find the run of starting characters to match.
+ self.count = 1
+ start = scanner.last(self.first)
+ self.count += start
+ scanner.advance(start)
+ # Then match them with the same number of closing characters.
+ loc = scanner.find(self.first * self.count, self.count)
+ if loc >= 0:
+ self.comment = scanner.chop(loc, self.count)
+ else:
+ raise TransientParseError("inline comment expects asterisk")
-class StringFilter(Filter):
+ def string(self):
+ return '%s%s%s%s' % (
+ self.config.prefix,
+ self.first * self.count,
+ self.comment,
+ self.first * self.count)
- """A filter that takes a translation string (256 characters) and
- filters any incoming data through it."""
+ def run(self, interpreter, locals):
+ interpreter.invoke('preInlineComment', comment=self.comment)
- def __init__(self, table):
- if not ((isinstance(table, _str) or isinstance(table, _unicode))
- and len(table) == 256):
- raise FilterError("table must be 256-character string")
- Filter.__init__(self)
- self.table = table
- def write(self, data):
- self.sink.write(data.translate(self.table))
+class LiteralToken(ExpansionToken):
-class BufferedFilter(Filter):
+ """The abstract base class of the literal tokens. If used as a
+ concrete token class, it will expand to the first character."""
- """A buffered filter is one that doesn't modify the source data
- sent to the sink, but instead holds it for a time. The standard
- variety only sends the data along when it receives a flush
- command."""
+ def string(self):
+ return '%s%s' % (self.config.prefix, self.first)
- def __init__(self):
- Filter.__init__(self)
- self.buffer = ''
+ def run(self, interpreter, locals):
+ interpreter.write(self.first)
- def write(self, data):
- self.buffer += data
- def flush(self):
- if self.buffer:
- self.sink.write(self.buffer)
- self._flush()
+class WhitespaceToken(LiteralToken):
-class SizeBufferedFilter(BufferedFilter):
+ """A whitespace markup: ``@ WS``"""
- """A size-buffered filter only in fixed size chunks (excepting the
- final chunk)."""
+ first = '<whitespace>'
- def __init__(self, bufferSize):
- BufferedFilter.__init__(self)
- self.bufferSize = bufferSize
+ def string(self):
+ return '%s%s' % (self.config.prefix, self.first)
- def write(self, data):
- BufferedFilter.write(self, data)
- while len(self.buffer) > self.bufferSize:
- chunk, self.buffer = self.buffer[:self.bufferSize], self.buffer[self.bufferSize:]
- self.sink.write(chunk)
+ def run(self, interpreter, locals):
+ interpreter.invoke('preWhitespace', whitespace=self.first)
-class LineBufferedFilter(BufferedFilter):
- """A line-buffered filter only lets data through when it sees
- whole lines."""
+class PrefixToken(LiteralToken):
- def __init__(self):
- BufferedFilter.__init__(self)
+ """A prefix markup: ``@@``"""
- def write(self, data):
- BufferedFilter.write(self, data)
- chunks = self.buffer.split('\n')
- for chunk in chunks[:-1]:
- self.sink.write(chunk + '\n')
- self.buffer = chunks[-1]
+ first = None # prefix
-class MaximallyBufferedFilter(BufferedFilter):
+ def string(self):
+ return self.config.prefix * 2
- """A maximally-buffered filter only lets its data through on the final
- close. It ignores flushes."""
+ def run(self, interpreter, locals):
+ if interpreter.invoke('prePrefix'):
+ return
+ interpreter.write(self.config.prefix)
- def __init__(self):
- BufferedFilter.__init__(self)
- def flush(self): pass
+class StringToken(LiteralToken):
- def close(self):
- if self.buffer:
- BufferedFilter.flush(self)
- self.sink.close()
+ """A string token markup: ``@'...'``, ``@'''...'''``, ``@"..."``,
+ ``@\"\"\"...\"\"\"``"""
+
+ first = QUOTE_CHARS
+
+ def scan(self, scanner):
+ scanner.retreat()
+ assert scanner[0] == self.first, (scanner[0], self.first)
+ i = scanner.quote()
+ self.literal = scanner.chop(i)
+ def string(self):
+ return '%s%s' % (self.config.prefix, self.literal)
-class Context:
-
- """An interpreter context, which encapsulates a name, an input
- file object, and a parser object."""
+ def run(self, interpreter, locals):
+ if interpreter.invoke('preString', string=self.literal):
+ return
+ interpreter.literal(self.literal, locals)
+ interpreter.invoke('postString')
- DEFAULT_UNIT = 'lines'
- def __init__(self, name, line=0, units=DEFAULT_UNIT):
- self.name = name
- self.line = line
- self.units = units
- self.pause = False
+class BackquoteToken(LiteralToken):
- def bump(self, quantity=1):
- if self.pause:
- self.pause = False
- else:
- self.line += quantity
+ """A backquote markup: ``@`...```"""
- def identify(self):
- return self.name, self.line
+ first = BACKQUOTE_CHAR
- def __str__(self):
- if self.units == self.DEFAULT_UNIT:
- return "%s:%s" % (self.name, self.line)
+ def scan(self, scanner):
+ # Find the run of starting characters to match.
+ self.count = 1
+ start = scanner.last(self.first)
+ self.count += start
+ scanner.advance(start)
+ # Then match them with the same number of closing characters.
+ loc = scanner.find(self.first * self.count)
+ if loc >= 0:
+ self.literal = scanner.chop(loc, self.count)
else:
- return "%s:%s[%s]" % (self.name, self.line, self.units)
+ raise TransientParseError("backquote markup expects %d backquotes" % self.count)
+ def string(self):
+ return '%s%s%s%s' % (
+ self.config.prefix,
+ self.first * self.count,
+ self.literal,
+ self.first * self.count)
-class Hook:
+ def run(self, interpreter, locals):
+ if interpreter.invoke('preBackquote', literal=self.literal):
+ return
+ interpreter.write(self.literal)
+ interpreter.invoke('postBackquote', result=self.literal)
- """The base class for implementing hooks."""
- def __init__(self):
- self.interpreter = None
+class ExecutionToken(ExpansionToken):
- def register(self, interpreter):
- self.interpreter = interpreter
+ """The abstract base class for execution tokens (expressions,
+ statements, controls, etc.)"""
- def deregister(self, interpreter):
- if interpreter is not self.interpreter:
- raise Error("hook not associated with this interpreter")
- self.interpreter = None
+ pass
- def push(self):
- self.interpreter.push()
- def pop(self):
- self.interpreter.pop()
+class ExpressionToken(ExecutionToken):
- def null(self): pass
+ """An expression markup: ``@(...)``"""
- def atStartup(self): pass
- def atReady(self): pass
- def atFinalize(self): pass
- def atShutdown(self): pass
- def atParse(self, scanner, locals): pass
- def atToken(self, token): pass
- def atHandle(self, meta): pass
- def atInteract(self): pass
+ first = OPEN_PARENTHESIS_CHAR
+ last = ENDING_CHAR_MAP[first]
- def beforeInclude(self, name, file, locals): pass
- def afterInclude(self): pass
+ def scan(self, scanner):
+ start = 0
+ end = scanner.complex(self.first, self.last)
+ try:
+ except_ = scanner.next('$', start, end, True)
+ except ParseError:
+ except_ = end
+ # Build up a list of relevant indices (separating start/if/then/else
+ # clauses)
+ indices = [start - 1] # start, if, then, [if, then]..., [else]
+ while True:
+ try:
+ first = scanner.next('?', start, except_, True)
+ indices.append(first)
+ try:
+ last = scanner.next('!', first, except_, True)
+ indices.append(last)
+ except ParseError:
+ last = except_
+ break
+ except ParseError:
+ first = last = except_
+ break
+ start = last + 1
+ indices.append(except_)
+ code = scanner.chop(end, 1)
+ # Now build up the ifThenCodes pair chain.
+ self.ifThenCodes = []
+ prev = None
+ pair = None
+ for index in indices:
+ if prev is not None:
+ # pair can either be None or a 2-list, possibly with None as
+ # the second element.
+ if pair is None:
+ pair = [code[prev + 1:index], None]
+ else:
+ pair[1] = code[prev + 1:index]
+ self.ifThenCodes.append(pair)
+ pair = None
+ prev = index
+ # If there's a half-constructed pair not yet added to the chain, add it
+ # now.
+ if pair is not None:
+ self.ifThenCodes.append(pair)
+ self.exceptCode = code[except_ + 1:end]
- def beforeExpand(self, string, locals): pass
- def afterExpand(self, result): pass
+ def string(self):
+ fragments = []
+ sep = None
+ for ifCode, thenCode in self.ifThenCodes:
+ if sep:
+ fragments.append(sep)
+ fragments.append(ifCode)
+ if thenCode is not None:
+ fragments.append('?')
+ fragments.append(thenCode)
+ sep = '!'
+ if self.exceptCode:
+ fragments.append('$' + self.exceptCode)
+ return '%s%s%s%s' % (
+ self.config.prefix, self.first,
+ ''.join(fragments), self.last)
- def beforeFile(self, name, file, locals): pass
- def afterFile(self): pass
+ def run(self, interpreter, locals):
+ # ifThenCodes is a list of 2-lists. A list of one sublist whose second
+ # subelement is None is a simple expression to evaluate; no
+ # if-then-else logic. A list of more than one sublist is a chained
+ # if-then-if-then-...-else clause with each sublist containing an if
+ # and a then subelement. If the second subelement is None, then the
+ # first element is not an if but an else.
+ if interpreter.invoke('preExpression', pairs=self.ifThenCodes,
+ except_=self.exceptCode, locals=locals):
+ return
+ result = None
+ try:
+ for ifCode, thenCode in self.ifThenCodes:
+ # An if or an else clause; evaluate it.
+ result = interpreter.evaluate(ifCode, locals)
+ if thenCode is None:
+ # If there's no then clause, then this is an isolated if or
+ # a final else, so we're done.
+ break
+ else:
+ if result:
+ # With a then clause with a true if clause, evaluate
+ # it.
+ result = interpreter.evaluate(thenCode, locals)
+ # If it's true, we're done.
+ if result:
+ break
+ else:
+ # Otherwise, go again. If there no remaining pairs,
+ # return None (no expansion).
+ result = None
+ except self.config.fallThroughErrors:
+ # Don't catch these errors; let them fall through.
+ raise
+ except:
+ if self.exceptCode:
+ result = interpreter.evaluate(self.exceptCode, locals)
+ else:
+ raise
+ interpreter.serialize(result)
+ interpreter.invoke('postExpression', result=result)
- def beforeBinary(self, name, file, chunkSize, locals): pass
- def afterBinary(self): pass
- def beforeString(self, name, string, locals): pass
- def afterString(self): pass
+class SimpleExpressionToken(ExecutionToken):
- def beforeQuote(self, string): pass
- def afterQuote(self, result): pass
+ """A simple expression markup: ``@x``, ``@x.y``, ``@x(y)``, ``@x[y]``,
+ ``@f{...}``"""
- def beforeEscape(self, string, more): pass
- def afterEscape(self, result): pass
+ first = '<identifier>'
- def beforeControl(self, type, rest, locals): pass
- def afterControl(self): pass
+ def scan(self, scanner):
+ i = scanner.simple()
+ self.code = self.first + scanner.chop(i)
+ # Now scan ahead for functional expressions.
+ self.subtokens = []
+ scanner.acquire()
+ try:
+ while True:
+ if not scanner:
+ raise TransientParseError("need more context for end of simple expression")
+ if scanner[0] != '{':
+ break
+ scanner.chop(1)
+ self.subtokens.append([])
+ level = 0
+ while True:
+ peek = scanner.read()
+ if peek == '{':
+ level += 1
+ scanner.chop(1)
+ current = self.config.renderContext(scanner.context)
+ scanner.currents.replace(current)
+ self.subtokens[-1].append(TextToken(current, '{'))
+ elif peek == '}':
+ level -= 1
+ scanner.chop(1)
+ if level < 0:
+ break
+ current = self.config.renderContext(scanner.context)
+ scanner.currents.replace(current)
+ self.subtokens[-1].append(TextToken(current, '}'))
+ token = scanner.one('{}')
+ self.subtokens[-1].append(token)
+ finally:
+ scanner.release()
- def beforeSignificate(self, key, value, locals): pass
- def afterSignificate(self): pass
+ def string(self):
+ results = ['%s%s' % (self.config.prefix, self.code)]
+ for tokens in self.subtokens:
+ results.append('{%s}' % ''.join(map(str, tokens)))
+ return ''.join(results)
- def beforeAtomic(self, name, value, locals): pass
- def afterAtomic(self): pass
+ def run(self, interpreter, locals):
+ if interpreter.invoke('preSimple', code=self.code,
+ subtokens=self.subtokens, locals=locals):
+ return
+ result = None
+ if self.subtokens:
+ result = interpreter.functional(self.code, self.subtokens, locals)
+ else:
+ result = interpreter.evaluate(self.code, locals)
+ interpreter.serialize(result)
+ interpreter.invoke('postSimple', result=result)
- def beforeMulti(self, name, values, locals): pass
- def afterMulti(self): pass
- def beforeImport(self, name, locals): pass
- def afterImport(self): pass
+class InPlaceToken(ExecutionToken):
- def beforeClause(self, catch, locals): pass
- def afterClause(self, exception, variable): pass
+ """An in-place markup: ``@$...$...$``"""
- def beforeSerialize(self, expression, locals): pass
- def afterSerialize(self): pass
+ first = DOLLAR_CHAR
- def beforeDefined(self, name, locals): pass
- def afterDefined(self, result): pass
+ def scan(self, scanner):
+ i = scanner.next(self.first)
+ j = scanner.next(self.first, i + 1)
+ self.code = scanner.chop(i, j - i + 1)
- def beforeLiteral(self, text): pass
- def afterLiteral(self): pass
+ def string(self):
+ return '%s%s%s%s%s' % (
+ self.config.prefix, self.first, self.code, self.first, self.first)
- def beforeEvaluate(self, expression, locals): pass
- def afterEvaluate(self, result): pass
+ def run(self, interpreter, locals):
+ if interpreter.invoke('preInPlace', code=self.code, locals=locals):
+ return
+ result = None
+ interpreter.write("%s%s%s%s" % (
+ self.config.prefix, self.first,
+ self.code, self.first))
+ try:
+ result = interpreter.evaluate(self.code, locals)
+ interpreter.serialize(result)
+ finally:
+ interpreter.write(self.first)
+ interpreter.invoke('postInPlace', result=result)
- def beforeExecute(self, statements, locals): pass
- def afterExecute(self): pass
- def beforeSingle(self, source, locals): pass
- def afterSingle(self): pass
+class StatementToken(ExecutionToken):
-class VerboseHook(Hook):
+ """A statement markup: ``@{...}``"""
- """A verbose hook that reports all information received by the
- hook interface. This class dynamically scans the Hook base class
- to ensure that all hook methods are properly represented."""
+ first = OPEN_BRACE_CHAR
+ last = ENDING_CHAR_MAP[first]
- EXEMPT_ATTRIBUTES = ['register', 'deregister', 'push', 'pop']
+ def scan(self, scanner):
+ i = scanner.complex(self.first, self.last)
+ self.code = scanner.chop(i, 1)
- def __init__(self, output=sys.stderr):
- Hook.__init__(self)
- self.output = output
- self.indent = 0
+ def string(self):
+ return '%s%s%s%s' % (
+ self.config.prefix, self.first, self.code, self.last)
- class FakeMethod:
- """This is a proxy method-like object."""
- def __init__(self, hook, name):
- self.hook = hook
- self.name = name
+ def run(self, interpreter, locals):
+ if interpreter.invoke('preStatement', code=self.code, locals=locals):
+ return
+ interpreter.execute(self.code, locals)
+ interpreter.invoke('postStatement')
- def __call__(self, **keywords):
- self.hook.output.write("%s%s: %s\n" %
- (' ' * self.hook.indent,
- self.name, repr(keywords)))
- for attribute in dir(Hook):
- if (attribute[:1] != '_' and
- attribute not in self.EXEMPT_ATTRIBUTES):
- self.__dict__[attribute] = FakeMethod(self, attribute)
-
+class ControlToken(ExecutionToken):
-class Token:
+ """A control markup: ``@[...]``"""
- """An element of expansion."""
+ first = OPEN_BRACKET_CHAR
+ last = ENDING_CHAR_MAP[first]
- def run(self, interpreter, locals):
- raise NotImplementedError
+ class Chain(Root):
- def string(self):
- raise NotImplementedError
+ """A chain of tokens with a starting token and the rest
+ that follow."""
- def __str__(self): return self.string()
+ def __init__(self, head, tail):
+ self.head = head
+ self.tail = tail
-class NullToken(Token):
- """A chunk of data not containing markups."""
- def __init__(self, data):
- self.data = data
+ def __str__(self):
+ return '(%s, %s)' % (self.head, self.tail)
- def run(self, interpreter, locals):
- interpreter.write(self.data)
+ def getType(self):
+ return self.head.type
- def string(self):
- return self.data
+ def hasType(self, name):
+ return self.head.type == name
-class ExpansionToken(Token):
- """A token that involves an expansion."""
- def __init__(self, prefix, first):
- self.prefix = prefix
- self.first = first
+ PRIMARY = ['if', 'for', 'while', 'dowhile', 'try', 'with', 'defined', 'def']
+ SECONDARY = ['elif', 'else', 'except', 'finally']
+ TERTIARY = ['continue', 'break']
+ GREEDY = [
+ 'if', 'elif', 'for', 'while', 'dowhile', 'with', 'defined', 'def', 'end'
+ ]
+ CLEAN = ['try', 'else', 'except', 'finally', 'continue', 'break', 'end']
+ END = ['end']
+
+ ALLOWED = {
+ 'if': ['elif', 'else'],
+ 'for': ['else'],
+ 'while': ['else'],
+ 'dowhile': ['else'],
+ 'try': ['except', 'else', 'finally'],
+ 'with': [],
+ 'defined': ['else'],
+ 'def': None,
+ 'continue': None,
+ 'break': None,
+ }
- def scan(self, scanner):
- pass
+ IN_RE = re.compile(r"\bin\b")
+ AS_RE = re.compile(r"\bas\b")
- def run(self, interpreter, locals):
- pass
+ runPrefix = 'run_'
-class WhitespaceToken(ExpansionToken):
- """A whitespace markup."""
- def string(self):
- return '%s%s' % (self.prefix, self.first)
+ def scan(self, scanner):
+ scanner.acquire()
+ try:
+ i = scanner.complex(self.first, self.last)
+ self.contents = scanner.chop(i, 1)
+ fields = self.contents.strip().split(None, 1)
+ if len(fields) > 1:
+ self.type, self.rest = fields
+ # If this is a "clean" control, remove anything that looks like
+ # a comment.
+ if self.type in self.CLEAN and '#' in self.rest:
+ self.rest = self.rest.split('#', 1)[0].strip()
+ else:
+ self.type = fields[0]
+ self.rest = None
+ self.subtokens = []
+ if self.type in self.GREEDY and self.rest is None:
+ raise ParseError("control '%s' needs arguments" % self.type)
+ if self.type in self.PRIMARY:
+ self.subscan(scanner, self.type)
+ self.kind = 'primary'
+ elif self.type in self.SECONDARY:
+ self.kind = 'secondary'
+ elif self.type in self.TERTIARY:
+ self.kind = 'tertiary'
+ elif self.type in self.END:
+ self.kind = 'end'
+ else:
+ raise ParseError("unknown control markup: '%s'" % self.type)
+ finally:
+ scanner.release()
-class LiteralToken(ExpansionToken):
- """A literal markup."""
- def run(self, interpreter, locals):
- interpreter.write(self.first)
+ def subscan(self, scanner, primary):
+ """Do a subscan for contained tokens."""
+ while True:
+ token = scanner.one()
+ if token is None:
+ raise TransientParseError("control '%s' needs more tokens" % primary)
+ if isinstance(token, ControlToken) and token.type in self.END:
+ if token.rest != primary:
+ raise ParseError("control must end with 'end %s'" % primary)
+ break
+ self.subtokens.append(token)
- def string(self):
- return '%s%s' % (self.prefix, self.first)
+ def build(self, allowed):
+ """Process the list of subtokens and divide it up into a list
+ of chains, returning that list. Allowed specifies a list of
+ the only secondary markup types which are allowed."""
+ result = []
+ current = []
+ result.append(self.Chain(self, current))
+ for subtoken in self.subtokens:
+ if (isinstance(subtoken, ControlToken) and
+ subtoken.kind == 'secondary'):
+ if subtoken.type not in allowed:
+ raise ParseError("control unexpected secondary: '%s'" % subtoken.type)
+ current = []
+ result.append(self.Chain(subtoken, current))
+ else:
+ current.append(subtoken)
+ return result
-class PrefixToken(ExpansionToken):
- """A prefix markup."""
- def run(self, interpreter, locals):
- interpreter.write(interpreter.prefix)
+ def subrun(self, tokens, interpreter, locals):
+ """Execute a list of tokens."""
+ interpreter.runSeveral(tokens, locals)
- def string(self):
- return self.prefix * 2
-
-class CommentToken(ExpansionToken):
- """A comment markup."""
- def scan(self, scanner):
- loc = scanner.find('\n')
- if loc >= 0:
- self.comment = scanner.chop(loc, 1)
- else:
- raise TransientParseError("comment expects newline")
+ def substring(self):
+ return ''.join([toString(x) for x in self.subtokens])
def string(self):
- return '%s#%s\n' % (self.prefix, self.comment)
-
-class ContextNameToken(ExpansionToken):
- """A context name change markup."""
- def scan(self, scanner):
- loc = scanner.find('\n')
- if loc >= 0:
- self.name = scanner.chop(loc, 1).strip()
+ if self.kind == 'primary':
+ return ('%s[%s]%s%s[end %s]' %
+ (self.config.prefix, self.contents, self.substring(),
+ self.config.prefix, self.type))
else:
- raise TransientParseError("context name expects newline")
+ return '%s[%s]' % (self.config.prefix, self.contents)
def run(self, interpreter, locals):
- context = interpreter.context()
- context.name = self.name
-
-class ContextLineToken(ExpansionToken):
- """A context line change markup."""
- def scan(self, scanner):
- loc = scanner.find('\n')
- if loc >= 0:
+ if interpreter.invoke('preControl', type=self.type,
+ rest=self.rest, locals=locals):
+ return
+ try:
+ allowed = self.ALLOWED[self.type]
+ except KeyError:
+ raise ParseError("control '%s' cannot be at this level" % self.type)
+ if allowed is not None:
+ chains = self.build(allowed)
+ else:
+ chains = None
+ try:
+ method = getattr(self, self.runPrefix + self.type)
+ except AttributeError:
+ raise ConsistencyError("unknown handler for control type '%s'" % self.type)
+ method(chains, interpreter, locals)
+ interpreter.invoke('postControl')
+
+ # Type handlers.
+
+ def run_if(self, chains, interpreter, locals):
+ # @[if E]...@[end if]
+ # @[if E]...@[else]...@[end if]
+ # @[if E]...@[elif E2]...@[end if]
+ # @[if E]...@[elif E2]...@[else]...@[end if]
+ # @[if E]...@[elif E2]... ... @[else]...@[end if]
+ if chains[-1].hasType('else'):
+ elseChain = chains.pop()
+ else:
+ elseChain = None
+ first = True
+ for chain in chains:
+ if first:
+ if not chain.hasType('if'):
+ raise ParseError("control 'if' expected: '%s'" % chain.head.type)
+ first = False
+ else:
+ if not chain.hasType('elif'):
+ raise ParseError("control 'elif' expected: '%s'" % chain.head.type)
+ if interpreter.evaluate(chain.head.rest, locals):
+ self.subrun(chain.tail, interpreter, locals)
+ break
+ else:
+ if elseChain:
+ self.subrun(elseChain.tail, interpreter, locals)
+
+ def run_for(self, chains, interpreter, locals):
+ # @[for N in E]...@[end for]
+ # @[for N in E]...@[else]...@[end for]
+ sides = self.IN_RE.split(self.rest, 1)
+ if len(sides) != 2:
+ raise ParseError("control 'for' expected 'for x in ...'")
+ iterator, iterableCode = sides
+ forChain = chains[0]
+ assert forChain.hasType('for')
+ elseChain = None
+ if chains[-1].hasType('else'):
+ elseChain = chains.pop()
+ if len(chains) != 1:
+ raise ParseError("control 'for' expects at most one 'else'")
+ iterable = interpreter.evaluate(iterableCode, locals)
+ for element in iterable:
try:
- self.line = int(scanner.chop(loc, 1))
- except ValueError:
- raise ParseError("context line requires integer")
+ interpreter.assign(iterator, element, locals)
+ self.subrun(forChain.tail, interpreter, locals)
+ except ContinueFlow:
+ continue
+ except BreakFlow:
+ break
else:
- raise TransientParseError("context line expects newline")
+ if elseChain:
+ self.subrun(elseChain.tail, interpreter, locals)
+
+ def run_while(self, chains, interpreter, locals):
+ # @[while E]...@[end while]
+ # @[while E]...@[else]...@[end while]
+ testCode = self.rest
+ whileChain = chains[0]
+ assert whileChain.hasType('while')
+ elseChain = None
+ if chains[-1].hasType('else'):
+ elseChain = chains.pop()
+ if len(chains) != 1:
+ raise ParseError("control 'while' expects at most one 'else'")
+ exitedNormally = False
+ while True:
+ try:
+ if not interpreter.evaluate(testCode, locals):
+ exitedNormally = True
+ break
+ self.subrun(whileChain.tail, interpreter, locals)
+ except ContinueFlow:
+ continue
+ except BreakFlow:
+ break
+ if exitedNormally and elseChain:
+ self.subrun(elseChain.tail, interpreter, locals)
+
+ def run_dowhile(self, chains, interpreter, locals):
+ # @[dowhile E]...@[end dowhile]
+ # @[dowhile E]...@[else]...@[end dowhile]
+ testCode = self.rest
+ doWhileChain = chains[0]
+ assert doWhileChain.hasType('dowhile')
+ elseChain = None
+ if chains[-1].hasType('else'):
+ elseChain = chains.pop()
+ if len(chains) != 1:
+ raise ParseError("control 'dowhile' expects at most one 'else'")
+ exitedNormally = False
+ done = False
+ while True:
+ try:
+ self.subrun(doWhileChain.tail, interpreter, locals)
+ if not interpreter.evaluate(testCode, locals):
+ exitedNormally = True
+ break
+ except ContinueFlow:
+ continue
+ except BreakFlow:
+ break
+ if exitedNormally and elseChain:
+ self.subrun(elseChain.tail, interpreter, locals)
+
+ def run_try(self, chains, interpreter, locals):
+ # @[try]...@[except]...@[end try]
+ # @[try]...@[except C]...@[end try]
+ # @[try]...@[except C as N]...@[end try]
+ # @[try]...@[except C, N]...@[end try]
+ # @[try]...@[except (C1, C2, ...) as N]...@[end try]
+ # @[try]...@[except C1]...@[except C2]...@[end try]
+ # @[try]...@[except C1]...@[except C2]... ... @[end try]
+ # @[try]...@[finally]...@[end try]
+ # @[try]...@[except ...]...@[finally]...@[end try]
+ # @[try]...@[except ...]...@[else]...@[end try]
+ # @[try]...@[except ...]...@[else]...@[finally]...@[end try]
+ if len(chains) == 1:
+ raise ParseError("control 'try' expects at least one 'except' or 'finally'")
+ tryChain = None
+ exceptChains = []
+ elseChain = None
+ finallyChain = None
+ # Process the chains and verify them.
+ for chain in chains:
+ if chain.hasType('try'):
+ if exceptChains or elseChain or finallyChain:
+ raise ParseError("control 'try' must be first")
+ tryChain = chain
+ elif chain.hasType('except'):
+ if elseChain:
+ raise ParseError("control 'try' cannot have 'except' following 'else'")
+ elif finallyChain:
+ raise ParseError("control 'try' cannot have 'except' following 'finally'")
+ exceptChains.append(chain)
+ elif chain.hasType('else'):
+ if not exceptChains:
+ raise ParseError("control 'try' cannot have 'else' with no preceding 'except'")
+ elif elseChain:
+ raise ParseError("control 'try' cannot have more than one 'else'")
+ elif finallyChain:
+ raise ParseError("control 'try' cannot have 'else' following 'finally'")
+ elseChain = chain
+ elif chain.hasType('finally'):
+ if finallyChain:
+ raise ParseError("control 'try' cannot have more than one 'finally'")
+ finallyChain = chain
+ else:
+ assert False, chain
+ try:
+ try:
+ self.subrun(tryChain.tail, interpreter, locals)
+ if elseChain:
+ self.subrun(elseChain.tail, interpreter, locals)
+ except Flow:
+ raise
+ except self.config.baseException:
+ type, error, traceback = sys.exc_info()
+ for chain in exceptChains:
+ exception, variable = interpreter.clause(chain.head.rest)
+ if isinstance(error, exception):
+ if variable is not None:
+ interpreter.assign(variable, error, locals)
+ self.subrun(chain.tail, interpreter, locals)
+ break
+ else:
+ raise
+ finally:
+ if finallyChain:
+ self.subrun(finallyChain.tail, interpreter, locals)
+
+ def run_with(self, chains, interpreter, locals):
+ # @[with E as N]...@[end with]
+ # @[with N]...@[end with]
+ # @[with E]...@[end with]
+ fields = self.AS_RE.split(self.rest, 1)
+ if len(fields) == 1:
+ # One field means either the expression only or the
+ # variable only.
+ field = fields[0].strip()
+ if interpreter.defined(field, locals):
+ expression = None
+ variable = field
+ else:
+ expression = field
+ variable = None
+ else: # len(fields) == 2
+ expression, variable = fields
+ variable = variable.strip()
+ if expression is not None:
+ manager = interpreter.evaluate(expression, locals)
+ resource = manager
+ if variable is not None:
+ interpreter.assign(variable, resource, locals)
+ else:
+ manager = interpreter.lookup(variable, locals)
+ if len(chains) != 1:
+ raise ParseError("control 'with' must be simple")
+ withChain = chains[0]
+ assert withChain.hasType('with')
+ # As per Python's compound statement reference documentation.
+ enter = manager.__enter__
+ exit = manager.__exit__
+ resource = enter()
+ oops = False
+ try:
+ try:
+ self.subrun(withChain.tail, interpreter, locals)
+ except:
+ oops = True
+ if not exit(*sys.exc_info()):
+ raise
+ finally:
+ if not oops:
+ exit(None, None, None)
+
+ def run_defined(self, chains, interpreter, locals):
+ # @[defined N]...@[end defined]
+ # @[defined N]...@[else]...@[end defined]
+ testName = self.rest.strip()
+ if not testName:
+ raise ParseError("control 'defined' expects an argument")
+ definedChain = chains[0]
+ assert definedChain.hasType('defined')
+ if len(chains) > 3:
+ raise ParseError("control 'defined' expects at most one 'else'")
+ if len(chains) == 2:
+ elseChain = chains[1]
+ else:
+ elseChain = None
+ if interpreter.defined(testName, locals):
+ self.subrun(definedChain.tail, interpreter, locals)
+ elif elseChain:
+ self.subrun(elseChain.tail, interpreter, locals)
+
+ def run_def(self, chains, interpreter, locals):
+ # @[def F(...)]...@[end def]
+ assert chains is None
+ signature = self.rest
+ definition = self.substring()
+ code = ('def %s:\n'
+ ' r"""%s"""\n'
+ ' return %s.expand(r"""%s""", locals())\n' %
+ (signature, definition,
+ interpreter.config.pseudomoduleName, definition))
+ interpreter.execute(code, locals)
+
+ def run_continue(self, chains, interpreter, locals):
+ # @[continue]
+ assert chains is None
+ raise ContinueFlow("control 'continue' encountered without loop control")
+
+ def run_break(self, chains, interpreter, locals):
+ # @[break]
+ assert chains is None
+ raise BreakFlow("control 'break' encountered without loop control")
+
+
+class CodedToken(ExpansionToken):
+
+ """The abstract base class for a token that supports codings."""
+
+ def recode(self, result):
+ """Convert a lookup table entry into a string. A
+ result can be a string itself, an integer corresponding to a
+ code point, or a 2-tuple, the first value of which is one of the
+ above (the second is a description)."""
+ assert result is not None
+ # If it's a tuple, then use the first element; the remaining elements
+ # are descriptions..
+ if isinstance(result, tuple):
+ result = result[0]
+ # If it's an int, then it's a character code.
+ if isinstance(result, int):
+ result = chr(result)
+ # If it's a list, then it's a sequence of some the above. Turn them
+ # all into strings and then concatenate them.
+ if isinstance(result, list):
+ fragments = []
+ for elem in result:
+ fragments.append(self.recode(elem))
+ result = ''.join(fragments)
+ return result
- def run(self, interpreter, locals):
- context = interpreter.context()
- context.line = self.line
- context.pause = True
-class EscapeToken(ExpansionToken):
- """An escape markup."""
+class EscapeToken(CodedToken):
+
+ """An escape markup: ``@\\...``"""
+
+ first = BACKSLASH_CHAR
+
def scan(self, scanner):
try:
code = scanner.chop(1)
result = None
- if code in '()[]{}\'\"\\': # literals
+ if code in '()[]{}<>\\\'\"?': # literals
result = code
- elif code == '0': # NUL
- result = '\x00'
- elif code == 'a': # BEL
- result = '\x07'
- elif code == 'b': # BS
- result = '\x08'
- elif code == 'd': # decimal code
+ elif code == '0': # NUL, null
+ result = 0x00
+ elif code == 'a': # BEL, bell
+ result = 0x07
+ elif code == 'b': # BS, backspace
+ result = 0x08
+ elif code == 'B': # freeform binary code
+ binaryCode = scanner.enclosure()
+ result = int(binaryCode, 2)
+ elif code == 'd': # three-digit decimal code
decimalCode = scanner.chop(3)
- result = chr(int(decimalCode, 10))
- elif code == 'e': # ESC
- result = '\x1b'
- elif code == 'f': # FF
- result = '\x0c'
- elif code == 'h': # DEL
- result = '\x7f'
- elif code == 'n': # LF (newline)
- result = '\x0a'
+ result = int(decimalCode, 10)
+ elif code == 'D': # freeform decimal code
+ decimalCode = scanner.enclosure()
+ result = int(decimalCode, 10)
+ elif code == 'e': # ESC, escape
+ result = 0x1b
+ elif code == 'f': # FF, form feed
+ result = 0x0c
+ elif code == 'h': # DEL, delete
+ result = 0x7f
+ elif code == 'k': # ACK, acknowledge
+ result = 0x06
+ elif code == 'K': # NAK, negative acknowledge
+ result = 0x15
+ elif code == 'n': # LF, linefeed; newline
+ result = 0x0a
elif code == 'N': # Unicode character name
- theSubsystem.assertUnicode()
- import unicodedata
- if scanner.chop(1) != '{':
- raise ParseError("Unicode name escape should be \\N{...}")
- i = scanner.find('}')
- name = scanner.chop(i, 1)
+ if unicodedata is None:
+ raise ConfigurationError("unicodedata module not available; cannot use @\\N{...} markup")
+ name = scanner.enclosure()
try:
+ if self.config.replaceNewlines:
+ name = name.replace('\n', ' ')
result = unicodedata.lookup(name)
+ except AttributeError:
+ raise ConfigurationError("unicodedata.lookup function not available; cannot use @\\N{...} markup")
except KeyError:
- raise SubsystemError("unknown Unicode character name: %s" % name)
- elif code == 'o': # octal code
+ raise ParseError("unknown Unicode character name: %s" % name)
+ elif code == 'o': # three-digit octal code
octalCode = scanner.chop(3)
- result = chr(int(octalCode, 8))
- elif code == 'q': # quaternary code
+ result = int(octalCode, 8)
+ elif code == 'O': # freeform octal code
+ octalCode = scanner.enclosure()
+ result = int(octalCode, 8)
+ elif code == 'q': # four-digit quaternary code
quaternaryCode = scanner.chop(4)
- result = chr(int(quaternaryCode, 4))
- elif code == 'r': # CR
- result = '\x0d'
- elif code in 's ': # SP
+ result = int(quaternaryCode, 4)
+ elif code == 'Q': # freeform quaternary code
+ quaternaryCode = scanner.enclosure()
+ result = int(quaternaryCode, 4)
+ elif code == 'r': # CR, carriage return
+ result = 0x0d
+ elif code == 's' or code in WHITESPACE_CHARS: # SP, space
result = ' '
- elif code == 't': # HT
- result = '\x09'
- elif code in 'u': # Unicode 16-bit hex literal
- theSubsystem.assertUnicode()
+ elif code == 'S': # NBSP, no-break space
+ result = 0xa0
+ elif code == 't': # HT, horizontal tab
+ result = 0x09
+ elif code == 'u': # 16-bit (four-digit) hexadecimal Unicode
hexCode = scanner.chop(4)
- result = _unichr(int(hexCode, 16))
- elif code in 'U': # Unicode 32-bit hex literal
- theSubsystem.assertUnicode()
+ result = int(hexCode, 16)
+ elif code == 'U': # 32-bit (eight-digit) hexadecimal Unicode
hexCode = scanner.chop(8)
- result = _unichr(int(hexCode, 16))
- elif code == 'v': # VT
- result = '\x0b'
- elif code == 'x': # hexadecimal code
+ result = int(hexCode, 16)
+ elif code == 'v': # VT, vertical tab
+ result = 0x0b
+ elif code == 'V': # variation selector
+ name = scanner.enclosure()
+ try:
+ selector = int(name)
+ except ValueError:
+ raise ParseError("variation selector must be int: %s" % name)
+ if selector < 1 or selector > 256:
+ raise ParseError("variation selector must be between 1 and 256 inclusive: %d" % selector)
+ if selector <= 16:
+ result = 0xfe00 + selector - 1
+ else:
+ result = 0xe0100 + (selector - 17)
+ elif code == 'w': # variation selector 15; text display
+ result = 0xfe0e
+ elif code == 'W': # variation selector 16; emoji display
+ result = 0xfe0f
+ elif code == 'x': # 8-bit (two-digit) hexadecimal code
hexCode = scanner.chop(2)
- result = chr(int(hexCode, 16))
- elif code == 'z': # EOT
- result = '\x04'
+ result = int(hexCode, 16)
+ elif code == 'X': # freeform hexadecimal code
+ hexCode = scanner.enclosure()
+ result = int(hexCode, 16)
+ elif code == 'y': # SUB, substitution
+ result = 0x1a
+ elif code == 'Y': # RC, replacement character
+ result = 0xfffd
+ elif code == 'z': # EOT, end of transmission
+ result = 0x04
+ elif code == 'Z': # ZWNBSP/BOM, zero-width no-break space/byte order mark
+ result = 0xfeff
+ elif code == ',': # thin space
+ result = 0x2009
elif code == '^': # control character
controlCode = scanner.chop(1).upper()
- if controlCode >= '@' and controlCode <= '`':
- result = chr(ord(controlCode) - ord('@'))
+ if controlCode == '{':
+ if self.config.controls is None:
+ raise ConfigurationError("controls not configured")
+ name = scanner.grab('}')
+ try:
+ result = self.config.controls[name.upper()]
+ except KeyError:
+ raise ParseError("unknown control character name: %s" % name)
+ elif controlCode >= '@' and controlCode <= '`':
+ result = ord(controlCode) - ord('@')
elif controlCode == '?':
- result = '\x7f'
+ result = 0x7f
else:
raise ParseError("invalid escape control code")
else:
- raise ParseError("unrecognized escape code")
- assert result is not None
- self.code = result
+ raise ParseError("unrecognized escape code: %s" % code)
+ self.code = self.recode(result)
except ValueError:
raise ParseError("invalid numeric escape code")
+ def string(self):
+ """Return a general hexadecimal escape sequence rather than
+ the exact one that was input."""
+ return self.config.escaped(ord(self.code),
+ self.config.prefix + self.first)
+
def run(self, interpreter, locals):
+ if interpreter.invoke('preEscape', code=self.code):
+ return
interpreter.write(self.code)
+ interpreter.invoke('postEscape')
- def string(self):
- return '%s\\x%02x' % (self.prefix, ord(self.code))
-class SignificatorToken(ExpansionToken):
- """A significator markup."""
+class DiacriticToken(CodedToken):
+
+ """A diacritic markup: ``@^...``"""
+
+ first = CARET_CHAR
+
def scan(self, scanner):
- loc = scanner.find('\n')
- if loc >= 0:
- line = scanner.chop(loc, 1)
- if not line:
- raise ParseError("significator must have nonblank key")
- if line[0] in ' \t\v\n':
- raise ParseError("no whitespace between % and key")
- # Work around a subtle CPython-Jython difference by stripping
- # the string before splitting it: 'a '.split(None, 1) has two
- # elements in Jython 2.1).
- fields = line.strip().split(None, 1)
- if len(fields) == 2 and fields[1] == '':
- fields.pop()
- self.key = fields[0]
- if len(fields) < 2:
- fields.append(None)
- self.key, self.valueCode = fields
+ if self.config.diacritics is None:
+ raise ConfigurationError("diacritics not configured")
+ character = scanner.chop(1)
+ diacritics = scanner.chop(1)
+ if diacritics == '{':
+ diacritics = scanner.grab('}')
+ combiners = []
+ try:
+ for diacritic in diacritics:
+ combiner = self.config.diacritics[diacritic]
+ combiner = self.recode(combiner)
+ combiners.append(combiner)
+ except KeyError:
+ raise ParseError("unknown diacritical mark: %s" % diacritic)
+ result = character + ''.join(combiners)
+ try:
+ if self.config.normalizationForm:
+ result = unicodedata.normalize(
+ self.config.normalizationForm, result)
+ except AttributeError:
+ raise ConfigurationError("unicodedata.normalize function not available; cannot use normalization form (must be blank or None)")
+ except ValueError:
+ pass
+ self.character = character
+ self.diacritics = diacritics
+ self.code = result
+
+ def string(self):
+ if len(self.diacritics) > 1:
+ return '%s%s%s{%s}' % (
+ self.config.prefix, self.first, self.character, self.diacritics)
else:
- raise TransientParseError("significator expects newline")
+ return '%s%s%s%s' % (
+ self.config.prefix, self.first, self.character, self.diacritics)
def run(self, interpreter, locals):
- value = self.valueCode
- if value is not None:
- value = interpreter.evaluate(value.strip(), locals)
- interpreter.significate(self.key, value)
+ if interpreter.invoke('preDiacritic', code=self.code):
+ return
+ interpreter.write(self.code)
+ interpreter.invoke('postDiacritic')
- def string(self):
- if self.valueCode is None:
- return '%s%%%s\n' % (self.prefix, self.key)
- else:
- return '%s%%%s %s\n' % (self.prefix, self.key, self.valueCode)
-class ExpressionToken(ExpansionToken):
- """An expression markup."""
+class IconToken(CodedToken):
+
+ """An icon markup: ``@|...``"""
+
+ first = STROKE_CHAR
+
def scan(self, scanner):
- z = scanner.complex('(', ')', 0)
- try:
- q = scanner.next('$', 0, z, True)
- except ParseError:
- q = z
- try:
- i = scanner.next('?', 0, q, True)
+ self.config.validateIcons()
+ key = ''
+ while True:
+ key += scanner.chop(1)
try:
- j = scanner.next('!', i, q, True)
- except ParseError:
- try:
- j = scanner.next(':', i, q, True) # DEPRECATED
- except ParseError:
- j = q
- except ParseError:
- i = j = q
- code = scanner.chop(z, 1)
- self.testCode = code[:i]
- self.thenCode = code[i + 1:j]
- self.elseCode = code[j + 1:q]
- self.exceptCode = code[q + 1:z]
+ result = self.config.icons[key]
+ except KeyError:
+ raise ParseError("unknown icon sequence: %s" % key)
+ if result is None:
+ continue
+ else:
+ break
+ self.key = key
+ self.code = self.recode(result)
+
+ def string(self):
+ return '%s%s%s' % (self.config.prefix, self.first, self.key)
def run(self, interpreter, locals):
- try:
- result = interpreter.evaluate(self.testCode, locals)
- if self.thenCode:
- if result:
- result = interpreter.evaluate(self.thenCode, locals)
+ if interpreter.invoke('preIcon', code=self.code):
+ return
+ interpreter.write(self.code)
+ interpreter.invoke('postIcon')
+
+
+class EmojiToken(CodedToken):
+
+ """An emoji markup: ``@:...:``"""
+
+ first = COLON_CHAR
+
+ def scan(self, scanner):
+ i = scanner.next(self.first)
+ self.name = scanner.chop(i, 1)
+ if not self.name:
+ raise ParseError("emoji cannot be blank")
+
+ def string(self):
+ return '%s%s%s%s' % (
+ self.config.prefix, self.first, self.name, self.first)
+
+ def run(self, interpreter, locals):
+ if interpreter.invoke('preEmoji', name=self.name):
+ return
+ if (self.config.emojis is not None and
+ self.name in self.config.emojis):
+ code = self.config.emojis[self.name]
+ else:
+ code = self.config.substituteEmoji(self.name)
+ if code is None:
+ if self.config.emojiNotFoundIsError:
+ raise UnknownEmojiError("emoji not found: %s" % self.name)
else:
- if self.elseCode:
- result = interpreter.evaluate(self.elseCode, locals)
- else:
- result = None
- except SyntaxError:
- # Don't catch syntax errors; let them through.
- raise
- except:
- if self.exceptCode:
- result = interpreter.evaluate(self.exceptCode, locals)
+ code = '%s%s%s' % (self.first, self.name, self.first)
+ code = self.recode(code)
+ interpreter.write(code)
+ interpreter.invoke('postEmoji')
+
+
+class SignificatorToken(ExpansionToken):
+
+ """A significator markup: ``@%... ... NL``, ``@%!... ... NL``,
+ ``@%%... ... %% NL``, ``@%%!... ... %% NL``"""
+
+ first = PERCENT_CHAR
+
+ def ending(self, multiline):
+ if multiline:
+ return (self.first * 2) + NEWLINE_CHAR
+ else:
+ return NEWLINE_CHAR
+
+ def scan(self, scanner):
+ self.multiline = self.stringized = False
+ peek = scanner.read()
+ if peek == self.first:
+ self.multiline = True
+ scanner.advance(1)
+ peek = scanner.read()
+ if peek == '!':
+ self.stringized = True
+ scanner.advance(1)
+ loc = scanner.find(self.ending(self.multiline))
+ if loc >= 0:
+ contents = scanner.chop(loc, len(self.ending(self.multiline)))
+ if not contents:
+ raise ParseError("significator must have nonblank key")
+ contents = contents.strip()
+ # Work around a subtle CPython-Jython difference by stripping the
+ # string before splitting it: 'a '.split(None, 1) has two elements
+ # in Jython 2.1).
+ fields = contents.strip().split(None, 1)
+ self.key = fields[0]
+ if len(fields) > 1:
+ self.value = fields[1].strip()
else:
- raise
- if result is not None:
- interpreter.write(str(result))
+ self.value = ''
+ if not self.value and not self.stringized:
+ self.value = self.config.emptySignificator
+ else:
+ if self.multiline:
+ raise TransientParseError("significator expects %s and then newline" % (self.first * 2))
+ else:
+ raise TransientParseError("significator expects newline")
def string(self):
- result = self.testCode
- if self.thenCode:
- result += '?' + self.thenCode
- if self.elseCode:
- result += '!' + self.elseCode
- if self.exceptCode:
- result += '$' + self.exceptCode
- return '%s(%s)' % (self.prefix, result)
-
-class StringLiteralToken(ExpansionToken):
- """A string token markup."""
- def scan(self, scanner):
- scanner.retreat()
- assert scanner[0] == self.first
- i = scanner.quote()
- self.literal = scanner.chop(i)
+ if self.value is None:
+ return '%s%s%s%s\n' % (
+ self.config.prefix, self.first,
+ ['', '!'][self.stringized],
+ self.key)
+ else:
+ if self.multiline:
+ return '%s%s%s%s %s%s\n' % (
+ self.config.prefix, self.first * 2,
+ ['', '!'][self.stringized],
+ self.key, self.value,
+ self.first * 2)
+ else:
+ return '%s%s%s%s %s\n' % (
+ self.config.prefix, self.first,
+ ['', '!'][self.stringized],
+ self.key, self.value)
def run(self, interpreter, locals):
- interpreter.literal(self.literal)
+ if interpreter.invoke('preSignificator', key=self.key,
+ value=self.value, stringized=self.stringized):
+ return
+ value = self.value
+ if value is not None and not self.stringized:
+ value = interpreter.evaluate(value, locals, replace=False)
+ interpreter.significate(self.key, value, locals)
+ interpreter.invoke('postSignificator')
- def string(self):
- return '%s%s' % (self.prefix, self.literal)
-class SimpleExpressionToken(ExpansionToken):
- """A simple expression markup."""
- def scan(self, scanner):
- i = scanner.simple()
- self.code = self.first + scanner.chop(i)
+class ContextToken(ExpansionToken):
- def run(self, interpreter, locals):
- interpreter.serialize(self.code, locals)
+ """A base class for the context tokens."""
- def string(self):
- return '%s%s' % (self.prefix, self.code)
+ pass
-class ReprToken(ExpansionToken):
- """A repr markup."""
- def scan(self, scanner):
- i = scanner.next('`', 0)
- self.code = scanner.chop(i, 1)
- def run(self, interpreter, locals):
- interpreter.write(repr(interpreter.evaluate(self.code, locals)))
+class ContextNameToken(ContextToken):
+
+ """A context name change markup: ``@?...``"""
+
+ first = QUESTION_CHAR
- def string(self):
- return '%s`%s`' % (self.prefix, self.code)
-
-class InPlaceToken(ExpansionToken):
- """An in-place markup."""
def scan(self, scanner):
- i = scanner.next(':', 0)
- j = scanner.next(':', i + 1)
- self.code = scanner.chop(i, j - i + 1)
+ loc = scanner.find(NEWLINE_CHAR)
+ if loc >= 0:
+ self.name = scanner.chop(loc, 1).strip()
+ else:
+ raise TransientParseError("context name expects newline")
+
+ def string(self):
+ return '%s%s%s\n' % (self.config.prefix, self.first, self.name)
def run(self, interpreter, locals):
- interpreter.write("%s:%s:" % (interpreter.prefix, self.code))
- try:
- interpreter.serialize(self.code, locals)
- finally:
- interpreter.write(":")
+ if interpreter.invoke('preContextName', name=self.name):
+ return
+ context = interpreter.getContext()
+ context.name = self.name
+ interpreter.invoke('postContextName', context=context)
- def string(self):
- return '%s:%s::' % (self.prefix, self.code)
-class StatementToken(ExpansionToken):
- """A statement markup."""
- def scan(self, scanner):
- i = scanner.complex('{', '}', 0)
- self.code = scanner.chop(i, 1)
+class ContextLineToken(ContextToken):
- def run(self, interpreter, locals):
- interpreter.execute(self.code, locals)
+ """A context line change markup: ``@!...``"""
- def string(self):
- return '%s{%s}' % (self.prefix, self.code)
+ first = EXCLAMATION_CHAR
-class CustomToken(ExpansionToken):
- """A custom markup."""
def scan(self, scanner):
- i = scanner.complex('<', '>', 0)
- self.contents = scanner.chop(i, 1)
+ loc = scanner.find(NEWLINE_CHAR)
+ if loc >= 0:
+ try:
+ self.line = int(scanner.chop(loc, 1))
+ except ValueError:
+ raise ParseError("context line requires integer")
+ else:
+ raise TransientParseError("context line expects newline")
+
+ def string(self):
+ return '%s%s%d\n' % (self.config.prefix, self.first, self.line)
def run(self, interpreter, locals):
- interpreter.invokeCallback(self.contents)
+ if interpreter.invoke('preContextLine', line=self.line):
+ return
+ context = interpreter.getContext()
+ context.line = self.line
+ interpreter.invoke('postContextLine', context=context)
- def string(self):
- return '%s<%s>' % (self.prefix, self.contents)
-class ControlToken(ExpansionToken):
+class CustomToken(ExpansionToken):
- """A control token."""
+ """A custom markup: ``@<...>``"""
- PRIMARY_TYPES = ['if', 'for', 'while', 'try', 'def']
- SECONDARY_TYPES = ['elif', 'else', 'except', 'finally']
- TERTIARY_TYPES = ['continue', 'break']
- GREEDY_TYPES = ['if', 'elif', 'for', 'while', 'def', 'end']
- END_TYPES = ['end']
+ first = OPEN_ANGLE_CHAR
+ last = ENDING_CHAR_MAP[first]
- IN_RE = re.compile(r"\bin\b")
-
def scan(self, scanner):
- scanner.acquire()
- i = scanner.complex('[', ']', 0)
- self.contents = scanner.chop(i, 1)
- fields = self.contents.strip().split(' ', 1)
- if len(fields) > 1:
- self.type, self.rest = fields
- else:
- self.type = fields[0]
- self.rest = None
- self.subtokens = []
- if self.type in self.GREEDY_TYPES and self.rest is None:
- raise ParseError("control '%s' needs arguments" % self.type)
- if self.type in self.PRIMARY_TYPES:
- self.subscan(scanner, self.type)
- self.kind = 'primary'
- elif self.type in self.SECONDARY_TYPES:
- self.kind = 'secondary'
- elif self.type in self.TERTIARY_TYPES:
- self.kind = 'tertiary'
- elif self.type in self.END_TYPES:
- self.kind = 'end'
- else:
- raise ParseError("unknown control markup: '%s'" % self.type)
- scanner.release()
-
- def subscan(self, scanner, primary):
- """Do a subscan for contained tokens."""
- while True:
- token = scanner.one()
- if token is None:
- raise TransientParseError("control '%s' needs more tokens" % primary)
- if (isinstance(token, ControlToken) and
- token.type in self.END_TYPES):
- if token.rest != primary:
- raise ParseError("control must end with 'end %s'" % primary)
- break
- self.subtokens.append(token)
+ # Find the run of starting characters to match.
+ self.count = 1
+ start = scanner.last(self.first)
+ self.count += start
+ scanner.advance(start)
+ # Then match them with the same number of closing characters.
+ loc = scanner.find(self.last * self.count)
+ if loc >= 0:
+ self.contents = scanner.chop(loc, self.count)
+ else:
+ raise TransientParseError("custom markup expects %d close angle brackets" % self.count)
- def build(self, allowed=None):
- """Process the list of subtokens and divide it into a list of
- 2-tuples, consisting of the dividing tokens and the list of
- subtokens that follow them. If allowed is specified, it will
- represent the list of the only secondary markup types which
- are allowed."""
- if allowed is None:
- allowed = SECONDARY_TYPES
- result = []
- latest = []
- result.append((self, latest))
- for subtoken in self.subtokens:
- if (isinstance(subtoken, ControlToken) and
- subtoken.kind == 'secondary'):
- if subtoken.type not in allowed:
- raise ParseError("control unexpected secondary: '%s'" % subtoken.type)
- latest = []
- result.append((subtoken, latest))
- else:
- latest.append(subtoken)
- return result
+ def string(self):
+ return '%s%s%s%s' % (
+ self.config.prefix,
+ self.first * self.count,
+ self.contents,
+ self.last * self.count)
def run(self, interpreter, locals):
- interpreter.invoke('beforeControl', type=self.type, rest=self.rest,
- locals=locals)
- if self.type == 'if':
- info = self.build(['elif', 'else'])
- elseTokens = None
- if info[-1][0].type == 'else':
- elseTokens = info.pop()[1]
- for secondary, subtokens in info:
- if secondary.type not in ('if', 'elif'):
- raise ParseError("control 'if' unexpected secondary: '%s'" % secondary.type)
- if interpreter.evaluate(secondary.rest, locals):
- self.subrun(subtokens, interpreter, locals)
- break
- else:
- if elseTokens:
- self.subrun(elseTokens, interpreter, locals)
- elif self.type == 'for':
- sides = self.IN_RE.split(self.rest, 1)
- if len(sides) != 2:
- raise ParseError("control expected 'for x in seq'")
- iterator, sequenceCode = sides
- info = self.build(['else'])
- elseTokens = None
- if info[-1][0].type == 'else':
- elseTokens = info.pop()[1]
- if len(info) != 1:
- raise ParseError("control 'for' expects at most one 'else'")
- sequence = interpreter.evaluate(sequenceCode, locals)
- for element in sequence:
- try:
- interpreter.assign(iterator, element, locals)
- self.subrun(info[0][1], interpreter, locals)
- except ContinueFlow:
- continue
- except BreakFlow:
- break
- else:
- if elseTokens:
- self.subrun(elseTokens, interpreter, locals)
- elif self.type == 'while':
- testCode = self.rest
- info = self.build(['else'])
- elseTokens = None
- if info[-1][0].type == 'else':
- elseTokens = info.pop()[1]
- if len(info) != 1:
- raise ParseError("control 'while' expects at most one 'else'")
- atLeastOnce = False
- while True:
- try:
- if not interpreter.evaluate(testCode, locals):
- break
- atLeastOnce = True
- self.subrun(info[0][1], interpreter, locals)
- except ContinueFlow:
- continue
- except BreakFlow:
- break
- if not atLeastOnce and elseTokens:
- self.subrun(elseTokens, interpreter, locals)
- elif self.type == 'try':
- info = self.build(['except', 'finally'])
- if len(info) == 1:
- raise ParseError("control 'try' needs 'except' or 'finally'")
- type = info[-1][0].type
- if type == 'except':
- for secondary, _tokens in info[1:]:
- if secondary.type != 'except':
- raise ParseError("control 'try' cannot have 'except' and 'finally'")
- else:
- assert type == 'finally'
- if len(info) != 2:
- raise ParseError("control 'try' can only have one 'finally'")
- if type == 'except':
- try:
- self.subrun(info[0][1], interpreter, locals)
- except FlowError:
- raise
- except Exception:
- e = sys.exc_info()[1]
- for secondary, tokens in info[1:]:
- exception, variable = interpreter.clause(secondary.rest)
- if variable is not None:
- interpreter.assign(variable, e)
- if isinstance(e, exception):
- self.subrun(tokens, interpreter, locals)
- break
- else:
- raise
- else:
- try:
- self.subrun(info[0][1], interpreter, locals)
- finally:
- self.subrun(info[1][1], interpreter, locals)
- elif self.type == 'continue':
- raise ContinueFlow("control 'continue' without 'for', 'while'")
- elif self.type == 'break':
- raise BreakFlow("control 'break' without 'for', 'while'")
- elif self.type == 'def':
- signature = self.rest
- definition = self.substring()
- code = ('def %s:\n'
- ' r"""%s"""\n'
- ' return %s.expand(r"""%s""", locals())\n' %
- (signature, definition, interpreter.pseudo, definition))
- interpreter.execute(code, locals)
- elif self.type == 'end':
- raise ParseError("control 'end' requires primary markup")
- else:
- raise ParseError("control '%s' cannot be at this level" % self.type)
- interpreter.invoke('afterControl')
-
- def subrun(self, tokens, interpreter, locals):
- """Execute a sequence of tokens."""
- for token in tokens:
- token.run(interpreter, locals)
+ if interpreter.invoke('preCustom', contents=self.contents):
+ return
+ result = interpreter.invokeCallback(self.contents)
+ interpreter.serialize(result)
+ interpreter.invoke('postCustom', result=result)
+
+
+Configuration.tokens = [
+ LineCommentToken,
+ InlineCommentToken,
+ WhitespaceToken,
+ PrefixToken,
+ StringToken,
+ BackquoteToken,
+ ExpressionToken,
+ SimpleExpressionToken,
+ InPlaceToken,
+ StatementToken,
+ ControlToken,
+ EscapeToken,
+ DiacriticToken,
+ IconToken,
+ EmojiToken,
+ SignificatorToken,
+ ContextNameToken,
+ ContextLineToken,
+ CustomToken,
+]
- def substring(self):
- return ''.join(str(x) for x in self.subtokens)
+#
+# Factory
+#
- def string(self):
- if self.kind == 'primary':
- return ('%s[%s]%s%s[end %s]' %
- (self.prefix, self.contents, self.substring(),
- self.prefix, self.type))
+class Factory(Root):
+
+ """Turn a first character into a token class. Token classes
+ have a first attribute which is either None to indicate
+ whatever the current prefix is; a string in angle brackets to
+ indicate a special test; or a character or characters. Token
+ classes are then retrieved by lookup table, or special test.
+ Initialize this meta-factory with a list of factory classes
+ and it will automatically setup the lookup tables based on
+ their first attributes."""
+
+ warnings = {
+ ')': "; the `@)` markup has been removed; just use `)` instead",
+ ']': "; the `@]` markup has been removed; just use `]` instead",
+ '}': "; the `@}` markup has been removed; just use `}` instead",
+ }
+
+ def __init__(self, factories):
+ self.byChar = {}
+ self.identifier = None
+ self.whitespace = None
+ for factory in factories:
+ first = factory.first
+ if first is None:
+ # A prefix.
+ assert None not in self.byChar
+ self.byChar[None] = factory
+ elif first.startswith('<') and first.endswith('>'):
+ # A special case.
+ if first == '<identifier>':
+ assert self.identifier is None
+ self.identifier = factory
+ elif first == '<whitespace>':
+ assert self.whitespace is None
+ self.whitespace = factory
+ else:
+ raise ConsistencyError("unknown special token case: %s" % first)
+ else:
+ # A character or characters.
+ for char in first:
+ assert char not in self.byChar
+ self.byChar[char] = factory
+ assert self.identifier is not None
+ assert self.whitespace is not None
+
+ def __contains__(self, first):
+ return first in self.byChar
+
+ def __getitem__(self, first):
+ return self.byChar[first]
+
+ def __call__(self, first):
+ if first in self.byChar:
+ return self.byChar[first]
else:
- return '%s[%s]' % (self.prefix, self.contents)
+ if first.isspace():
+ return self.whitespace
+ elif isIdentifier(first):
+ return self.identifier
+ return None
+
+ def adjust(self, config):
+ """Adjust this factory to swap the markup for a non-default
+ prefix, if necessary."""
+ if not config.hasDefaultPrefix() and config.prefix in self:
+ oldFactory = self[config.prefix]
+ self.byChar[config.defaultPrefix] = oldFactory
+ oldFactory._first = oldFactory.first
+ oldFactory.first = None # config.defaultPrefix
+
+ def warn(self, first):
+ """Warn about an unsupported markup sequence (for compatibility
+ or future notes)."""
+ return self.warnings.get(first, '')
+#
+# Scanner
+#
-class Scanner:
+class Scanner(Root):
"""A scanner holds a buffer for lookahead parsing and has the
ability to scan for special symbols and indicators in that
buffer."""
- # This is the token mapping table that maps first characters to
- # token classes.
- TOKEN_MAP = [
- (None, PrefixToken),
- (' \t\v\r\n', WhitespaceToken),
- (')]}', LiteralToken),
- ('\\', EscapeToken),
- ('#', CommentToken),
- ('?', ContextNameToken),
- ('!', ContextLineToken),
- ('%', SignificatorToken),
- ('(', ExpressionToken),
- (IDENTIFIER_FIRST_CHARS, SimpleExpressionToken),
- ('\'\"', StringLiteralToken),
- ('`', ReprToken),
- (':', InPlaceToken),
- ('[', ControlToken),
- ('{', StatementToken),
- ('<', CustomToken),
- ]
-
- def __init__(self, prefix, data=''):
- self.prefix = prefix
+ def __init__(self, config, context, currents, data=''):
+ self.config = config
+ self.context = context
+ self.currents = currents
+ self.head = 0
self.pointer = 0
self.buffer = data
self.lock = 0
+ self.factory = config.getFactory()
- def __nonzero__(self): return self.pointer < len(self.buffer) # 2.x
- def __bool__(self): return self.pointer < len(self.buffer) # 3.x
- def __len__(self): return len(self.buffer) - self.pointer
+ def __bool__(self):
+ return self.head + self.pointer < len(self.buffer) # 3.x
+ def __nonzero__(self):
+ return self.head + self.pointer < len(self.buffer) # 2.x
- def __getitem__(self, index):
- if isinstance(index, slice):
- assert index.step is None or index.step == 1
- return self.__getslice__(index.start, index.stop)
- else:
- return self.buffer[self.pointer + index]
+ def __len__(self): return len(self.buffer) - self.pointer - self.head
+
+ if major >= 3:
+ def __getitem__(self, index):
+ if isinstance(index, slice):
+ assert index.step is None or index.step == 1
+ return self.__getslice__(index.start, index.stop)
+ else:
+ return self.buffer[self.head + self.pointer + index]
+ else:
+ def __getitem__(self, index):
+ return self.buffer[self.head + self.pointer + index]
def __getslice__(self, start, stop):
if start is None:
stop = len(self)
if stop > len(self):
stop = len(self)
- return self.buffer[self.pointer + start:self.pointer + stop]
+ return self.buffer[self.head + self.pointer + start:
+ self.head + self.pointer + stop]
+
+ # Meta.
def advance(self, count=1):
"""Advance the pointer count characters."""
self.pointer += count
def retreat(self, count=1):
- self.pointer = self.pointer - count
+ self.pointer -= count
if self.pointer < 0:
raise ParseError("can't retreat back over synced out chars")
def set(self, data):
"""Start the scanner digesting a new batch of data; start the pointer
over from scratch."""
+ self.head = 0
self.pointer = 0
self.buffer = data
def feed(self, data):
"""Feed some more data to the scanner."""
- self.buffer += data
-
- def chop(self, count=None, slop=0):
- """Chop the first count + slop characters off the front, and return
- the first count. If count is not specified, then return
- everything."""
- if count is None:
- assert slop == 0
- count = len(self)
- if count > len(self):
- raise TransientParseError("not enough data to read")
- result = self[:count]
- self.advance(count + slop)
- return result
+ self.rectify()
+ if self.buffer:
+ self.buffer += data
+ else:
+ self.buffer = data
def acquire(self):
"""Lock the scanner so it doesn't destroy data on sync."""
"""Unlock the scanner."""
self.lock -= 1
+ def track(self):
+ """Accumulate the moved pointer into the context."""
+ if self.pointer > 0:
+ self.context.track(self.buffer,
+ self.head, self.head + self.pointer)
+
+ def accumulate(self):
+ """Update the accumulated context into the actual context."""
+ self.context.accumulate()
+
+ def rectify(self):
+ """Reset the read head and trim down the buffer."""
+ if self.head + self.pointer > 0:
+ self.buffer = self.buffer[self.head + self.pointer:]
+ self.head = 0
+ self.pointer = 0
+
def sync(self):
"""Sync up the buffer with the read head."""
- if self.lock == 0 and self.pointer != 0:
- self.buffer = self.buffer[self.pointer:]
+ if self.lock == 0 and self.pointer > 0:
+ self.track()
+ self.head += self.pointer
self.pointer = 0
def unsync(self):
"""Undo changes; reset the read head."""
- if self.pointer != 0:
- self.lock = 0
+ if self.lock == 0:
self.pointer = 0
def rest(self):
"""Get the remainder of the buffer."""
return self[:]
- def read(self, i=0, count=1):
- """Read count chars starting from i; raise a transient error if
- there aren't enough characters remaining."""
- if len(self) < i + count:
- raise TransientParseError("need more data to read")
+ # Active.
+
+ def chop(self, count=None, slop=0):
+ """Chop the first count + slop characters off the front, and
+ return the first count, advancing the pointer past them. If
+ count is not specified, then return everything."""
+ if count is None:
+ assert slop == 0
+ count = len(self)
+ if count > len(self):
+ raise TransientParseError("not enough data to read")
+ result = self[:count]
+ self.advance(count + slop)
+ return result
+
+ def enclosure(self, begin='{', end='}'):
+ """Consume and return the next enclosure (text wrapped
+ in the given delimiters)."""
+ if self.chop(len(begin)) == begin:
+ name = self.grab(end)
+ return name
else:
- return self[i:i + count]
+ raise ParseError("enclosure must start with %s" % begin)
- def check(self, i, archetype=None):
- """Scan for the next single or triple quote, with the specified
- archetype. Return the found quote or None."""
- quote = None
- if self[i] in '\'\"':
- quote = self[i]
- if len(self) - i < 3:
- for j in range(i, len(self)):
- if self[i] == quote:
- return quote
- else:
- raise TransientParseError("need to scan for rest of quote")
- if self[i + 1] == self[i + 2] == quote:
- quote = quote * 3
- if quote is not None:
- if archetype is None:
- return quote
- else:
- if archetype == quote:
- return quote
- elif len(archetype) < len(quote) and archetype[0] == quote[0]:
- return archetype
- else:
- return None
+ def read(self, start=0, count=1):
+ """Read count chars starting from start; raise a transient
+ error if there aren't enough characters remaining."""
+ if len(self) < start + count:
+ raise TransientParseError("need more data to read")
else:
- return None
+ return self[start:start + count]
def find(self, sub, start=0, end=None):
- """Find the next occurrence of the character, or return -1."""
- if end is not None:
- return self.rest().find(sub, start, end)
- else:
- return self.rest().find(sub, start)
+ """Find the next occurrence of the substring, or return -1."""
+ if end is None:
+ end = len(self)
+ return self.rest().find(sub, start, end)
- def last(self, char, start=0, end=None):
- """Find the first character that is _not_ the specified character."""
+ def trivial(self, sub, start=0, end=None):
+ """Find the first occurrence of the substring where the
+ previous character is _not_ the escape character `\\`)."""
+ head = start
+ while True:
+ i = self.find(sub, head, end)
+ if i == -1:
+ raise TransientParseError("substring not found: %s" % sub)
+ if i > 0 and self[i - 1] == BACKSLASH_CHAR:
+ head = i + len(sub)
+ continue
+ return i
+
+ def last(self, chars, start=0, end=None):
+ """Find the first character that is _not_ one of the specified
+ characters."""
if end is None:
end = len(self)
i = start
while i < end:
- if self[i] != char:
+ if self[i] not in chars:
return i
i += 1
else:
- raise TransientParseError("expecting other than %s" % char)
+ raise TransientParseError("expecting other than %s" % chars)
+
+ def grab(self, sub, start=0, end=None):
+ """Find the next occurrence of the substring and chop the
+ intervening characters, disposing the substring found."""
+ i = self.find(sub, start, end)
+ if i >= 0:
+ return self.chop(i, len(sub))
+ else:
+ raise TransientParseError("delimiter not found: %s" % sub)
def next(self, target, start=0, end=None, mandatory=False):
"""Scan for the next occurrence of one of the characters in
else:
raise TransientParseError("expecting ending character")
+ def check(self, start=0, archetype=None):
+ """Scan for the next single or triple quote, optionally with
+ the specified archetype. Return the found quote or None."""
+ quote = None
+ i = start
+ if len(self) - i <= 1:
+ raise TransientParseError("need to scan for rest of quote")
+ if self[i] in QUOTE_CHARS:
+ quote = self[i]
+ if self[i + 1] == quote:
+ if len(self) - i <= 2:
+ raise TransientParseError("need more context to complete quote")
+ if self[i + 2] == quote:
+ quote *= 3
+ if quote is not None:
+ if archetype is None:
+ return quote
+ else:
+ if archetype == quote:
+ return archetype
+ elif len(archetype) < len(quote) and archetype[0] == quote[0]:
+ return archetype
+ else:
+ return None
+ else:
+ return None
+
def quote(self, start=0, end=None, mandatory=False):
"""Scan for the end of the next quote."""
- assert self[start] in '\'\"'
+ assert self[start] in QUOTE_CHARS
quote = self.check(start)
if end is None:
end = len(self)
raise TransientParseError("expecting end of string literal")
def nested(self, enter, exit, start=0, end=None):
- """Scan from i for an ending sequence, respecting entries and exits
+ """Scan from start for an ending sequence, respecting entries and exits
only."""
depth = 0
if end is None:
else:
raise TransientParseError("expecting end of complex expression")
- def complex(self, enter, exit, start=0, end=None, skip=None):
- """Scan from i for an ending sequence, respecting quotes,
+ def complex(self, enter, exit, comment=OCTOTHORPE_CHAR,
+ start=0, end=None, skip=None):
+ """Scan from start for an ending sequence, respecting quotes,
entries and exits."""
quote = None
depth = 0
if end is None:
end = len(self)
- last = None
+ lastNonQuote = None
+ commented = False
i = start
while i < end:
- newQuote = self.check(i, quote)
- if newQuote:
- if newQuote == quote:
- quote = None
- else:
- quote = newQuote
- i += len(newQuote)
- else:
+ if commented:
c = self[i]
- if quote:
- if c == '\\':
- i += 1
- else:
- if skip is None or last != skip:
- if c == enter:
- depth += 1
- elif c == exit:
- depth -= 1
- if depth < 0:
- return i
- last = c
+ if c == '\n':
+ commented = False
+ elif c == exit:
+ return i
i += 1
+ else:
+ newQuote = self.check(i, quote)
+ if newQuote:
+ if newQuote == quote:
+ quote = None
+ else:
+ quote = newQuote
+ i += len(newQuote)
+ else:
+ c = self[i]
+ if quote:
+ if c == '\\':
+ i += 1
+ else:
+ if skip is None or lastNonQuote != skip:
+ if c == enter:
+ depth += 1
+ elif c == exit:
+ depth -= 1
+ if depth < 0:
+ return i
+ if c == comment and depth == 0:
+ commented = True
+ lastNonQuote = c
+ i += 1
else:
raise TransientParseError("expecting end of complex expression")
- def word(self, start=0):
- """Scan from i for a simple word."""
+ def word(self, start=0, additional='._'):
+ """Scan from start for a simple word."""
length = len(self)
i = start
while i < length:
- if not self[i] in IDENTIFIER_CHARS:
+ if not (self[i].isalnum() or self[i] in additional):
return i
i += 1
else:
raise TransientParseError("expecting end of word")
def phrase(self, start=0):
- """Scan from i for a phrase (e.g., 'word', 'f(a, b, c)', 'a[i]', or
- combinations like 'x[i](a)'."""
+ """Scan from start for a phrase (e.g., 'word', 'f(a, b, c)',
+ 'a[i]', or combinations like 'x[i](a)'."""
# Find the word.
i = self.word(start)
- while i < len(self) and self[i] in '([{':
+ while i < len(self) and self[i] in PHRASE_OPENING_CHARS:
enter = self[i]
- if enter == '{':
- raise ParseError("curly braces can't open simple expressions")
- exit = ENDING_CHARS[enter]
- i = self.complex(enter, exit, i + 1) + 1
+ exit = ENDING_CHAR_MAP[enter]
+ i = self.complex(enter, exit, None, i + 1) + 1
return i
-
+
def simple(self, start=0):
- """Scan from i for a simple expression, which consists of one
- more phrases separated by dots."""
+ """Scan from start for a simple expression, which consists of
+ one more phrases separated by dots. Return a tuple giving the
+ end of the expression and a list of tuple pairs consisting of
+ the simple expression extensions found, if any."""
i = self.phrase(start)
length = len(self)
- while i < length and self[i] == '.':
+ while i < length and self[i] == DOT_CHAR:
i = self.phrase(i)
# Make sure we don't end with a trailing dot.
- while i > 0 and self[i - 1] == '.':
+ while i > 0 and self[i - 1] == DOT_CHAR:
i -= 1
return i
- def one(self):
- """Parse and return one token, or None if the scanner is empty."""
+ def one(self, firebreaks=None):
+ """Parse, scan, and return one token, or None if the scanner
+ is empty. If the firebreaks argument is supplied, chop up
+ text tokens before a character in that string."""
if not self:
return None
- if not self.prefix:
+ if not self.config.prefix:
loc = -1
else:
- loc = self.find(self.prefix)
+ loc = self.find(self.config.prefix)
if loc < 0:
- # If there's no prefix in the buffer, then set the location to
- # the end so the whole thing gets processed.
+ # If there's no prefix in the buffer, then set the location to the
+ # end so the whole thing gets processed.
loc = len(self)
if loc == 0:
# If there's a prefix at the beginning of the buffer, process
# an expansion.
prefix = self.chop(1)
- assert prefix == self.prefix
- first = self.chop(1)
- if first == self.prefix:
- first = None
- for firsts, factory in self.TOKEN_MAP:
- if firsts is None:
- if first is None:
- break
- elif first in firsts:
- break
- else:
- raise ParseError("unknown markup: %s%s" % (self.prefix, first))
- token = factory(self.prefix, first)
+ assert prefix == self.config.prefix
try:
+ first = self.chop(1)
+ if first == self.config.prefix:
+ first = None
+ factory = self.factory(first)
+ if factory is None:
+ raise ParseError("unknown markup sequence: %s%s%s" % (self.config.prefix, first, self.factory.warn(first)))
+ current = self.config.renderContext(self.context)
+ self.currents.replace(current)
+ token = factory(current, self.config, first)
token.scan(self)
except TransientParseError:
# If a transient parse error occurs, reset the buffer pointer
self.unsync()
raise
else:
- # Process everything up to loc as a null token.
+ # Process everything up to loc as a text token, unless there are
+ # intervening firebreaks before loc.
+ if firebreaks:
+ for firebreak in firebreaks:
+ i = self.find(firebreak, 0, loc)
+ if i >= 0 and i < loc:
+ loc = i
data = self.chop(loc)
- token = NullToken(data)
+ current = self.config.renderContext(self.context)
+ self.currents.replace(current)
+ token = TextToken(current, data)
self.sync()
return token
+ def all(self):
+ """Yield a sequence of all tokens."""
+ while True:
+ token = self.one()
+ if token:
+ yield token
+ else:
+ break
+
+#
+# Command ...
+#
+
+class Command(Root):
+
+ """A generic high-level processing command."""
+
+ def __init__(self, noun):
+ self.noun = noun
+
+ def __str__(self):
+ return self.noun
+
+ def cleanup(self):
+ pass
+
+ def process(self, interpreter, n):
+ """Run the command."""
+ raise NotImplementedError
+
+
+class DocumentCommand(Command):
+
+ """Read and execute an EmPy document."""
+
+ def process(self, interpreter, n):
+ name = self.noun
+ method = interpreter.file
+ self.target = interpreter.config.open(self.noun, 'r')
+ result = interpreter.protect(name, method, self.target)
+
+ def cleanup(self):
+ self.target.close()
+
+
+class ImportCommand(Command):
+
+ """Import a Python module."""
+
+ def process(self, interpreter, n):
+ name = '<import:%d>' % n
+ context = interpreter.newContext(name)
+ interpreter.pushContext(context)
+ try:
+ module = __import__(self.noun)
+ interpreter.atomic(self.noun, module)
+ method = interpreter.string
+ target = '%s{import %s}' % (interpreter.config.prefix, self.noun)
+ return name, method, (target,), {}
+ finally:
+ interpreter.popContext()
+
+
+class DefineCommand(Command):
+
+ """Define a Python variable."""
+
+ def process(self, interpreter, n):
+ name = '<define:%d>' % n
+ context = interpreter.newContext(name)
+ interpreter.pushContext(context)
+ try:
+ if '=' in self.noun:
+ interpreter.execute(self.noun)
+ else:
+ interpreter.atomic(self.noun.strip(), None)
+ finally:
+ interpreter.popContext()
+
+
+class StringCommand(Command):
+
+ """Define a Python string variable."""
+
+ def process(self, interpreter, n):
+ method = None
+ if '=' in self.noun:
+ key, value = self.noun.split('=', 1)
+ key = key.strip()
+ value = value.strip()
+ else:
+ key = self.noun.strip()
+ value = ''
+ interpreter.atomic(key, value)
+
+class ExecCommand(Command):
+
+ """Execute a Python statement."""
+
+ def process(self, interpreter, n):
+ name = '<exec:%d>' % n
+ context = interpreter.newContext(name)
+ interpreter.pushContext(context)
+ try:
+ interpreter.execute(self.noun)
+ finally:
+ interpreter.popContext()
+
+
+class FileCommand(Command):
+
+ """Load an execute a Python file."""
+
+ def process(self, interpreter, n):
+ name = '<file:%d>' % n
+ context = interpreter.newContext(name)
+ interpreter.pushContext(context)
+ try:
+ file = interpreter.config.open(self.noun, 'r')
+ try:
+ data = file.read()
+ finally:
+ file.close()
+ interpreter.execute(data)
+ finally:
+ interpreter.popContext()
+
+
+#
+# Interpreter
+#
+
+class Interpreter(Root):
-class Interpreter:
-
"""An interpreter can process chunks of EmPy code."""
+ # Compatibility.
+
+ version = __version__
+ compat = compat
+
# Constants.
- VERSION = __version__
- SIGNIFICATOR_RE_SUFFIX = SIGNIFICATOR_RE_SUFFIX
- SIGNIFICATOR_RE_STRING = None
+ ASSIGN_TOKEN_RE = re.compile(r"[_a-zA-Z][_a-zA-Z0-9]*|\(|\)|,")
+ AS_RE = re.compile(r"\bas\b")
- # Types.
+ # Statics.
- Interpreter = None # define this below to prevent a circular reference
- Hook = Hook # DEPRECATED
- Filter = Filter # DEPRECATED
- NullFilter = NullFilter # DEPRECATED
- FunctionFilter = FunctionFilter # DEPRECATED
- StringFilter = StringFilter # DEPRECATED
- BufferedFilter = BufferedFilter # DEPRECATED
- SizeBufferedFilter = SizeBufferedFilter # DEPRECATED
- LineBufferedFilter = LineBufferedFilter # DEPRECATED
- MaximallyBufferedFilter = MaximallyBufferedFilter # DEPRECATED
+ _proxy = None # the installed proxy or None
- # Tables.
+ # Construction, initialization, destruction.
- ESCAPE_CODES = {0x00: '0', 0x07: 'a', 0x08: 'b', 0x1b: 'e', 0x0c: 'f',
- 0x7f: 'h', 0x0a: 'n', 0x0d: 'r', 0x09: 't', 0x0b: 'v',
- 0x04: 'z'}
+ def __init__(self, **kwargs):
+ """Accept keyword arguments only, so users will never have to
+ worry about the ordering of arguments."""
+ def extract(dict, key, default=None):
+ if key in dict:
+ value = dict.get(key)
+ del dict[key]
+ else:
+ value = default
+ return value
+ self.ok = None # is the interpreter initialized?
+ args = (
+ extract(kwargs, 'ident', None),
+ extract(kwargs, 'config', None),
+ extract(kwargs, 'globals', None),
+ extract(kwargs, 'output', None),
+ extract(kwargs, 'executable', '?'),
+ extract(kwargs, 'argv', None),
+ extract(kwargs, 'filespec', None),
+ extract(kwargs, 'hooks', None),
+ extract(kwargs, 'filters', None),
+ extract(kwargs, 'callback', None),
+ extract(kwargs, 'dispatcher', True),
+ extract(kwargs, 'handler', None),
+ extract(kwargs, 'evalFunc', eval),
+ extract(kwargs, 'execFunc', execFunc),
+ extract(kwargs, 'serializerFunc', toString),
+ extract(kwargs, 'input', sys.stdin),
+ extract(kwargs, 'root', None),
+ extract(kwargs, 'immediately', True),
+ )
+ if kwargs:
+ # Any remaining keyword arguments are a mistake: either simple
+ # typos, or an old-style specification of local variables in an
+ # `expand` call.
+ keys = list(kwargs.keys())
+ keys.sort()
+ raise CompatibilityError("unrecognized Interpreter constructor keyword arguments; when calling expand, use locals dictionary instead of keywords: %s" % keys, keys=keys)
+ self.initialize(*args)
- ASSIGN_TOKEN_RE = re.compile(r"[_a-zA-Z][_a-zA-Z0-9]*|\(|\)|,")
+ def __del__(self):
+ self.shutdown()
- DEFAULT_OPTIONS = {BANGPATH_OPT: True,
- BUFFERED_OPT: False,
- RAW_OPT: False,
- EXIT_OPT: True,
- FLATTEN_OPT: False,
- OVERRIDE_OPT: True,
- CALLBACK_OPT: False}
+ def __repr__(self):
+ if self.ident is None:
+ return '<%s pseudomodule/interpreter object @ 0x%x>' % (
+ self.config.pseudomoduleName, id(self))
+ else:
+ return '<%s pseudomodule/interpreter object "%s" @ 0x%x>' % (
+ self.config.pseudomoduleName, self.ident, id(self))
- _wasProxyInstalled = False # was a proxy installed?
+ def __bool__(self): return self.ok # 3.x
+ def __nonzero__(self): return self.ok # 2.x
- # Construction, initialization, destruction.
+ def __enter__(self):
+ self.check()
+ return self
- def __init__(self, output=None, argv=None, prefix=DEFAULT_PREFIX,
- pseudo=None, options=None, globals=None, hooks=None):
- self.interpreter = self # DEPRECATED
- # Set up the stream.
- if output is None:
- output = UncloseableFile(sys.__stdout__)
- self.output = output
- self.prefix = prefix
- if pseudo is None:
- pseudo = DEFAULT_PSEUDOMODULE_NAME
- self.pseudo = pseudo
+ def __exit__(self, *exc):
+ self.shutdown()
+
+ def initialize(self, ident=None, config=None, globals=None, output=None,
+ executable=None, argv=None, filespec=None,
+ hooks=None, filters=None, callback=None,
+ dispatcher=True, handler=None,
+ evalFunc=evalFunc, execFunc=execFunc, serializerFunc=toString,
+ input=sys.stdin, root=None, immediately=True):
+ """Initialize the interpreter with the given arguments (all of
+ which have defaults). The number and order of arguments here
+ is subject to change."""
+ self.ident = ident
+ self.error = None # last error that occurred or None
+ # Set up the configuration.
+ if config is None:
+ config = Configuration()
+ self.config = config
+ self.filespec = filespec
+ self.globals = globals
+ # Handle the executable and arguments.
+ self.executable = executable
if argv is None:
- argv = [DEFAULT_SCRIPT_NAME]
+ argv = [None]
+ if argv[0] is None:
+ argv[0] = config.unknownScriptName
self.argv = argv
- self.args = argv[1:]
- if options is None:
- options = {}
- self.options = options
- # Initialize any hooks.
- self.hooksEnabled = None # special sentinel meaning "false until added"
- self.hooks = []
+ # The interpreter stacks.
+ self.contexts = Stack()
+ self.streams = Stack()
+ self.currents = Stack()
+ # Initialize hooks.
if hooks is None:
hooks = []
+ self.hooks = []
+ self.hooksEnabled = None
for hook in hooks:
- self.register(hook)
+ self.addHook(hook)
# Initialize callback.
- self.callback = None
+ self.callback = callback
+ # Initialize dispatcher.
+ if dispatcher is True:
+ dispatcher = self.dispatch
+ elif dispatcher is False:
+ dispatcher = self.reraise
+ elif dispatcher is None:
+ raise ConfigurationError("dispatcher cannot be None")
+ self.dispatcher = dispatcher
+ # Initialize handler.
+ self.handler = None
+ if handler is not None:
+ self.setHandler(handler)
+ # Install a proxy stdout if one hasn't been already..
+ self.output = self.installProxy(output)
+ # Setup the execution environment.
+ self.evalFunc = evalFunc
+ self.execFunc = execFunc
+ self.serializerFunc = serializerFunc
+ self.input = input
+ # Setup the root context.
+ if root is None:
+ root = self.config.defaultRoot
+ self.root = root
+ # Now declare that we've started up.
+ self.ok = True
+ self.invoke('atStartup')
+ # Reset the state.
+ self.reset(True)
+ # Initialize filters (need to be done after stacks are up).
+ if filters:
+ self.setFilterChain(filters)
+ # Declare the interpreter ready.
+ if immediately:
+ self.ready()
+
+ def reset(self, clearStacks=False):
+ """Completely reset the interpreter state. If clearStacks is
+ true, wipe the call stacks. If immediately is true, declare
+ the interpreter ready."""
+ self.ok = False
+ self.error = None
+ # None is a special sentinel meaning "false until added."
+ self.hooksEnabled = len(self.hooks) > 0 and True or None
+ # Set up a diversions dictionary.
+ self.diversions = {}
+ # Significators.
+ self.significators = {}
# Finalizers.
self.finals = []
- # The interpreter stacks.
- self.contexts = Stack()
- self.streams = Stack()
# Now set up the globals.
- self.globals = globals
- self.fix()
- self.history = Stack()
- # Install a proxy stdout if one hasn't been already.
- self.installProxy()
- # Finally, reset the state of all the stacks.
- self.reset()
- # Okay, now flatten the namespaces if that option has been set.
- if self.options.get(FLATTEN_OPT, False):
- self.flatten()
- # Set up old pseudomodule attributes.
- if prefix is None:
- self.SIGNIFICATOR_RE_STRING = None
- else:
- self.SIGNIFICATOR_RE_STRING = prefix + self.SIGNIFICATOR_RE_SUFFIX
- self.Interpreter = self.__class__
+ self.fixGlobals()
+ self.globalsHistory = Stack()
+ # Now, clear the state of all the stacks.
+ if clearStacks:
+ self.clear()
+ self.current = None
# Done. Now declare that we've started up.
- self.invoke('atStartup')
-
- def __del__(self):
- self.shutdown()
-
- def __repr__(self):
- return ('<%s pseudomodule/interpreter at 0x%x>' %
- (self.pseudo, id(self)))
+ self.ok = True
def ready(self):
"""Declare the interpreter ready for normal operations."""
self.invoke('atReady')
- def fix(self):
- """Reset the globals, stamping in the pseudomodule."""
- if self.globals is None:
- self.globals = {}
- # Make sure that there is no collision between two interpreters'
- # globals.
- if self.pseudo in self.globals:
- if self.globals[self.pseudo] is not self:
- raise Error("interpreter globals collision")
- self.globals[self.pseudo] = self
-
- def unfix(self):
- """Remove the pseudomodule (if present) from the globals."""
- UNWANTED_KEYS = [self.pseudo, '__builtins__']
- for unwantedKey in UNWANTED_KEYS:
- if unwantedKey in self.globals:
- del self.globals[unwantedKey]
-
- def update(self, other):
- """Update the current globals dictionary with another dictionary."""
- self.globals.update(other)
- self.fix()
-
- def clear(self):
- """Clear out the globals dictionary with a brand new one."""
- self.globals = {}
- self.fix()
+ def finalize(self):
+ """Execute any remaining final routines."""
+ if self.finals:
+ self.push()
+ self.invoke('atFinalize')
+ try:
+ # Pop them off one at a time so they get executed in reverse
+ # order and we remove them as they're executed in case
+ # something bad happens.
+ while self.finals:
+ final = self.finals.pop()
+ if self.invoke('beforeFinalizer', finalizer=final):
+ continue
+ final()
+ self.invoke('afterFinalizer')
+ finally:
+ self.pop()
- def save(self, deep=True):
- if deep:
- copyMethod = copy.deepcopy
- else:
- copyMethod = copy.copy
- """Save a copy of the current globals on the history stack."""
- self.unfix()
- self.history.push(copyMethod(self.globals))
- self.fix()
+ def succeeded(self):
+ """Did the interpreter succeed? That is, is the logged
+ error not an error?"""
+ return self.config.isNotAnError(self.error)
- def restore(self, destructive=True):
- """Restore the topmost historic globals."""
- if destructive:
- fetchMethod = self.history.pop
- else:
- fetchMethod = self.history.top
- self.unfix()
- self.globals = fetchMethod()
- self.fix()
+ def pause(self):
+ """Pause (at the end of processing)."""
+ try:
+ self.input.readline()
+ except EOFError:
+ pass
def shutdown(self):
- """Declare this interpreting session over; close the stream file
- object. This method is idempotent."""
- if self.streams is not None:
+ """Declare this interpreting session over; close all the
+ stream file objects, and if this is the last interpreter,
+ uninstall the proxy. This method is idempotent."""
+ if self.ok:
+ # If we're supposed to go interactive afterwards, do it.
+ if self.config.goInteractive:
+ self.interact()
+ # Wrap things up.
+ succeeded = self.succeeded()
try:
self.finalize()
self.invoke('atShutdown')
while self.streams:
stream = self.streams.pop()
- stream.close()
+ if self.streams:
+ stream.close()
+ else:
+ # Don't close the bottom stream; auto-play diversions
+ # and just flush it.
+ if self.config.autoPlayDiversions and succeeded:
+ stream.undivertAll()
+ stream.flush()
+ self.clear()
finally:
- self.streams = None
-
- def ok(self):
- """Is the interpreter still active?"""
- return self.streams is not None
+ self.uninstallProxy()
+ # Finally, pause if desired.
+ if self.config.pauseAtEnd:
+ self.pause()
+ self.ok = False
+
+ def check(self):
+ """Check the verify this interpreter is still alive."""
+ if not self.ok:
+ raise ConsistencyError("interpreter has already been shutdown")
+
+ def failed(self):
+ """Has this interpreter had an error (which we should not
+ ignore)?"""
+ return self.error and self.config.exitOnError
# Writeable file-like methods.
def write(self, data):
- self.stream().write(data)
+ stream = self.top()
+ assert stream is not None
+ stream.write(data)
- def writelines(self, stuff):
- self.stream().writelines(stuff)
+ def writelines(self, lines):
+ stream = self.top()
+ assert stream is not None
+ stream.writelines(lines)
def flush(self):
- self.stream().flush()
+ stream = self.top()
+ assert stream is not None
+ stream.flush()
def close(self):
self.shutdown()
- # Stack-related activity.
+ def serialize(self, thing):
+ """Output the string version of an object, or a special token if
+ it is None."""
+ if thing is None:
+ if self.config.noneSymbol is not None:
+ self.write(self.config.noneSymbol)
+ else:
+ self.write(self.serializerFunc(thing))
- def context(self):
- return self.contexts.top()
+ # Stack-related activity.
- def stream(self):
+ def top(self):
+ """Get the top stream."""
return self.streams.top()
- def reset(self):
- self.contexts.purge()
- self.streams.purge()
- self.streams.push(Stream(self.output))
- if self.options.get(OVERRIDE_OPT, True):
- sys.stdout.clear(self)
-
def push(self):
- if self.options.get(OVERRIDE_OPT, True):
- sys.stdout.push(self)
+ if self.config.useProxy and self.ok:
+ try:
+ sys.stdout._EmPy_push(self)
+ except AttributeError:
+ raise ConsistencyError("stdout proxy lost; cannot push stream")
def pop(self):
- if self.options.get(OVERRIDE_OPT, True):
- sys.stdout.pop(self)
+ if self.config.useProxy and self.ok:
+ try:
+ sys.stdout._EmPy_pop(self)
+ except AttributeError:
+ raise ConsistencyError("stdout proxy lost; cannot pop stream")
+
+ def clear(self):
+ self.streams.purge()
+ self.streams.push(Stream(self.output, self.diversions))
+ self.contexts.purge()
+ context = self.newContext(self.root)
+ self.contexts.push(context)
+ self.currents.purge()
+ self.currents.push(self.config.renderContext(context))
- # Higher-level operations.
+ # Entry-level processing.
- def include(self, fileOrFilename, locals=None):
+ def include(self, fileOrFilename, locals=None, name=None):
"""Do an include pass on a file or filename."""
- if isinstance(fileOrFilename, _str):
+ if isinstance(fileOrFilename, strType):
# Either it's a string representing a filename ...
filename = fileOrFilename
- name = filename
- file = theSubsystem.open(filename, 'r')
+ if not name:
+ name = filename
+ file = self.config.open(filename, 'r')
else:
# ... or a file object.
file = fileOrFilename
- name = "<%s>" % str(file.__class__)
- self.invoke('beforeInclude', name=name, file=file, locals=locals)
- self.file(file, name, locals)
+ if not name:
+ name = '<%s>' % toString(file.__class__.__name__)
+ if self.invoke('beforeInclude', file=file, locals=locals, name=name):
+ return
+ if name:
+ context = self.newContext(name)
+ self.pushContext(context)
+ self.file(file, locals)
+ if name:
+ self.popContext()
self.invoke('afterInclude')
- def expand(self, data, locals=None):
- """Do an explicit expansion on a subordinate stream."""
+ def expand(self, data, locals=None, name='<expand>', dispatcher=False):
+ """Do an explicit expansion on a subordinate stream in a
+ new context. If dispatch is true, dispatch any exception
+ through the interpreter; otherwise just reraise."""
+ if dispatcher is None:
+ dispatcher = self.dispatcher
+ elif dispatcher is True:
+ dispatcher = self.dispatch
+ elif dispatcher is False:
+ dispatcher = self.reraise
outFile = StringIO()
- stream = Stream(outFile)
- self.invoke('beforeExpand', string=data, locals=locals)
+ stream = Stream(outFile, self.diversions)
+ if self.invoke('beforeExpand', string=data, locals=locals, name=name,
+ dispatcher=dispatcher):
+ return
+ self.push()
self.streams.push(stream)
try:
- self.string(data, '<expand>', locals)
- stream.flush()
- expansion = outFile.getvalue()
+ if name:
+ context = self.newContext(name)
+ self.pushContext(context)
+ try:
+ self.string(data, locals, dispatcher)
+ finally:
+ if name:
+ self.popContext()
+ try:
+ stream.flush()
+ expansion = outFile.getvalue()
+ except ValueError:
+ # Premature termination will result in the file being closed;
+ # ignore it.
+ expansion = None
self.invoke('afterExpand', result=expansion)
return expansion
finally:
self.streams.pop()
+ self.pop()
- def quote(self, data):
- """Quote the given string so that if it were expanded it would
- evaluate to the original."""
- self.invoke('beforeQuote', string=data)
- scanner = Scanner(self.prefix, data)
- result = []
- i = 0
- try:
- j = scanner.next(self.prefix, i)
- result.append(data[i:j])
- result.append(self.prefix * 2)
- i = j + 1
- except TransientParseError:
- pass
- result.append(data[i:])
- result = ''.join(result)
- self.invoke('afterQuote', result=result)
- return result
+ # High-level processing.
- def escape(self, data, more=''):
- """Escape a string so that nonprintable characters are replaced
- with compatible EmPy expansions."""
- self.invoke('beforeEscape', string=data, more=more)
- result = []
- for char in data:
- if char < ' ' or char > '~':
- charOrd = ord(char)
- if charOrd in Interpreter.ESCAPE_CODES:
- result.append(self.prefix + '\\' +
- Interpreter.ESCAPE_CODES[charOrd])
- else:
- result.append(self.prefix + '\\x%02x' % charOrd)
- elif char in more:
- result.append(self.prefix + '\\' + char)
+ def go(self, inputFilename, inputMode, preprocessing, postprocessing):
+ """Execute an interpreter stack at a high level."""
+ # Execute any preprocessing commands.
+ self.process(preprocessing)
+ # Ready!
+ self.ready()
+ # Now process the primary file.
+ method = self.file
+ if inputFilename is None:
+ # Check to see if the encoding/errors are default.
+ if not self.config.isDefaultEncodingErrors(asInput=True):
+ raise InvocationError("non-default Unicode input encoding/errors but using interactive; give explicit input filename: %s/%s" % (self.config.inputEncoding, self.config.inputErrors))
+ self.config.goInteractive = True
+ else:
+ if inputFilename == '-':
+ file = sys.stdin
+ name = '<stdin>'
else:
- result.append(char)
- result = ''.join(result)
- self.invoke('afterEscape', result=result)
- return result
-
- # Processing.
-
- def wrap(self, callable, args):
- """Wrap around an application of a callable and handle errors.
- Return whether no error occurred."""
+ file = self.config.open(inputFilename, inputMode, self.config.buffering)
+ name = inputFilename
+ if self.config.relativePath:
+ dirname = os.path.split(inputFilename)[0]
+ sys.path.insert(0, dirname)
+ try:
+ self.protect(name, method, file)
+ finally:
+ if file is not sys.stdin:
+ file.close()
+ # Finally, execute any postprocessing commands.
+ self.process(postprocessing)
+
+ def protect(self, name, callable, *args, **kwargs):
+ """Wrap around an application of a callable in a new
+ context (named name)."""
+ if name:
+ context = self.newContext(name)
+ self.pushContext(context)
try:
- callable(*args)
- self.reset()
- return True
- except KeyboardInterrupt:
- # Handle keyboard interrupts specially: we should always exit
- # from these.
- e = sys.exc_info()[1]
- self.fail(e, True)
- except Exception:
- # A standard exception (other than a keyboard interrupt).
- e = sys.exc_info()[1]
- self.fail(e)
- except:
- # If we get here, then either it's an exception not derived from
- # Exception or it's a string exception, so get the error type
- # from the sys module.
- e = sys.exc_info()[1]
- self.fail(e)
- # An error occurred if we leak through to here, so do cleanup.
- self.reset()
- return False
+ if kwargs is None:
+ kwargs = {}
+ callable(*args, **kwargs)
+ finally:
+ if name and self.contexts:
+ self.popContext()
def interact(self):
- """Perform interaction."""
+ """Perform interaction. Return whether or not it succeded."""
self.invoke('atInteract')
- done = False
- while not done:
- result = self.wrap(self.file, (sys.stdin, '<interact>'))
- if self.options.get(EXIT_OPT, True):
- done = True
- else:
- if result:
- done = True
- else:
- self.reset()
-
- def fail(self, error, fatal=False):
- """Handle an actual error that occurred."""
- if self.options.get(BUFFERED_OPT, False):
- try:
- self.output.abort()
- except AttributeError:
- # If the output file object doesn't have an abort method,
- # something got mismatched, but it's too late to do
- # anything about it now anyway, so just ignore it.
- pass
- meta = self.meta(error)
- self.handle(meta)
- if self.options.get(RAW_OPT, False):
- raise
- if fatal or self.options.get(EXIT_OPT, True):
- sys.exit(FAILURE_CODE)
-
- def file(self, file, name='<file>', locals=None):
+ self.protect('<interact>', self.fileLines, self.input)
+
+ def file(self, file, locals=None, dispatcher=None):
+ """Parse a file according to the current buffering strategy."""
+ config = self.config
+ if config.hasNoBuffering() or config.hasLineBuffering():
+ self.fileLines(file, locals, dispatcher)
+ elif config.hasFullBuffering():
+ self.fileFull(file, locals, dispatcher)
+ else: # if self.hasFixedBuffering()
+ self.fileChunks(file, config.buffering, locals, dispatcher)
+
+ def fileLines(self, file, locals=None, dispatcher=None):
"""Parse the entire contents of a file-like object, line by line."""
- context = Context(name)
- self.contexts.push(context)
- self.invoke('beforeFile', name=name, file=file, locals=locals)
- scanner = Scanner(self.prefix)
- first = True
+ if self.invoke('beforeFileLines', file=file, locals=locals,
+ dispatcher=dispatcher):
+ return
+ scanner = Scanner(self.config, self.getContext(), self.currents)
done = False
- while not done:
- self.context().bump()
+ first = True
+ while not done and not self.failed():
line = file.readline()
if first:
- if self.options.get(BANGPATH_OPT, True) and self.prefix:
- # Replace a bangpath at the beginning of the first line
- # with an EmPy comment.
- if line.startswith(BANGPATH):
- line = self.prefix + '#' + line[2:]
+ if self.config.ignoreBangpaths and self.config.prefix:
+ if line.startswith(self.config.bangpath):
+ line = self.config.prefix + line
first = False
if line:
scanner.feed(line)
else:
done = True
- self.safe(scanner, done, locals)
- self.invoke('afterFile')
- self.contexts.pop()
-
- def binary(self, file, name='<binary>', chunkSize=0, locals=None):
- """Parse the entire contents of a file-like object, in chunks."""
- if chunkSize <= 0:
- chunkSize = DEFAULT_CHUNK_SIZE
- context = Context(name, units='bytes')
- self.contexts.push(context)
- self.invoke('beforeBinary', name=name, file=file,
- chunkSize=chunkSize, locals=locals)
- scanner = Scanner(self.prefix)
+ while not self.safe(scanner, done, locals, dispatcher):
+ pass
+ self.invoke('afterFileLines')
+
+ def fileChunks(self, file, bufferSize=0, locals=None, dispatcher=None):
+ """Parse the entire contents of a file-like object, in
+ buffered chunks."""
+ assert bufferSize > 0, bufferSize
+ if self.invoke('beforeFileChunks', file=file, bufferSize=bufferSize,
+ locals=locals, dispatcher=dispatcher):
+ return
+ scanner = Scanner(self.config, self.getContext(), self.currents)
done = False
- while not done:
- chunk = file.read(chunkSize)
+ first = True
+ while not done and not self.failed():
+ chunk = file.read(bufferSize)
+ if first:
+ if self.config.ignoreBangpaths and self.config.prefix:
+ if chunk.startswith(self.config.bangpath):
+ chunk = self.config.prefix + chunk
+ first = False
if chunk:
scanner.feed(chunk)
else:
done = True
- self.safe(scanner, done, locals)
- self.context().bump(len(chunk))
- self.invoke('afterBinary')
- self.contexts.pop()
-
- def string(self, data, name='<string>', locals=None):
- """Parse a string."""
- context = Context(name)
- self.contexts.push(context)
- self.invoke('beforeString', name=name, string=data, locals=locals)
- context.bump()
- scanner = Scanner(self.prefix, data)
- self.safe(scanner, True, locals)
+ while not self.safe(scanner, done, locals, dispatcher):
+ pass
+ self.invoke('afterFileChunks')
+
+ def fileFull(self, file, locals=None, dispatcher=None):
+ """Parse the entire contents of a file-like object, in one big
+ chunk."""
+ if self.invoke('beforeFileFull', file=file, locals=locals,
+ dispatcher=dispatcher):
+ return
+ scanner = Scanner(self.config, self.getContext(), self.currents)
+ data = file.read()
+ if self.config.ignoreBangpaths and self.config.prefix:
+ if data.startswith(self.config.bangpath):
+ data = self.config.prefix + data
+ scanner.feed(data)
+ while not self.safe(scanner, True, locals, dispatcher):
+ pass
+ self.invoke('afterFileFull')
+
+ def string(self, data, locals=None, dispatcher=None):
+ """Parse a string. Cleans up after itself."""
+ if self.invoke('beforeString', string=data, locals=locals,
+ dispatcher=dispatcher):
+ return
+ scanner = Scanner(self.config, self.getContext(), self.currents, data)
+ while not self.safe(scanner, True, locals, dispatcher):
+ pass
self.invoke('afterString')
- self.contexts.pop()
- def safe(self, scanner, final=False, locals=None):
+ def safe(self, scanner, final=False, locals=None, dispatcher=None):
"""Do a protected parse. Catch transient parse errors; if
final is true, then make a final pass with a terminator,
otherwise ignore the transient parse error (more data is
- pending)."""
+ pending). Return true if the scanner is exhausted or if an
+ error has occurred."""
+ if dispatcher is None:
+ dispatcher = self.dispatcher
try:
- self.parse(scanner, locals)
+ return self.parse(scanner, locals)
except TransientParseError:
if final:
- # If the buffer doesn't end with a newline, try tacking on
- # a dummy terminator.
buffer = scanner.rest()
- if buffer and buffer[-1] != '\n':
- scanner.feed(self.prefix + '\n')
- # A TransientParseError thrown from here is a real parse
+ # If the buffer ends with a prefix, it's a real parse
# error.
- self.parse(scanner, locals)
+ if buffer and buffer.endswith(self.config.prefix):
+ raise
+ # Try tacking on a dummy terminator to take into account
+ # greedy tokens.
+ scanner.feed(self.config.prefix + NEWLINE_CHAR)
+ try:
+ # Any error thrown from here is a real parse error.
+ self.parse(scanner, locals)
+ except:
+ if dispatcher():
+ return True
+ return True
+ except:
+ if dispatcher():
+ return True
def parse(self, scanner, locals=None):
- """Parse and run as much from this scanner as possible."""
+ """Parse and run as much from this scanner as possible. Return
+ true if the scanner ran out of tokens."""
self.invoke('atParse', scanner=scanner, locals=locals)
while True:
token = scanner.one()
if token is None:
break
self.invoke('atToken', token=token)
- token.run(self, locals)
+ self.run(token, locals)
+ scanner.accumulate()
+ return True
+
+ def process(self, commands):
+ """Process a sequence of high-level commands."""
+ n = 0
+ for command in commands:
+ if self.invoke('beforeProcess', command=command, n=n):
+ return
+ try:
+ command.process(self, n)
+ finally:
+ command.cleanup()
+ self.invoke('afterProcess')
+ n += 1
+
+ # Medium-level processing.
+
+ def tokens(self, tokens, locals=None):
+ """Do an explicit expansion on a sequence of tokens.
+ Cleans up after itself."""
+ outFile = StringIO()
+ stream = Stream(outFile, self.diversions)
+ if self.invoke('beforeTokens', tokens=tokens, locals=locals):
+ return
+ self.streams.push(stream)
+ try:
+ self.runSeveral(tokens, locals)
+ stream.flush()
+ expansion = outFile.getvalue()
+ self.invoke('afterTokens', result=expansion)
+ return expansion
+ finally:
+ self.streams.pop()
+
+ def quote(self, data):
+ """Quote the given string so that if it were expanded it would
+ evaluate to the original."""
+ if self.invoke('beforeQuote', string=data):
+ return
+ scanner = Scanner(self.config, self.getContext(), self.currents, data)
+ result = []
+ i = 0
+ try:
+ j = scanner.next(self.config.prefix, i)
+ result.append(data[i:j])
+ result.append(self.config.prefix * 2)
+ i = j + 1
+ except TransientParseError:
+ pass
+ result.append(data[i:])
+ result = ''.join(result)
+ self.invoke('afterQuote', result=result)
+ return result
- # Medium-level evaluation and execution.
+ def escape(self, data, more=''):
+ """Escape a string so that nonprintable or non-ASCII characters
+ are replaced with compatible EmPy expansions. Also treat
+ characters in more as escapes."""
+ if self.invoke('beforeEscape', string=data, more=more):
+ return
+ result = []
+ for char in data:
+ if char in more:
+ result.append(self.config.prefix + '\\' + char)
+ elif char < ' ' or char > '~':
+ result.append(self.config.escaped(ord(char),
+ self.config.prefix + '\\'))
+ else:
+ result.append(char)
+ result = ''.join(result)
+ self.invoke('afterEscape', result=result)
+ return result
def tokenize(self, name):
"""Take an lvalue string and return a name or a (possibly recursive)
else:
return result
- def significate(self, key, value=None, locals=None):
- """Declare a significator."""
- self.invoke('beforeSignificate', key=key, value=value, locals=locals)
- name = '__%s__' % key
- self.atomic(name, value, locals)
- self.invoke('afterSignificate')
-
def atomic(self, name, value, locals=None):
"""Do an atomic assignment."""
- self.invoke('beforeAtomic', name=name, value=value, locals=locals)
+ if self.invoke('beforeAtomic', name=name, value=value, locals=locals):
+ return
if locals is None:
self.globals[name] = value
else:
def multi(self, names, values, locals=None):
"""Do a (potentially recursive) assignment."""
- self.invoke('beforeMulti', names=names, values=values, locals=locals)
- # No zip in 1.5, so we have to do it manually.
- i = 0
- try:
- values = tuple(values)
- except TypeError:
- raise TypeError("unpack non-sequence")
+ if self.invoke('beforeMulti', names=names, values=values, locals=locals):
+ return
+ values = tuple(values) # to force an exception if not a sequence
if len(names) != len(values):
raise ValueError("unpack tuple of wrong size")
- for i in range(len(names)):
- name = names[i]
- if isinstance(name, _str) or isinstance(name, _unicode):
- self.atomic(name, values[i], locals)
+ for name, value in zip(names, values):
+ if isinstance(name, strType):
+ self.atomic(name, value, locals)
else:
- self.multi(name, values[i], locals)
+ self.multi(name, value, locals)
self.invoke('afterMulti')
def assign(self, name, value, locals=None):
left = self.tokenize(name)
# The return value of tokenize can either be a string or a list of
# (lists of) strings.
- if isinstance(left, _str) or isinstance(left, _unicode):
+ if isinstance(left, strType):
self.atomic(left, value, locals)
else:
self.multi(left, value, locals)
+ def significate(self, key, value=None, locals=None):
+ """Declare a significator."""
+ if self.invoke('beforeSignificate', key=key, value=value, locals=locals):
+ return
+ name = self.config.significatorFor(key)
+ self.atomic(name, value, locals)
+ self.significators[key] = value
+ self.invoke('afterSignificate')
+
def import_(self, name, locals=None):
"""Do an import."""
- self.invoke('beforeImport', name=name, locals=locals)
+ if self.invoke('beforeImport', name=name, locals=locals):
+ return
self.execute('import %s' % name, locals)
self.invoke('afterImport')
def clause(self, catch, locals=None):
- """Given the string representation of an except clause, turn it into
- a 2-tuple consisting of the class name, and either a variable name
- or None."""
- self.invoke('beforeClause', catch=catch, locals=locals)
+ """Given the string representation of an except clause, turn
+ it into a 2-tuple consisting of the class name or tuple of
+ names, and either a variable name or None. If the
+ representation is None, then it's all exceptions and no name."""
+ if self.invoke('beforeClause', catch=catch, locals=locals):
+ return
+ done = False
if catch is None:
exceptionCode, variable = None, None
- elif catch.find(',') >= 0:
- exceptionCode, variable = catch.strip().split(',', 1)
- variable = variable.strip()
- else:
- exceptionCode, variable = catch.strip(), None
+ done = True
+ if not done:
+ match = self.AS_RE.search(catch)
+ if match:
+ exceptionCode, variable = self.AS_RE.split(catch.strip(), 1)
+ exceptionCode = exceptionCode.strip()
+ variable = variable.strip()
+ else:
+ comma = catch.rfind(',')
+ if comma >= 0:
+ exceptionCode, variable = catch[:comma], catch[comma + 1:]
+ exceptionCode = exceptionCode.strip()
+ variable = variable.strip()
+ else:
+ exceptionCode, variable = catch.strip(), None
if not exceptionCode:
- exception = Exception
+ exception = self.config.baseException
else:
exception = self.evaluate(exceptionCode, locals)
self.invoke('afterClause', exception=exception, variable=variable)
return exception, variable
- def serialize(self, expression, locals=None):
- """Do an expansion, involving evaluating an expression, then
- converting it to a string and writing that string to the
- output if the evaluation is not None."""
- self.invoke('beforeSerialize', expression=expression, locals=locals)
- result = self.evaluate(expression, locals)
- if result is not None:
- self.write(str(result))
- self.invoke('afterSerialize')
+ def dictionary(self, code, locals=None):
+ """Given a string representing a key-value argument list, turn
+ it into a dictionary."""
+ code = code.strip()
+ self.push()
+ try:
+ if self.invoke('beforeDictionary', code=code, locals=locals):
+ return
+ if code.strip():
+ result = self.evaluate('{%s}' % code, locals)
+ else:
+ result = {}
+ self.invoke('afterDictionary', result=result)
+ return result
+ finally:
+ self.pop()
+
+ def literal(self, text, locals=None):
+ """Process a string literal."""
+ if self.invoke('beforeLiteral', text=text, locals=locals):
+ return
+ result = self.evaluate(text, locals, replace=False)
+ self.serialize(result)
+ self.invoke('afterLiteral', result=result)
+
+ def functional(self, code, tokensLists, locals=None):
+ """Handle a functional expression like @f{x}. tokensLists
+ is a list of list of tokens. If write is true, write a
+ string version of the result (if not None); otherwise,
+ return it."""
+ self.push()
+ try:
+ if self.invoke('beforeFunctional', code=code, lists=tokensLists,
+ locals=locals):
+ return
+ function = self.evaluate(code, locals)
+ arguments = []
+ for tokensSublist in tokensLists:
+ arguments.append(self.tokens(tokensSublist, locals))
+ result = function(*tuple(arguments))
+ self.invoke('afterFunctional', result=result)
+ return result
+ finally:
+ self.pop()
+
+ # Low-level evaluation.
+
+ def run(self, token, locals=None):
+ """Run a token, tracking the current context."""
+ token.run(self, locals)
+
+ def runSeveral(self, tokens, locals=None):
+ """Run a sequence of tokens."""
+ for token in tokens:
+ self.run(token, locals)
def defined(self, name, locals=None):
"""Return a Boolean indicating whether or not the name is
defined either in the locals or the globals."""
- self.invoke('beforeDefined', name=name, local=local)
- if locals is not None:
- if name in locals:
- result = True
- else:
- result = False
+ if self.invoke('beforeDefined', name=name, locals=locals):
+ return
+ result = False
+ if locals is not None and name in locals:
+ result = True
elif name in self.globals:
result = True
- else:
- result = False
self.invoke('afterDefined', result=result)
+ return result
- def literal(self, text):
- """Process a string literal."""
- self.invoke('beforeLiteral', text=text)
- self.serialize(text)
- self.invoke('afterLiteral')
-
- # Low-level evaluation and execution.
+ def lookup(self, variable, locals=None):
+ """Lookup the value of a variable."""
+ if locals is not None and variable in locals:
+ return locals[variable]
+ else:
+ return self.globals[variable]
- def evaluate(self, expression, locals=None):
- """Evaluate an expression."""
- if expression in ('1', 'True'): return True
- if expression in ('0', 'False'): return False
+ def evaluate(self, expression, locals=None, replace=True):
+ """Evaluate an expression. If replace is true, replace
+ newlines in the expression with spaces if that config
+ variable is set; otherwise, don't do it regardless."""
self.push()
try:
- self.invoke('beforeEvaluate',
- expression=expression, locals=locals)
+ if self.invoke('beforeEvaluate',
+ expression=expression, locals=locals, replace=replace):
+ return
+ if replace and self.config.replaceNewlines:
+ expression = expression.replace('\n', ' ')
if locals is not None:
- result = eval(expression, self.globals, locals)
+ result = self.evalFunc(expression, self.globals, locals)
else:
- result = eval(expression, self.globals)
+ result = self.evalFunc(expression, self.globals)
self.invoke('afterEvaluate', result=result)
return result
finally:
self.pop()
def execute(self, statements, locals=None):
- """Execute a statement."""
+ """Execute a statement(s)."""
# If there are any carriage returns (as opposed to linefeeds/newlines)
- # in the statements code, then remove them. Even on DOS/Windows
- # platforms,
- if statements.find('\r') >= 0:
- statements = statements.replace('\r', '')
+ # in the statements code, then remove them. Even on Windows platforms,
+ # this will work in the Python interpreter.
+ if CARRIAGE_RETURN_CHAR in statements:
+ statements = statements.replace(CARRIAGE_RETURN_CHAR, '')
# If there are no newlines in the statements code, then strip any
# leading or trailing whitespace.
- if statements.find('\n') < 0:
+ if statements.find(NEWLINE_CHAR) < 0:
statements = statements.strip()
self.push()
try:
- self.invoke('beforeExecute',
- statements=statements, locals=locals)
- _exec(statements, self.globals, locals)
+ if self.invoke('beforeExecute',
+ statements=statements, locals=locals):
+ return
+ self.execFunc(statements, self.globals, locals)
self.invoke('afterExecute')
finally:
self.pop()
entered into the Python interactive interpreter."""
self.push()
try:
- self.invoke('beforeSingle',
- source=source, locals=locals)
+ if self.invoke('beforeSingle',
+ source=source, locals=locals):
+ return
code = compile(source, '<single>', 'single')
- _exec(code, self.globals, locals)
- self.invoke('afterSingle')
+ result = self.execFunc(code, self.globals, locals)
+ self.invoke('afterSingle', result=result)
+ return result
finally:
self.pop()
- # Hooks.
+ # Proxy.
- def register(self, hook, prepend=False):
- """Register the provided hook."""
- hook.register(self)
- if self.hooksEnabled is None:
- # A special optimization so that hooks can be effectively
- # disabled until one is added or they are explicitly turned on.
- self.hooksEnabled = True
- if prepend:
- self.hooks.insert(0, hook)
+ def evocare(self, increment):
+ """Try to call the EmPy special method on the proxy with the
+ given increment argument and return the resulting count value.
+ If the magic method is not present (no proxy installed) return None."""
+ method = getattr(sys.stdout, '_EmPy_evocare', None);
+ if method is not None:
+ try:
+ return method(increment)
+ except:
+ raise ConsistencyError("proxy evocare method should not raise")
else:
- self.hooks.append(hook)
-
- def deregister(self, hook):
- """Remove an already registered hook."""
- hook.deregister(self)
- self.hooks.remove(hook)
-
- def invoke(self, _name, **keywords):
- """Invoke the hook(s) associated with the hook name, should they
- exist."""
- if self.hooksEnabled:
- for hook in self.hooks:
- hook.push()
- try:
- method = getattr(hook, _name)
- method(*(), **keywords)
- finally:
- hook.pop()
-
- def finalize(self):
- """Execute any remaining final routines."""
- self.push()
- self.invoke('atFinalize')
- try:
- # Pop them off one at a time so they get executed in reverse
- # order and we remove them as they're executed in case something
- # bad happens.
- while self.finals:
- final = self.finals.pop()
- final()
- finally:
- self.pop()
-
- # Error handling.
-
- def meta(self, exc=None):
- """Construct a MetaError for the interpreter's current state."""
- return MetaError(self.contexts.clone(), exc)
+ return None
- def handle(self, meta):
- """Handle a MetaError."""
- first = True
- self.invoke('atHandle', meta=meta)
- for context in meta.contexts:
- if first:
- if meta.exc is not None:
- desc = "error: %s: %s" % (meta.exc.__class__, meta.exc)
- else:
- desc = "error"
+ def installProxy(self, output=None):
+ """Install a proxy if necessary around the given output,
+ wrapped to be uncloseable, which can be None. Return the
+ wrapped object (but not the proxy)."""
+ if not self.config.useProxy:
+ return UncloseableFile(self.config.defaultStdout)
+ # Unfortunately, there's no surefire way to make sure that installing a
+ # sys.stdout proxy is idempotent, what with different interpreters
+ # running from different modules. The best we can do here is to try to
+ # access the special method on the proxy ...
+ count = self.evocare(+1)
+ if count is not None:
+ # ... and if it's present, this is definitely a proxy. Record it.
+ if Interpreter._proxy is None:
+ Interpreter._proxy = sys.stdout
else:
- desc = "from this context"
- first = False
- sys.stderr.write('%s: %s\n' % (context, desc))
-
- def installProxy(self):
- """Install a proxy if necessary."""
- # Unfortunately, there's no surefire way to make sure that installing
- # a sys.stdout proxy is idempotent, what with different interpreters
- # running from different modules. The best we can do here is to try
- # manipulating the proxy's test function ...
- try:
- sys.stdout._testProxy()
- except AttributeError:
- # ... if the current stdout object doesn't have one, then check
- # to see if we think _this_ particularly Interpreter class has
+ if sys.stdout is not Interpreter._proxy:
+ raise ConsistencyError("stdout proxy duplicated")
+ new = False
+ if output is None:
+ output = Interpreter._proxy._EmPy_bottom
+ else:
+ # ... but if the current sys.stdout object doesn't have one, then
+ # check to see if we think _this_ particular Interpreter class has
# installed it before ...
- if Interpreter._wasProxyInstalled:
- # ... and if so, we have a proxy problem.
- raise Error("interpreter stdout proxy lost")
+ if Interpreter._proxy is not None:
+ # ... and if so, we have a problem.
+ raise ConsistencyError("stdout proxy lost; has sys.stdout been rebound?: %s" % repr(sys.stdout))
else:
- # Otherwise, install the proxy and set the flag.
- sys.stdout = ProxyFile(sys.stdout)
- Interpreter._wasProxyInstalled = True
+ # If not, setup the output file, install the proxy, and
+ # increment the reference count.
+ if output is None:
+ output = self.config.defaultStdout
+ sys.stdout = Interpreter._proxy = ProxyFile(output, self.config.proxyWrapper)
+ self.evocare(+1)
+ new = True
+ assert output is not None
+ self.invoke('atInstallProxy', proxy=Interpreter._proxy, new=new)
+ return output
+
+ def uninstallProxy(self):
+ """Uninstall a proxy if necessary."""
+ if not self.config.useProxy:
+ return
+ # Try decrementing the reference count; if it hits zero, it will
+ # automatically remove itself and restore sys.stdout.
+ try:
+ proxy = sys.stdout
+ done = not self.evocare(-1)
+ self.invoke('atUninstallProxy', proxy=proxy, done=done)
+ except AttributeError:
+ if Interpreter._proxy is not None:
+ raise ConsistencyError("stdout proxy lost; did you not call shutdown?: %s" % repr(sys.stdout))
+ Interpreter._proxy = None
+
+ def checkProxy(self, abandonIsError=True):
+ """Check whether a proxy is installed. Returns the
+ current reference count (positive means one is
+ installed), None (for no proxy installed), or 0 if the
+ proxy has been abandoned. Thus, true means a proxy is
+ installed, false means one isn't. If abandonIsError
+ is true, raise instead of returning 0 on abandonment."""
+ if not self.config.useProxy:
+ return False
+ count = self.evocare(0)
+ if count is not None:
+ if count == 0 and abandonIsError:
+ raise ConsistencyError("stdout proxy abandoned; proxy present but with zero reference count: %s" % repr(sys.stdout))
+ return count
+ else:
+ return None
#
# Pseudomodule routines.
# Identification.
def identify(self):
- """Identify the topmost context with a 2-tuple of the name and
- line number."""
- return self.context().identify()
+ """Identify the topmost context with a tuple of the name and
+ counters."""
+ return self.getContext().identify()
- def atExit(self, callable):
- """Register a function to be called at exit."""
- self.finals.append(callable)
+ # Contexts.
- # Context manipulation.
+ def getContext(self):
+ """Get the top context."""
+ return self.contexts.top()
- def pushContext(self, name='<unnamed>', line=0):
- """Create a new context and push it."""
- self.contexts.push(Context(name, line))
+ def newContext(self, name='<unnamed>', line=None, column=None):
+ """Create and return a new context."""
+ if isinstance(name, tuple):
+ # If name is a tuple, then use it as an argument.
+ return self.newContext(*name)
+ elif isinstance(name, Context):
+ # If it's a Context, create a fresh clone of it.
+ context = Context('<null>', 0, 0,
+ startingLine=self.config.startingLine,
+ startingColumn=self.config.startingColumn)
+ context.restore(name)
+ return context
+ else:
+ # Otherwise, build it up from scratch.
+ if line is None:
+ line = self.config.startingLine
+ if column is None:
+ column = self.config.startingColumn
+ return Context(name, line, column)
+
+ def pushContext(self, context):
+ """Push a new context on the stack."""
+ self.invoke('pushContext', context=context)
+ self.contexts.push(context)
+ self.currents.push(self.config.renderContext(context))
def popContext(self):
"""Pop the top context."""
- self.contexts.pop()
+ context = self.contexts.pop()
+ self.currents.pop()
+ self.invoke('popContext', context=context)
+
+ def setContext(self, context):
+ """Replace the top context."""
+ self.contexts.replace(context)
+ self.currents.replace(self.config.renderContext(context))
+ self.invoke('setContext', context=context)
def setContextName(self, name):
"""Set the name of the topmost context."""
- context = self.context()
+ context = self.getContext()
context.name = name
-
+ self.currents.replace(self.config.renderContext(context))
+ self.invoke('setContext', context=context)
+
def setContextLine(self, line):
- """Set the name of the topmost context."""
- context = self.context()
+ """Set the line number of the topmost context."""
+ context = self.getContext()
context.line = line
+ self.currents.replace(self.config.renderContext(context))
+ self.invoke('setContext', context=context)
+
+ def setContextColumn(self, column):
+ """Set the column number of the topmost context."""
+ context = self.getContext()
+ context.column = column
+ self.currents.replace(self.config.renderContext(context))
+ self.invoke('setContext', context=context)
+
+ def setContextData(self, name=None, line=None, column=None):
+ """Set any of the name, line, or column of the topmost context."""
+ context = self.getContext()
+ if name is not None:
+ context.name = name
+ if line is not None:
+ context.line = line
+ if column is not None:
+ context.column = column
+ self.currents.replace(self.config.renderContext(context))
+ self.invoke('setContext', context=context)
+
+ def restoreContext(self, oldContext, strict=False):
+ """Restore from an old context."""
+ context = self.getContext()
+ context.restore(oldContext, strict)
+ self.currents.replace(self.config.renderContext(context))
+ self.invoke('restoreContext', context=context)
+
+ # Finalizers.
+
+ def clearFinalizers(self):
+ """Clear all finalizers."""
+ self.finals.clear()
+
+ def appendFinalizer(self, finalizer):
+ """Register a function to be called at exit."""
+ self.finals.append(finalizer)
+
+ def prependFinalizer(self, finalizer):
+ """Register a function to be called at exit."""
+ self.finals.insert(0, finalizer)
+
+ atExit = appendFinalizer
- setName = setContextName # DEPRECATED
- setLine = setContextLine # DEPRECATED
+ # Globals.
- # Globals manipulation.
+ def fixGlobals(self):
+ """Reset the globals, stamping in the pseudomodule."""
+ if self.globals is None:
+ self.globals = {}
+ # Make sure that there is no collision between two interpreters'
+ # globals.
+ if self.config.pseudomoduleName in self.globals:
+ if self.globals[self.config.pseudomoduleName] is not self:
+ raise ConsistencyError("interpreter pseudomodule collision in globals")
+ # And finally, flatten the namespaces if that option has been set.
+ if self.config.doFlatten:
+ self.flattenGlobals()
+ self.globals[self.config.pseudomoduleName] = self
+
+ def unfixGlobals(self):
+ """Remove the pseudomodule (if present) from the globals."""
+ for unwantedKey in self.config.unwantedGlobalsKeys:
+ # None is a special sentinel that must be replaced with the name of
+ # the pseudomodule.
+ if unwantedKey is None:
+ unwantedKey = self.config.pseudomoduleName
+ if unwantedKey in self.globals:
+ del self.globals[unwantedKey]
def getGlobals(self):
"""Retrieve the globals."""
def setGlobals(self, globals):
"""Set the globals to the specified dictionary."""
self.globals = globals
- self.fix()
+ self.fixGlobals()
def updateGlobals(self, otherGlobals):
"""Merge another mapping object into this interpreter's globals."""
- self.update(otherGlobals)
+ self.globals.update(otherGlobals)
+ self.fixGlobals()
def clearGlobals(self):
"""Clear out the globals with a brand new dictionary."""
- self.clear()
+ self.globals = {}
+ self.fixGlobals()
def saveGlobals(self, deep=True):
"""Save a copy of the globals off onto the history stack."""
- self.save(deep)
+ if deep:
+ copyMethod = copy.deepcopy
+ else:
+ copyMethod = copy.copy
+ self.unfixGlobals()
+ self.globalsHistory.push(copyMethod(self.globals))
+ self.fixGlobals()
def restoreGlobals(self, destructive=True):
"""Restore the most recently saved copy of the globals."""
- self.restore(destructive)
-
- # Hook support.
-
- def areHooksEnabled(self):
- """Return whether or not hooks are presently enabled."""
- if self.hooksEnabled is None:
- return True
- else:
- return self.hooksEnabled
-
- def enableHooks(self):
- """Enable hooks."""
- self.hooksEnabled = True
-
- def disableHooks(self):
- """Disable hooks."""
- self.hooksEnabled = False
-
- def getHooks(self):
- """Get the current hooks."""
- return self.hooks[:]
-
- def clearHooks(self):
- """Clear all hooks."""
- self.hooks = []
-
- def addHook(self, hook, prepend=False):
- """Add a new hook; optionally insert it rather than appending it."""
- self.register(hook, prepend)
-
- def removeHook(self, hook):
- """Remove a preexisting hook."""
- self.deregister(hook)
-
- def invokeHook(self, _name, **keywords):
- """Manually invoke a hook."""
- self.invoke(*(_name,), **keywords)
-
- # Callbacks.
-
- def getCallback(self):
- """Get the callback registered with this interpreter, or None."""
- return self.callback
-
- def registerCallback(self, callback):
- """Register a custom markup callback with this interpreter."""
- self.callback = callback
-
- def deregisterCallback(self):
- """Remove any previously registered callback with this interpreter."""
- self.callback = None
-
- def invokeCallback(self, contents):
- """Invoke the callback."""
- if self.callback is None:
- if self.options.get(CALLBACK_OPT, False):
- raise Error("custom markup invoked with no defined callback")
+ if destructive:
+ fetchMethod = self.globalsHistory.pop
else:
- self.callback(contents)
-
- # Pseudomodule manipulation.
+ fetchMethod = self.globalsHistory.top
+ self.unfixGlobals()
+ self.globals = fetchMethod()
+ self.fixGlobals()
- def flatten(self, keys=None):
+ def flattenGlobals(self, skipKeys=None):
"""Flatten the contents of the pseudo-module into the globals
namespace."""
- if keys is None:
- keys = list(self.__dict__.keys()) + list(self.__class__.__dict__.keys())
- dict = {}
- for key in keys:
- # The pseudomodule is really a class instance, so we need to
- # fumble use getattr instead of simply fumbling through the
- # instance's __dict__.
- dict[key] = getattr(self, key)
+ flattened = {}
+ if skipKeys is None:
+ skipKeys = self.config.unflattenableGlobalsKeys
+ # The pseudomodule is really a class instance, so we need to fumble
+ # using getattr instead of simply fumbling through the instance's
+ # __dict__.
+ for key in self.__dict__.keys():
+ if key not in skipKeys:
+ flattened[key] = getattr(self, key)
+ for key in self.__class__.__dict__.keys():
+ if key not in skipKeys:
+ flattened[key] = getattr(self, key)
# Stomp everything into the globals namespace.
- self.globals.update(dict)
+ self.globals.update(flattened)
# Prefix.
def getPrefix(self):
"""Get the current prefix."""
- return self.prefix
+ return self.config.prefix
def setPrefix(self, prefix):
"""Set the prefix."""
- self.prefix = prefix
+ assert (prefix is None or
+ (isinstance(prefix, strType) and len(prefix) == 1)), prefix
+ self.config.prefix = prefix
# Diversions.
def stopDiverting(self):
"""Stop any diverting."""
- self.stream().revert()
+ self.top().revert()
def createDiversion(self, name):
"""Create a diversion (but do not divert to it) if it does not
already exist."""
- self.stream().create(name)
+ self.top().create(name)
- def retrieveDiversion(self, name):
+ def retrieveDiversion(self, name, *defaults):
"""Retrieve the diversion object associated with the name."""
- return self.stream().retrieve(name)
+ return self.top().retrieve(name, *defaults)
def startDiversion(self, name):
"""Start diverting to the given diversion name."""
- self.stream().divert(name)
+ self.top().divert(name)
- def playDiversion(self, name):
- """Play the given diversion and then purge it."""
- self.stream().undivert(name, True)
+ def playDiversion(self, name, drop=True):
+ """Play the given diversion and then drop it."""
+ self.top().undivert(name, drop)
- def replayDiversion(self, name):
- """Replay the diversion without purging it."""
- self.stream().undivert(name, False)
+ def replayDiversion(self, name, drop=False):
+ """Replay the diversion without dropping it."""
+ self.top().undivert(name, drop)
- def purgeDiversion(self, name):
+ def dropDiversion(self, name):
"""Eliminate the given diversion."""
- self.stream().purge(name)
+ self.top().drop(name)
def playAllDiversions(self):
- """Play all existing diversions and then purge them."""
- self.stream().undivertAll(True)
+ """Play all existing diversions and then drop them."""
+ self.top().undivertAll(True)
def replayAllDiversions(self):
- """Replay all existing diversions without purging them."""
- self.stream().undivertAll(False)
+ """Replay all existing diversions without dropping them."""
+ self.top().undivertAll(False)
- def purgeAllDiversions(self):
- """Purge all existing diversions."""
- self.stream().purgeAll()
+ def dropAllDiversions(self):
+ """Drop all existing diversions."""
+ self.top().dropAll()
- def getCurrentDiversion(self):
+ def getCurrentDiversionName(self):
"""Get the name of the current diversion."""
- return self.stream().currentDiversion
+ return self.top().current
- def getAllDiversions(self):
+ def getAllDiversionNames(self):
"""Get the names of all existing diversions."""
- names = sorted(self.stream().diversions.keys())
- return names
-
- # Filter.
+ return self.top().names()
- def resetFilter(self):
- """Reset the filter so that it does no filtering."""
- self.stream().install(None)
+ def isExistingDiversionName(self, name):
+ """Does a diversion with this name currently exist?"""
+ return self.top().has(name)
- def nullFilter(self):
- """Install a filter that will consume all text."""
- self.stream().install(0)
+ # Filters.
+
+ def resetFilter(self):
+ """Reset the filter stream so that it does no filtering."""
+ self.top().install(None)
def getFilter(self):
- """Get the current filter."""
- filter = self.stream().filter
- if filter is self.stream().file:
+ """Get the top-level filter."""
+ filter = self.top().filter
+ if filter is self.top().file:
return None
else:
return filter
- def setFilter(self, shortcut):
+ getFirstFilter = getFilter
+
+ def getLastFilter(self):
+ """Get the last filter in the current chain."""
+ return self.top().last()
+
+ def getFilterCount(self):
+ """Get the number of chained filters; 0 means no active
+ filters."""
+ return self.top().count()
+
+ def setFilter(self, *filters):
"""Set the filter."""
- self.stream().install(shortcut)
+ self.top().install(filters)
- def attachFilter(self, shortcut):
+ def prependFilter(self, filter):
"""Attach a single filter to the end of the current filter chain."""
- self.stream().attach(shortcut)
+ self.top().prepend(filter)
+ def appendFilter(self, filter):
+ """Attach a single filter to the end of the current filter chain."""
+ self.top().append(filter)
-class Document:
+ def setFilterChain(self, filters):
+ """Set the filter."""
+ self.top().install(filters)
- """A representation of an individual EmPy document, as used by a
- processor."""
+ # Hooks.
- def __init__(self, ID, filename):
- self.ID = ID
- self.filename = filename
- self.significators = {}
+ def invokeHook(self, _name, **kwargs):
+ """Invoke the hook(s) associated with the hook name, should they
+ exist. Stop and return on the first hook which returns a true
+ result."""
+ if self.config.verbose:
+ self.config.verboseFile.write("%s: %s\n" % (_name, repr(kwargs)))
+ if self.hooksEnabled:
+ for hook in self.hooks:
+ try:
+ method = getattr(hook, _name)
+ result = method(**kwargs)
+ if result:
+ return result
+ finally:
+ pass
+ invoke = invokeHook
-class Processor:
+ def areHooksEnabled(self):
+ """Return whether or not hooks are presently enabled."""
+ if self.hooksEnabled is None:
+ # None is a special value indicate that hooks are enabled but none
+ # have been added yet. It is equivalent to true for testing but
+ # can be optimized away upon invocation.
+ return True
+ else:
+ return self.hooksEnabled
- """An entity which is capable of processing a hierarchy of EmPy
- files and building a dictionary of document objects associated
- with them describing their significator contents."""
+ def enableHooks(self):
+ """Enable hooks."""
+ self.hooksEnabled = True
- DEFAULT_EMPY_EXTENSIONS = ('.em',)
- SIGNIFICATOR_RE = re.compile(SIGNIFICATOR_RE_STRING)
+ def disableHooks(self):
+ """Disable hooks."""
+ self.hooksEnabled = False
- def __init__(self, factory=Document):
- self.factory = factory
- self.documents = {}
+ def getHooks(self):
+ """Get the current hooks."""
+ return self.hooks
- def identifier(self, pathname, filename): return filename
+ def addHook(self, hook, prepend=False):
+ """Add a new hook; optionally insert it rather than appending it."""
+ hook.register(self)
+ if self.hooksEnabled is None:
+ self.hooksEnabled = True
+ if prepend:
+ self.hooks.insert(0, hook)
+ else:
+ self.hooks.append(hook)
- def clear(self):
- self.documents = {}
+ def appendHook(self, hook):
+ """Append the given hook."""
+ self.addHook(hook, False)
- def scan(self, basename, extensions=DEFAULT_EMPY_EXTENSIONS):
- if isinstance(extensions, _str):
- extensions = (extensions,)
- def _noCriteria(x):
- return True
- def _extensionsCriteria(pathname, extensions=extensions):
- if extensions:
- for extension in extensions:
- if pathname[-len(extension):] == extension:
- return True
- return False
- else:
- return True
- self.directory(basename, _noCriteria, _extensionsCriteria, None)
- self.postprocess()
+ def prependHook(self, hook):
+ """Prepend the given hook."""
+ self.addHook(hook, True)
- def postprocess(self):
- pass
+ def removeHook(self, hook):
+ """Remove a preexisting hook."""
+ hook.deregister(self)
+ self.hooks.remove(hook)
- def directory(self, basename, dirCriteria, fileCriteria, depth=None):
- if depth is not None:
- if depth <= 0:
- return
- else:
- depth -= 1
- filenames = os.listdir(basename)
- for filename in filenames:
- pathname = os.path.join(basename, filename)
- if os.path.isdir(pathname):
- if dirCriteria(pathname):
- self.directory(pathname, dirCriteria, fileCriteria, depth)
- elif os.path.isfile(pathname):
- if fileCriteria(pathname):
- documentID = self.identifier(pathname, filename)
- document = self.factory(documentID, pathname)
- self.file(document, open(pathname))
- self.documents[documentID] = document
-
- def file(self, document, file):
- while True:
- line = file.readline()
- if not line:
- break
- self.line(document, line)
-
- def line(self, document, line):
- match = self.SIGNIFICATOR_RE.search(line)
- if match:
- key, valueS = match.groups()
- valueS = valueS.strip()
- if valueS:
- value = eval(valueS)
+ def clearHooks(self):
+ """Clear all hooks."""
+ for hook in self.hooks:
+ hook.deregister(self)
+ self.hooks = []
+ self.hooksEnabled = None
+
+ # Callbacks.
+
+ def hasCallback(self):
+ """Is there a custom callback registered?"""
+ return self.callback is not None
+
+ def getCallback(self):
+ """Get the custom markup callback registered with this
+ interpreter, or None."""
+ return self.callback
+
+ def registerCallback(self, callback):
+ """Register a custom markup callback with this interpreter."""
+ self.callback = callback
+
+ def deregisterCallback(self):
+ """Remove any previously registered custom markup callback
+ with this interpreter."""
+ self.callback = None
+
+ def invokeCallback(self, contents):
+ """Call the custom markup callback."""
+ if self.invoke('beforeCallback', contents=contents):
+ return
+ result = None
+ if self.callback is None:
+ if self.config.noCallbackIsError:
+ raise ConfigurationError("custom markup invoked with no defined callback")
+ else:
+ result = self.callback(contents)
+ self.invoke('afterCallback', result=result)
+ return result
+
+ # Error handling.
+
+ def exit(self, exitCode):
+ """Exit on an error."""
+ # If we are supposed to delete the file on error, do it.
+ if self.filespec is not None and self.config.deleteOnError:
+ # But don't do it on a successful exit.
+ if exitCode != self.config.successCode:
+ os.remove(self.filespec[0])
+
+ def reraise(self, *args):
+ """Reraise an exception."""
+ raise
+
+ def dispatch(self, triple=None):
+ """Dispatch an exception."""
+ if self.config.ignoreErrors:
+ return False
+ if triple is None:
+ triple = sys.exc_info()
+ type, error, traceback = triple
+ # If error is None, then this is a old-style string exception.
+ if error is None:
+ error = StringError(type)
+ # If it's a keyboard interrupt, quit immediately.
+ if isinstance(type, KeyboardInterrupt):
+ fatal = True
+ else:
+ fatal = False
+ # Now handle the exception.
+ self.handle((type, error, traceback), fatal)
+ return self.error is not None and self.config.exitOnError
+
+ def handle(self, info, fatal=False):
+ """Handle an actual error that occurred."""
+ self.invoke('atHandle', info=info, fatal=fatal, contexts=self.currents)
+ type, self.error, traceback = info
+ exitCode = self.config.errorToExitCode(self.error)
+ if self.config.isExitError(self.error):
+ # No Python exception, but we're going to exit.
+ fatal = True
+ else:
+ useDefault = True
+ if self.handler is not None:
+ # Call the customer handler.
+ useDefault = self.handler(type, self.error, traceback)
+ if useDefault and self.error is not None:
+ # Call the default handler if there's still an error.
+ self.defaultHandler(type, self.error, traceback)
+ if self.config.rawErrors:
+ raise
+ if self.error is not None and (fatal or self.config.exitOnError):
+ self.shutdown()
+ self.exit(exitCode)
+
+ def defaultHandler(self, type, error, traceback):
+ """Report an error."""
+ first = True
+ self.flush()
+ sys.stderr.write('\n')
+ for current in self.currents:
+ if current is None:
+ current = self.config.renderContext(self.getContext())
+ if first:
+ if error is not None:
+ description = "error: %s" % self.config.formatError(error)
+ else:
+ description = "error"
else:
- value = None
- document.significators[key] = value
-
-
-def expand(_data, _globals=None,
- _argv=None, _prefix=DEFAULT_PREFIX, _pseudo=None, _options=None, \
- **_locals):
- """Do an atomic expansion of the given source data, creating and
- shutting down an interpreter dedicated to the task. The sys.stdout
- object is saved off and then replaced before this function
- returns."""
- if len(_locals) == 0:
+ description = "from this context"
+ first = False
+ sys.stderr.write('%s: %s\n' % (current, description))
+ sys.stderr.flush()
+
+ def getHandler(self):
+ """Get the current handler, or None for the default."""
+ return self.handler
+
+ def setHandler(self, handler, exitOnError=False):
+ """Set the current handler. Additionally, specify whether
+ errors should exit (defaults to false with a custom
+ handler)."""
+ self.handler = handler
+ if exitOnError is not None:
+ self.config.exitOnError = exitOnError
+
+ def invokeHandler(self, *args):
+ """Manually invoke the error handler with the given
+ exception info 3-tuple or three arguments."""
+ if len(args) == 1:
+ self.handler(*args[0])
+ else:
+ self.handler(*args)
+
+ # Emojis.
+
+ def initializeEmojiModules(self, moduleNames=None):
+ """Determine which emoji module to use. If moduleNames is not
+ specified, use the defaults."""
+ return self.config.initializeEmojiModules(moduleNames)
+
+ def getEmojiModule(self, moduleName):
+ """Return an abstracted emoji module by name or return
+ None."""
+ return self.config.emojiModules.get(moduleName)
+
+ def getEmojiModuleNames(self):
+ """Return the emoji module names in usage in their proper
+ order."""
+ return self.config.emojiModuleNames
+
+ def substituteEmoji(self, text):
+ """Substitute an emoji text or return None."""
+ return self.config.substituteEmoji(text)
+
+#
+# functions
+#
+
+def details(level, prelim="Welcome to ", postlim=".\n",
+ file=sys.stdout):
+ """Write some details, using the details subsystem if available."""
+ write = file.write
+ details = None
+ if level > Version.VERSION:
+ try:
+ import emlib
+ details = emlib.Details()
+ except ImportError:
+ raise ConfigurationError("missing emlib module; details subsystem not available")
+ if details:
+ try:
+ details.show(level, prelim, postlim, file)
+ except TypeError:
+ raise
+ else:
+ write("%s%s version %s%s" % (prelim, __project__, __version__, postlim))
+ sys.stdout.flush()
+
+def expand(data,
+ _globals=None, _argv=None, _prefix=None, _pseudo=None, _options=None,
+ **kwargs):
+ """Do a self-contained expansion of the given source data,
+ creating and shutting down an interpreter dedicated to the task.
+ Expects the same keyword arguments as the Interpreter constructor.
+ Additionally, 'name' will identify the expansion filename and
+ 'locals', if present, represents the locals dictionary to use.
+ The sys.stdout object is saved off and then replaced before this
+ function returns. Any exception that occurs will be raised to the
+ caller."""
+ def extract(dict, key, default=None):
+ if key in dict:
+ value = dict.get(key)
+ del dict[key]
+ else:
+ value = default
+ return value
+ # For backward compatibility. These arguments (starting with underscore)
+ # are currently DEPRECATED.
+ if _globals is not None:
+ if 'globals' in kwargs:
+ raise CompatibilityError("extra keywords contain extra 'globals' key; use keyword arguments")
+ kwargs['globals'] = _globals
+ if _argv is not None:
+ if 'argv' in kwargs:
+ raise CompatibilityError("extra keywords contain extra 'argv' key; use keyword arguments")
+ kwargs['argv'] = _argv
+ if _prefix is not None:
+ raise CompatibilityError("_prefix argument to expand no longer supported; use prefix configuration variable")
+ if _pseudo is not None:
+ raise CompatibilityError("_pseudo argument to expand no longer supported; use pseudomoduleName configuration variable")
+ if _options is not None:
+ raise CompatibilityError("options dictionary is no longer supported; use configurations")
+ # Keyword argument compatibility checks.
+ for key in ['filters', 'handler', 'input', 'output']:
+ if kwargs.get(key):
+ raise ConfigurationError("argument doesn't make sense with an ephemeral interpreter; use a non-ephemeral interpreter instead: %s" % key, key=key)
+ # Set up the changed defaults.
+ if 'dispatcher' not in kwargs:
+ kwargs['dispatcher'] = False
+ # And then the local variables.
+ name = extract(kwargs, 'name', '<expand>')
+ locals = extract(kwargs, 'locals', None)
+ if isinstance(locals, dict) and len(locals) == 0:
# If there were no keyword arguments specified, don't use a locals
# dictionary at all.
- _locals = None
+ locals = None
output = NullFile()
- interpreter = Interpreter(output, argv=_argv, prefix=_prefix,
- pseudo=_pseudo, options=_options,
- globals=_globals)
- if interpreter.options.get(OVERRIDE_OPT, True):
- oldStdout = sys.stdout
+ interpreter = None
+ result = None
try:
- result = interpreter.expand(_data, _locals)
+ interpreter = Interpreter(**kwargs)
+ result = interpreter.expand(data, locals, name, dispatcher=None)
finally:
- interpreter.shutdown()
- if _globals is not None:
- interpreter.unfix() # remove pseudomodule to prevent clashes
- if interpreter.options.get(OVERRIDE_OPT, True):
- sys.stdout = oldStdout
+ if interpreter:
+ interpreter.shutdown()
+ interpreter.unfixGlobals() # remove pseudomodule to prevent clashes
return result
-def environment(name, default=None):
- """Get data from the current environment. If the default is True
- or False, then presume that we're only interested in the existence
- or non-existence of the environment variable."""
- if name in os.environ:
- # Do the True/False test by value for future compatibility.
- if default == False or default == True:
- return True
+def invoke(args, **kwargs):
+ """Run a standalone instance of an EmPy interpreter with the
+ given globals, config, and output (any of which can be None).
+ Return the resulting exit code. Errors is a variable that
+ represents a tuple of exception types to catch and print
+ rather than let through; if it is None, use the defaults from
+ the configuration."""
+ def extract(dict, key, default=None):
+ if key in dict:
+ value = dict.get(key)
+ del dict[key]
else:
- return os.environ[name]
- else:
- return default
-
-def info(table):
- DEFAULT_LEFT = 28
- maxLeft = 0
- maxRight = 0
- for left, right in table:
- if len(left) > maxLeft:
- maxLeft = len(left)
- if len(right) > maxRight:
- maxRight = len(right)
- FORMAT = ' %%-%ds %%s\n' % max(maxLeft, DEFAULT_LEFT)
- for left, right in table:
- if right.find('\n') >= 0:
- for right in right.split('\n'):
- sys.stderr.write(FORMAT % (left, right))
- left = ''
- else:
- sys.stderr.write(FORMAT % (left, right))
-
-def usage(verbose=True):
- """Print usage information."""
- programName = sys.argv[0]
- def warn(line=''):
- sys.stderr.write("%s\n" % line)
- warn("""\
-Usage: %s [options] [<filename, or '-' for stdin> [<argument>...]]
-Welcome to EmPy version %s.""" % (programName, __version__))
- warn()
- warn("Valid options:")
- info(OPTION_INFO)
- if verbose:
- warn()
- warn("The following markups are supported:")
- info(MARKUP_INFO)
- warn()
- warn("Valid escape sequences are:")
- info(ESCAPE_INFO)
- warn()
- warn("The %s pseudomodule contains the following attributes:" % DEFAULT_PSEUDOMODULE_NAME)
- info(PSEUDOMODULE_INFO)
- warn()
- warn("The following environment variables are recognized:")
- info(ENVIRONMENT_INFO)
- warn()
- warn(USAGE_NOTES)
- else:
- warn()
- warn("Type %s -H for more extensive help." % programName)
-
-def invoke(args):
- """Run a standalone instance of an EmPy interpeter."""
+ value = default
+ return value
+ # Get the defaults.
+ config = extract(kwargs, 'config', None)
+ errors = extract(kwargs, 'errors', ())
+ globals = extract(kwargs, 'globals', None)
+ hooks = extract(kwargs, 'hooks', [])
+ output = extract(kwargs, 'output', None)
+ for key in ['filespec', 'immediately']:
+ if key in kwargs:
+ raise ConfigurationError("argument cannot be specified with invoke: %s" % key, key=key)
# Initialize the options.
- _output = None
- _options = {BUFFERED_OPT: environment(BUFFERED_ENV, False),
- RAW_OPT: environment(RAW_ENV, False),
- EXIT_OPT: True,
- FLATTEN_OPT: environment(FLATTEN_ENV, False),
- OVERRIDE_OPT: not environment(NO_OVERRIDE_ENV, False),
- CALLBACK_OPT: False}
- _preprocessing = []
- _prefix = environment(PREFIX_ENV, DEFAULT_PREFIX)
- _pseudo = environment(PSEUDO_ENV, None)
- _interactive = environment(INTERACTIVE_ENV, False)
- _extraArguments = environment(OPTIONS_ENV)
- _binary = -1 # negative for not, 0 for default size, positive for size
- _unicode = environment(UNICODE_ENV, False)
- _unicodeInputEncoding = environment(INPUT_ENCODING_ENV, None)
- _unicodeOutputEncoding = environment(OUTPUT_ENCODING_ENV, None)
- _unicodeInputErrors = environment(INPUT_ERRORS_ENV, None)
- _unicodeOutputErrors = environment(OUTPUT_ERRORS_ENV, None)
- _hooks = []
- _pauseAtEnd = False
- _relativePath = False
- if _extraArguments is not None:
- _extraArguments = _extraArguments.split()
- args = _extraArguments + args
- # Parse the arguments.
- pairs, remainder = getopt.getopt(args, 'VhHvkp:m:frino:a:buBP:I:D:E:F:', ['version', 'help', 'extended-help', 'verbose', 'null-hook', 'suppress-errors', 'prefix=', 'no-prefix', 'module=', 'flatten', 'raw-errors', 'interactive', 'no-override-stdout', 'binary', 'chunk-size=', 'output=' 'append=', 'preprocess=', 'import=', 'define=', 'execute=', 'execute-file=', 'buffered-output', 'pause-at-end', 'relative-path', 'no-callback-error', 'no-bangpath-processing', 'unicode', 'unicode-encoding=', 'unicode-input-encoding=', 'unicode-output-encoding=', 'unicode-errors=', 'unicode-input-errors=', 'unicode-output-errors='])
- for option, argument in pairs:
- if option in ('-V', '--version'):
- sys.stderr.write("%s version %s\n" % (__program__, __version__))
- return
- elif option in ('-h', '--help'):
- usage(False)
- return
- elif option in ('-H', '--extended-help'):
- usage(True)
- return
- elif option in ('-v', '--verbose'):
- _hooks.append(VerboseHook())
- elif option in ('--null-hook',):
- _hooks.append(Hook())
- elif option in ('-k', '--suppress-errors'):
- _options[EXIT_OPT] = False
- _interactive = True # suppress errors implies interactive mode
- elif option in ('-m', '--module'):
- _pseudo = argument
- elif option in ('-f', '--flatten'):
- _options[FLATTEN_OPT] = True
- elif option in ('-p', '--prefix'):
- _prefix = argument
- elif option in ('--no-prefix',):
- _prefix = None
- elif option in ('-r', '--raw-errors'):
- _options[RAW_OPT] = True
- elif option in ('-i', '--interactive'):
- _interactive = True
- elif option in ('-n', '--no-override-stdout'):
- _options[OVERRIDE_OPT] = False
- elif option in ('-o', '--output'):
- _output = argument, 'w', _options[BUFFERED_OPT]
- elif option in ('-a', '--append'):
- _output = argument, 'a', _options[BUFFERED_OPT]
- elif option in ('-b', '--buffered-output'):
- _options[BUFFERED_OPT] = True
- elif option in ('-B',): # DEPRECATED
- _options[BUFFERED_OPT] = True
- elif option in ('--binary',):
- _binary = 0
- elif option in ('--chunk-size',):
- _binary = int(argument)
- elif option in ('-P', '--preprocess'):
- _preprocessing.append(('pre', argument))
- elif option in ('-I', '--import'):
- for module in argument.split(','):
- module = module.strip()
- _preprocessing.append(('import', module))
- elif option in ('-D', '--define'):
- _preprocessing.append(('define', argument))
- elif option in ('-E', '--execute'):
- _preprocessing.append(('exec', argument))
- elif option in ('-F', '--execute-file'):
- _preprocessing.append(('file', argument))
- elif option in ('-u', '--unicode'):
- _unicode = True
- elif option in ('--pause-at-end',):
- _pauseAtEnd = True
- elif option in ('--relative-path',):
- _relativePath = True
- elif option in ('--no-callback-error',):
- _options[CALLBACK_OPT] = True
- elif option in ('--no-bangpath-processing',):
- _options[BANGPATH_OPT] = False
- elif option in ('--unicode-encoding',):
- _unicodeInputEncoding = _unicodeOutputEncoding = argument
- elif option in ('--unicode-input-encoding',):
- _unicodeInputEncoding = argument
- elif option in ('--unicode-output-encoding',):
- _unicodeOutputEncoding = argument
- elif option in ('--unicode-errors',):
- _unicodeInputErrors = _unicodeOutputErrors = argument
- elif option in ('--unicode-input-errors',):
- _unicodeInputErrors = argument
- elif option in ('--unicode-output-errors',):
- _unicodeOutputErrors = argument
- # Set up the Unicode subsystem if required.
- if (_unicode or
- _unicodeInputEncoding or _unicodeOutputEncoding or
- _unicodeInputErrors or _unicodeOutputErrors):
- theSubsystem.initialize(_unicodeInputEncoding,
- _unicodeOutputEncoding,
- _unicodeInputErrors, _unicodeOutputErrors)
- # Now initialize the output file if something has already been selected.
- if _output is not None:
- _output = AbstractFile(*_output)
- # Set up the main filename and the argument.
- if not remainder:
- remainder.append('-')
- filename, arguments = remainder[0], remainder[1:]
- # Set up the interpreter.
- if _options[BUFFERED_OPT] and _output is None:
- raise ValueError("-b only makes sense with -o or -a arguments")
- if _prefix == 'None':
- _prefix = None
- if (_prefix and isinstance(_prefix, _str) and len(_prefix) != 1):
- raise Error("prefix must be single-character string")
- interpreter = Interpreter(output=_output,
- argv=remainder,
- prefix=_prefix,
- pseudo=_pseudo,
- options=_options,
- hooks=_hooks)
+ if config is None:
+ config = Configuration()
+ if errors is None:
+ errors = config.topLevelErrors
+ # Let's go!
try:
- # Execute command-line statements.
- i = 0
- for which, thing in _preprocessing:
- if which == 'pre':
- command = interpreter.file
- target = theSubsystem.open(thing, 'r')
- name = thing
- elif which == 'define':
- command = interpreter.string
- if thing.find('=') >= 0:
- target = '%s{%s}' % (_prefix, thing)
- else:
- target = '%s{%s = None}' % (_prefix, thing)
- name = '<define:%d>' % i
- elif which == 'exec':
- command = interpreter.string
- target = '%s{%s}' % (_prefix, thing)
- name = '<exec:%d>' % i
- elif which == 'file':
- command = interpreter.string
- name = '<file:%d (%s)>' % (i, thing)
- target = '%s{exec(open("""%s""").read())}' % (_prefix, thing)
- elif which == 'import':
- command = interpreter.string
- name = '<import:%d>' % i
- target = '%s{import %s}' % (_prefix, thing)
- else:
- assert 0
- interpreter.wrap(command, (target, name))
- i += 1
- # Now process the primary file.
- interpreter.ready()
- if filename == '-':
- if not _interactive:
- name = '<stdin>'
- path = ''
- file = sys.stdin
+ interpreter = None
+ inputFilename = None
+ inputMode = 'r'
+ outputFilename = None
+ outputMode = None
+ nullFile = False
+ preprocessing = []
+ postprocessing = []
+ configStatements = []
+ configPaths = []
+ immediately = False
+ level = Version.NONE
+ topics = None
+ # Note any configuration files from the environment.
+ configPath = config.environment(CONFIG_ENV)
+ if configPath is not None:
+ configPaths.append(configPath)
+ # Get any extra arguments from the environment.
+ extraArguments = config.environment(OPTIONS_ENV)
+ if extraArguments is not None:
+ extraArguments = extraArguments.split()
+ args = extraArguments + args
+ # Parse the arguments.
+ try:
+ SHORTS = 'VWZh?H:vp:qm:fkeridnc:Co:a:O:A:b:NLBP:Q:I:D:S:E:F:G:wluxyz'
+ LONGS = ['version', 'info', 'details', 'help', 'topics=', 'extended-help=', 'verbose', 'prefix=', 'no-prefix', 'no-output', 'pseudomodule=', 'module=', 'flatten', 'keep-going', 'ignore-errors', 'raw-errors', 'interactive', 'delete-on-error', 'no-proxy', 'no-override-stdout', 'config=', 'configuration=', 'config-file=', 'configuration-file=', 'config-variable=', 'configuration-variable=', 'ignore-missing-config', 'output=' 'append=', 'output-binary=', 'append-binary=', 'output-mode=', 'input-mode=', 'buffering=', 'default-buffering', 'no-buffering', 'line-buffering', 'full-buffering', 'preprocess=', 'postprocess=', 'import=', 'define=', 'string=', 'execute=', 'file=', 'postfile=', 'pause-at-end', 'relative-path', 'no-callback-error', 'no-replace-newlines', 'no-ignore-bangpaths', 'no-expand-user', 'no-auto-validate-icons', 'none-symbol', 'no-none-symbol', 'starting-line=', 'starting-column=', 'emoji-modules=', 'no-emoji-modules', 'disable-emoji-modules', 'ignore-emoji-not-found', 'binary', 'input-binary', 'unicode', 'encoding=', 'unicode-encoding=', 'input-encoding=', 'unicode-input-encoding=', 'output-encoding=', 'unicode-output-encoding=', 'errors=', 'unicode-errors=', 'input-errors=', 'unicode-input-errors=', 'output-errors=', 'unicode-output-errors=', 'normalization-form=', 'unicode-normalization-form=', 'auto-play-diversions', 'no-auto-play-diversions', 'check-variables', 'no-check-variables', 'path-separator', 'context-format=', 'success-code=', 'failure-code=', 'unknown-code=', 'null-hook']
+ pairs, argv = getopt.getopt(args, SHORTS, LONGS)
+ except getopt.GetoptError:
+ type, error, traceback = sys.exc_info()
+ if error.args[1] == 'H':
+ # A missing argument with -H should be interpreted as -H all.
+ pairs = []
+ topics = 'all'
else:
- name, file = None, None
- else:
- name = filename
- file = theSubsystem.open(filename, 'r')
- path = os.path.split(filename)[0]
- if _relativePath:
- sys.path.insert(0, path)
- if file is not None:
- if _binary < 0:
- interpreter.wrap(interpreter.file, (file, name))
+ raise InvocationError(*error.args)
+ for option, argument in pairs:
+ if option in ['-V', '--version']:
+ level += 1
+ elif option in ['-W', '--info']:
+ level = Version.INFO
+ elif option in ['-Z', '--details']:
+ level = Version.ALL
+ elif option in ['-h', '-?', '--help']:
+ if not topics:
+ topics = 'default'
+ elif topics == 'default':
+ topics = 'more'
+ else:
+ topics = 'all'
+ elif option in ['-H', '--topics', '--extended-help']:
+ topics = argument
+ if ',' in topics:
+ topics = topics.split(',')
+ else:
+ topics = [topics]
+ elif option in ['-v', '--verbose']:
+ config.verbose = True
+ elif option in ['-p', '--prefix']:
+ config.prefix = argument
+ elif option in ['--no-prefix']:
+ config.prefix = None
+ elif option in ['-q', '--no-output']:
+ nullFile = True
+ elif option in ['-m', '--pseudomodule', '--module']:
+ config.pseudomoduleName = argument
+ elif option in ['-f', '--flatten']:
+ config.doFlatten = True
+ elif option in ['-k', '--keep-going']:
+ config.exitOnError = False
+ elif option in ['-e', '--ignore-errors']:
+ config.ignoreErrors = True
+ config.exitOnError = False
+ elif option in ['-r', '--raw-errors']:
+ config.rawErrors = True
+ elif option in ['-i', '--interactive']:
+ config.goInteractive = True
+ elif option in ['-d', '--delete-on-error']:
+ config.deleteOnError = True
+ elif option in ['-n', '--no-proxy', '--no-override-stdout']:
+ config.useProxy = False
+ elif option in ['--config', '--configuration']:
+ configStatements.append(argument)
+ elif option in ['-c', '--config-file', '--configuration-file']:
+ configPaths.append(argument)
+ elif option in ['--config-variable', '--configuration-variable']:
+ config.configVariableName = argument
+ elif option in ['-C', '--ignore-missing-config']:
+ config.missingConfigIsError = False
+ elif option in ['-o', '--output']:
+ outputFilename = argument
+ outputMode = 'w'
+ elif option in ['-a', '--append']:
+ outputFilename = argument
+ outputMode = 'a'
+ elif option in ['-O', '--output-binary']:
+ outputFilename = argument
+ outputMode = 'wb'
+ elif option in ['-A', '--append-binary']:
+ outputFilename = argument
+ outputMode = 'ab'
+ elif option in ['--output-mode']:
+ outputMode = argument
+ elif option in ['--input-mode']:
+ inputMode = argument
+ elif option in ['-b', '--buffering']:
+ config.setBuffering(argument)
+ elif option in ['--default-buffering']:
+ config.setBuffering(config.defaultBuffering)
+ elif option in ['-N', '--no-buffering']:
+ config.setBuffering(config.noBuffering)
+ elif option in ['-L', '--line-buffering']:
+ config.setBuffering(config.lineBuffering)
+ elif option in ['-B', '--full-buffering']:
+ config.setBuffering(config.fullBuffering)
+ elif option in ['-P', '--preprocess']:
+ preprocessing.append(DocumentCommand(argument))
+ elif option in ['-Q', '--postprocess']:
+ postprocessing.append(DocumentCommand(argument))
+ elif option in ['-I', '--import']:
+ for module in argument.split(','):
+ module = module.strip()
+ preprocessing.append(ImportCommand(module))
+ elif option in ['-D', '--define']:
+ preprocessing.append(DefineCommand(argument))
+ elif option in ['-S', '--string']:
+ preprocessing.append(StringCommand(argument))
+ elif option in ['-E', '--execute']:
+ preprocessing.append(ExecCommand(argument))
+ elif option in ['-F', '--file']:
+ preprocessing.append(FileCommand(argument))
+ elif option in ['-G', '--postfile']:
+ postprocessing.append(FileCommand(argument))
+ elif option in ['-w', '--pause-at-end']:
+ config.pauseAtEnd = True
+ elif option in ['-l', '--relative-path']:
+ config.relativePath = True
+ elif option in ['--no-callback-error']:
+ config.noCallbackIsError = False
+ elif option in ['--no-replace-newlines']:
+ config.replaceNewlines = False
+ elif option in ['--no-ignore-bangpaths']:
+ config.ignoreBangpaths = False
+ elif option in ['--no-expand-user']:
+ config.expandUserConstructions = False
+ elif option in ['--no-auto-validate-icons']:
+ config.autoValidateIcons = False
+ elif option in ['--none-symbol']:
+ config.noneSymbol = argument
+ elif option in ['--no-none-symbol']:
+ config.noneSymbol = None
+ elif option in ['--starting-line']:
+ config.startingLine = int(argument)
+ elif option in ['--starting-column']:
+ config.startingColumn = int(argument)
+ elif option in ['--emoji-modules']:
+ moduleNames = [x.strip() for x in argument.split(',')]
+ if moduleNames == ['None'] or moduleNames == ['']:
+ moduleNames = None
+ config.emojiModuleNames = moduleNames
+ elif option in ['--no-emoji-modules']:
+ config.emojiModuleNames = config.defaultNoEmojiModuleNames
+ elif option in ['--disable-emoji-modules']:
+ config.emojiModuleNames = None
+ elif option in ['--ignore-emoji-not-found']:
+ config.emojiNotFoundIsError = False
+ elif option in ['-u', '--binary', '--input-binary', '--unicode']:
+ config.enableBinary()
+ elif option in ['-x', '--encoding', '--unicode-encoding']:
+ config.enableBinary(major, minor)
+ config.inputEncoding = config.outputEncoding = argument
+ elif option in ['--input-encoding', '--unicode-input-encoding']:
+ config.enableBinary(major, minor)
+ config.inputEncoding = argument
+ elif option in ['--output-encoding', '--unicode-output-encoding']:
+ config.enableBinary(major, minor)
+ config.outputEncoding = argument
+ elif option in ['-y', '--errors', '--unicode-errors']:
+ config.enableBinary(major, minor)
+ config.inputErrors = config.outputErrors = argument
+ elif option in ['--input-errors', '--unicode-input-errors']:
+ config.enableBinary(major, minor)
+ config.inputErrors = argument
+ elif option in ['--output-errors', '--unicode-output-errors']:
+ config.enableBinary(major, minor)
+ config.outputErrors = argument
+ elif option in ['-z', '--normalization-form', '--unicode-normalization-form']:
+ if argument == 'none' or argument == 'None':
+ argument = ''
+ config.normalizationForm = argument
+ elif option in ['--auto-play-diversions']:
+ config.autoPlayDiversions = True
+ elif option in ['--no-auto-play-diversions']:
+ config.autoPlayDiversions = False
+ elif option in ['--check-variables']:
+ config.checkVariables = True
+ elif option in ['--no-check-variables']:
+ config.checkVariables = False
+ elif option in ['--path-separator']:
+ config.pathSeparator = argument
+ elif option in ['--context-format']:
+ config.setContextFormat(argument)
+ Context.format = config.contextFormat
+ elif option in ['--success-code']:
+ config.successCode = int(argument)
+ elif option in ['--failure-code']:
+ config.failureCode = int(argument)
+ elif option in ['--unknown-code']:
+ config.unknownCode = int(argument)
+ elif option in ['--null-hook']:
+ try:
+ import emlib
+ hooks.append(emlib.Hook())
+ except ImportError:
+ raise InvocationError("missing emlib module; --null-hook not available")
else:
- chunkSize = _binary
- interpreter.wrap(interpreter.binary, (file, name, chunkSize))
- # If we're supposed to go interactive afterwards, do it.
- if _interactive:
- interpreter.interact()
- finally:
- interpreter.shutdown()
- # Finally, if we should pause at the end, do it.
- if _pauseAtEnd:
+ assert False, "unhandled option: %s" % option
+ # Show the details and exit if desired.
+ if level > 0:
+ details(level)
+ return config.successCode
+ # Load any configuration files.
+ for configStatement in configStatements:
+ config.run(configStatement)
+ for configPath in configPaths:
+ config.path(configPath)
+ # Show the help if desired.
+ if topics is not None:
+ try:
+ import emhelp
+ usage = emhelp.Usage(config)
+ usage.hello()
+ usage.show(topics)
+ except ImportError:
+ raise InvocationError("missing emhelp subsystem module; no help available")
+ return config.successCode
+ # Set up the main script filename and the arguments.
+ if not argv:
+ argv.append(None)
+ else:
+ inputFilename = argv[0]
+ # Do sanity checks on the configuration.
+ config.check(inputFilename, outputFilename)
+ # Now initialize the output file.
+ if nullFile:
+ output = NullFile()
+ filespec = None
+ elif outputFilename is not None:
+ if output is not None:
+ raise InvocationError("can't specify more than one output")
+ filespec = outputFilename, outputMode, config.buffering
+ output = config.open(*filespec)
+ else:
+ # Check to see if the encoding/errors are default.
+ if not config.isDefaultEncodingErrors(asInput=False):
+ raise InvocationError("non-default Unicode output encoding/errors selected but using stdout; use -o/-a option: %s/%s" % (config.outputEncoding, config.outputErrors))
+ filespec = None
+ # Get ready!
+ exitCode = config.successCode
+ kwargs['argv'] = argv
+ kwargs['config'] = config
+ kwargs['filespec'] = filespec
+ kwargs['globals'] = globals
+ kwargs['hooks'] = hooks
+ kwargs['immediately'] = immediately
+ kwargs['output'] = output
try:
- _input()
- except EOFError:
- pass
+ # Create the interpreter.
+ interpreter = Interpreter(**kwargs)
+ # Run it.
+ interpreter.go(
+ inputFilename, inputMode, preprocessing, postprocessing)
+ exitCode = config.errorToExitCode(interpreter.error)
+ finally:
+ # Finally, handle any cleanup.
+ if interpreter is not None:
+ interpreter.shutdown()
+ except KeyboardInterrupt:
+ if config.rawErrors:
+ raise
+ exitCode = config.failureCode
+ except SystemExit:
+ type, error, traceback = sys.exc_info()
+ if len(error.args) > 0:
+ exitCode = error.args[0] # okay even if a string
+ except errors:
+ if config.rawErrors:
+ raise
+ type, error, traceback = sys.exc_info()
+ if not interpreter:
+ sys.stderr.write(config.formatError(error, "ERROR: ", "\n"))
+ exitCode = config.unknownCode
+ except:
+ if config.rawErrors:
+ raise
+ type, error, traceback = sys.exc_info()
+ if not interpreter:
+ sys.stderr.write(config.formatError(error, "ERROR: ", "\n"))
+ exitCode = config.errorToExitCode(error)
+ # Old versions of Python 3.x don't flush sys.__stdout__ when redirecting
+ # stdout for some reason.
+ if sys.__stdout__ is not None:
+ sys.__stdout__.flush()
+ return exitCode
+
+#
+# main
+#
def main():
- invoke(sys.argv[1:])
+ exitCode = invoke(sys.argv[1:], executable=sys.argv[0], errors=None)
+ sys.exit(exitCode)
if __name__ == '__main__': main()
--- /dev/null
+#!/usr/bin/env python3
+
+"""
+EmPy documentation generating system. This module requires a modern
+Python 3.x interpreter.
+"""
+
+#
+# imports
+#
+
+import hashlib
+import os
+import subprocess
+import sys
+import time
+
+import em
+import emhelp
+import emlib
+
+#
+# constants
+#
+
+def admonish(text):
+ return ":::{{important}}\n{}\n:::\n"
+
+EMOJIS = {
+ '...': ('\N{HORIZONTAL ELLIPSIS}', "horizontal ellipsis"),
+ '!!!': (admonish("!!! \u2757\ufe0f"), "exclamation mark"),
+ '???': (admonish("??? \u2753\ufe0f"), "question mark"),
+ '^^^': (admonish("^^^ \u26a0\ufe0f"), "warning sign"),
+ '///': (admonish("/// \u2714\ufe0f"), "check mark"),
+ '\\\\\\': (admonish("\\\\\\ \u274c\ufe0f"), "cross mark"),
+ '+++': (admonish("+++ \U0001f53a"), "red triangle pointed up"),
+ '---': (admonish("--- \U0001f53b"), "red triangle pointed down"),
+ '-->': ('\N{LONG RIGHTWARDS ARROW}', "long rightwards arrow"),
+}
+
+#
+# Identity
+#
+
+class Identity:
+
+ """Dynamically access magic attributes on both the interpreter and
+ underlying module."""
+
+ def __init__(self, pseudo, module):
+ self.pseudo = pseudo
+ self.module = module
+
+ def __str__(self):
+ try:
+ return self.__getattr__('project')
+ except AttributeError:
+ return self.__getattr__('program')
+
+ def __getattr__(self, attr):
+ attribute = '__{}__'.format(attr)
+ if attribute in self.pseudo.globals:
+ return self.pseudo.globals[attribute]
+ elif attribute in self.module.__dict__:
+ return self.module.__dict__[attribute]
+ else:
+ raise AttributeError("unknown attribute: {}".format(__attribute__))
+
+ def tarball(self, version='latest'):
+ if version is None:
+ version = self.version
+ return '{}{}-{}.tar.gz'.format(self.url, self.program, version)
+
+ def path(self, suffix=None):
+ if suffix is not None:
+ return self.url + suffix
+ else:
+ return self.url
+
+#
+# Information
+#
+
+class Information:
+
+ """A helper information class to generate documentation."""
+
+ timeFormat = '%Y-%m-%d %H:%M:%S'
+ extensions = ['.md.em', '.md.pre', '.md', '']
+ hashFactory = hashlib.sha1
+ hashName = 'SHA1'
+ encoding = 'utf-8'
+
+ class Flag:
+
+ """Encapsulate a flag: a command line option, a configuration
+ variable, and/or an environment variable."""
+
+ def __init__(self, config, options, var=None, env=None):
+ self.config = config
+ self.options = options
+ self.var = var
+ self.env = env
+
+ def __str__(self):
+ return str((self.options, self.var))
+
+ def render(self, file, key, verbose=False):
+ isOption = key.startswith('-')
+ options = '/'.join("`{}`".format(x) for x in self.options)
+ environ = '`{}`'.format(self.env) if self.env else None
+ variable = '`{}`'.format(self.var) if self.var else None
+ fragments = []
+ if verbose:
+ if isOption:
+ assert options
+ # It's an option, so list those first.
+ primary = options
+ if environ:
+ fragments.extend(["_environment variable:_ " + environ])
+ if variable:
+ fragments.extend(["_configuration variable:_ " + variable])
+ elif key.startswith('EMPY_'):
+ assert environ
+ # If it starts with EMPY_, it's an environment variable.
+ primary = environ
+ if options:
+ fragments.extend(["_command line option:_ " + options])
+ if variable:
+ fragments.extend(["_configuration variable:_ " + variable])
+ else:
+ assert variable
+ # Otherwise, it's a configuration variable.
+ primary = variable
+ types = self.config._specs[key]
+ if types is not None:
+ if types == (bytes, str):
+ types = str
+ if not isinstance(types, tuple):
+ types = (types,)
+ optional = False
+ if types[-1] is None:
+ # If the last one is None, then the type is
+ # Optional.
+ optional = True
+ types = types[:-1]
+ types = ' | '.join(
+ 'None' if x is None else x.__name__
+ for x in types)
+ if optional:
+ types = 'Optional[%s]' % types
+ primary = primary[:-1] + ": {}`".format(types)
+ if options:
+ fragments.extend(["_command line option:_ " + options])
+ if environ:
+ fragments.extend(["_environment variable:_ " + environ])
+ if fragments:
+ file.write('{} ({})'.format(primary, ', '.join(fragments)))
+ else:
+ file.write(primary)
+ else:
+ if isOption:
+ file.write(options)
+ else:
+ file.write('`{}`'.format(key))
+
+ noLanguage = 'text'
+
+ def __init__(self, pseudo, moduleName, file=sys.stdout):
+ self.pseudo = pseudo
+ self.moduleName = moduleName
+ self.file = file
+ self.module = __import__(moduleName)
+ self.ident = Identity(pseudo, self.module)
+ self.details = emlib.Details()
+ self.config = em.Configuration()
+ self.usage = emhelp.Usage(config=self.config)
+ self.options = self.process()
+
+ def process(self):
+ options = {}
+ section = self.usage.payload['options']
+ for entry in section.entries:
+ fullOptions = [x for x in entry.raw if not x.isspace()]
+ theseOptions = [x.split('=', 1)[0] for x in fullOptions]
+ flag = self.Flag(self.config, fullOptions, entry.var, entry.env)
+ for key in theseOptions:
+ assert key not in options, key
+ options[key] = flag
+ if entry.var:
+ options[entry.var] = flag
+ if entry.env:
+ options[entry.env.split(' ', 1)[0]] = flag
+ for key, value in self.config.__dict__.items():
+ if key in options:
+ options[key].val = value
+ else:
+ flag = self.Flag(self.config, [], key)
+ options[key] = flag
+ return options
+
+ def topic(self, topic, separator=False):
+ self.file.write("```{}\n".format(self.noLanguage))
+ self.usage.show([topic], separator)
+ self.file.write("```\n")
+
+ def option(self, key, verbose=False, default=False):
+ if verbose is None:
+ self.file.write('`{}`'.format(key))
+ return
+ self.options[key].render(self.file, key, verbose)
+ if default and key in self.config:
+ if key == 'pathSeparator':
+ value = "`;` (Windows), `:` (others)"
+ else:
+ value = getattr(self.config, key)
+ if isinstance(value, tuple):
+ value = repr(value)
+ if isinstance(value, dict):
+ value = "{...}"
+ value = "`{}`".format(value)
+ self.file.write(" [{}]".format(value))
+
+ def variable(self, variable):
+ self.file.write("`{}`".format(variable))
+
+ def source(self, filename='README'):
+ for extension in self.extensions:
+ if os.path.exists(filename + extension):
+ return filename + extension
+ else:
+ raise FileNotFoundError("source file not found: {}".format(filename))
+
+ def filter(self, text, lines=None, blanks=None):
+ if isinstance(text, bytes) and self.encoding:
+ text = text.decode(self.encoding)
+ text = (text
+ .replace('&', '&')
+ .replace('<', '<')
+ .replace('>', '>'))
+ stopped = False
+ chunks = []
+ for line in text.splitlines():
+ if line.startswith('...'):
+ chunks.append("<i>{}</i>".format(line))
+ else:
+ chunks.append(line)
+ if not line and blanks is not None:
+ blanks -= 1
+ if blanks == 0:
+ stopped = True
+ if lines is not None and len(chunks) >= lines:
+ stopped = True
+ if stopped:
+ break
+ if stopped:
+ chunks.append('...')
+ return '\n'.join(chunks)
+
+ def shell(self, command, output, prefix='% ', lines=None, blanks=None,
+ exitCode=0):
+ display = command
+ if isinstance(display, list):
+ words = ['"{}"'.format(x)
+ if ' ' in x and not x.startswith('#')
+ else x
+ for x in command]
+ display = ' '.join(words)
+ self.file.write("<pre class=\"shell\">")
+ if display:
+ self.file.write("<b><i>{}{}</i></b>\n".format(
+ prefix, self.filter(display)))
+ self.file.write(self.filter(output, lines, blanks))
+ if exitCode != 0:
+ self.file.write("<i>Exit code: {}</i>".format(exitCode))
+ self.file.write("</pre>\n")
+
+ def execute(self, command, prefix='% ', lines=None, blanks=None, check=True):
+ oldPath = os.environ['PATH']
+ try:
+ # Make sure that if it's em.py, it's the local one.
+ path = '.:' + oldPath
+ os.environ['PATH'] = path
+ result = subprocess.run(command, capture_output=True)
+ output = result.stdout
+ self.shell(command, output, prefix, lines, blanks,
+ exitCode=result.returncode if check else 0)
+ finally:
+ os.environ['PATH'] = oldPath
+
+ def summarize(self):
+ filename = self.source()
+ hasher = self.hashFactory()
+ with open(filename, 'rb') as f:
+ data = f.read()
+ length = len(data)
+ hasher.update(data)
+ hash = hasher.hexdigest()
+ record = os.stat(filename)
+ when = time.localtime(record.st_mtime)
+ timeStamp = time.strftime(self.timeFormat, when)
+ out = em.StringIO('w')
+ self.details.show(file=out)
+ self.file.write("""\
+_This documentation for {} version {} was generated from {} ({} `{}`, {} bytes) at {} with {}._
+""".format(
+ self.ident, self.ident.version, filename,
+ self.hashName, hash, length,
+ timeStamp, out.getvalue()))
+ self.done()
+
+ def done(self):
+ if self.config:
+ self.pseudo.dropAllDiversions()
+ self.config = None
+
+#
+# Callback
+#
+
+class Callback(emlib.Callback):
+
+ """The EmPy documentation custom callback."""
+
+ languages = {
+ 'empy': '' # to eliminate Pygments warning
+ }
+
+ asTable = False
+
+ def __init__(self, interp):
+ super(Callback, self).__init__(interp)
+ self.current = 0
+
+ def __call__(self, source):
+ caption = None
+ if source.startswith('['):
+ language = 'empy'
+ caption, source = source[1:].split(']', 1)
+ example = True
+ else:
+ if not source.startswith('\n'):
+ language, source = source.split('\n', 1)
+ language = language.strip()
+ else:
+ language = ''
+ example = False
+ if caption:
+ suffix = ': ' + caption
+ else:
+ suffix = ''
+ source = source.strip() + '\n'
+ if example:
+ number = self.next()
+ self.interp.startDiversion(caption)
+ self.interp.write(":::{{admonition}} Example {}{}\n".format(
+ number, suffix))
+ output = em.expand(source,
+ name='<example {}>'.format(number))
+ if self.asTable:
+ self.interp.write(" \n")
+ self.interp.write("<table>\n")
+ self.interp.write("<tr><th>Source</th><th>Output</th></tr>\n")
+ self.interp.write("<tr><td valign=top>\n\n")
+ self.interp.write("``````\n{}``````\n\n".format(source))
+ self.interp.write("</td><td valign=top>\n\n")
+ self.interp.write("``````\n{}``````\n\n".format(output))
+ self.interp.write("</td></tr>\n")
+ self.interp.write("</table>\n")
+ else:
+ self.interp.write(" \n")
+ self.interp.write(" \n")
+ self.interp.write("_Source_:\n")
+ self.interp.write("``````{}\n".format(self.languages.get(language, language)))
+ self.interp.write(source)
+ self.interp.write("``````\n")
+ self.interp.write("\n")
+ self.interp.write("_Output_:\n")
+ self.interp.write("``````\n")
+ self.interp.write(output)
+ self.interp.write("``````\n")
+ self.interp.write(":::\n")
+ self.interp.stopDiverting()
+ self.interp.replayDiversion(caption)
+ else:
+ self.interp.write("``````{}\n".format(self.languages.get(language, language)))
+ self.interp.write(source)
+ self.interp.write("``````\n")
+
+ def next(self, amount=1):
+ self.current += amount
+ return self.current
+
+#
+# Hook
+#
+
+class Hook(emlib.Hook):
+
+ """The EmPy documentation hook."""
+
+ delimiter = '`'
+
+ def __init__(self, interp):
+ self.interp = interp
+
+ def preBackquote(self, literal):
+ if self.delimiter in literal:
+ for count in range(1, 10):
+ if '`' * count not in literal:
+ count -= 1
+ break
+ else:
+ count = 0
+ affix = self.delimiter * (count + 1)
+ self.interp.write("{}{}{}".format(affix, literal, affix))
+ return True
+
+#
+# init
+#
+
+def init(pseudo, moduleName, paths=['../..', '.']):
+ """Initialize the information object."""
+ for path in paths:
+ sys.path.insert(0, os.path.abspath(path))
+ pseudo.config.emojis = EMOJIS
+ pseudo.addHook(Hook(pseudo))
+ pseudo.registerCallback(Callback(pseudo))
+ return Information(pseudo, moduleName)
--- /dev/null
+#!/usr/bin/env python3
+
+"""
+Help subsystem for EmPy.
+"""
+
+#
+# imports
+#
+
+import sys
+
+import em
+
+#
+# Entry ...
+#
+
+class Entry(em.Root):
+
+ """An entry in one of the usage tables. This exists to allow
+ optional annotations or processing for each entry."""
+
+ def __init__(self, raw, right,
+ var=None, env=None, arg=None, ord=None, ex=None, fun=None):
+ self.raw = raw
+ self.left = self.format(raw)
+ self.right = right
+ self.var = var
+ self.env = env
+ self.arg = arg
+ if isinstance(ord, int):
+ ord = [ord]
+ self.ords = ord
+ self.ex = ex
+ self.fun = fun
+
+ def __str__(self):
+ if self.ords is None:
+ ords = '--'
+ else:
+ ords = ' '.join([hex(x) for x in self.ords])
+ return '%s [%s]' % (self.left, ords)
+
+ def __lt__(self, other):
+ if self.ords is None or other.ords is None:
+ return self.left < other.left
+ else:
+ if self.ords == other.ords:
+ return self.left < other.left
+ else:
+ return self.ords < other.ords
+
+ def __cmp__(self, other):
+ if self.ords is None or other.ords is None:
+ return cmp(self.left, other.left)
+ else:
+ if self.ords == other.ords:
+ return cmp(self.left, other.left)
+ else:
+ return cmp(self.ords, other.ords)
+
+ def format(self, raw):
+ """Format the raw list. Override in subclasses."""
+ if isinstance(raw, list):
+ if isinstance(raw, list):
+ return ' '.join(raw)
+ else:
+ return raw
+ else:
+ return raw
+
+#
+# NameEntry
+#
+
+class NameEntry(Entry):
+
+ def __lt__(self, other):
+ return self.left < other.left
+
+ def __cmp__(self, other):
+ return cmp(self.left, other.left)
+
+#
+# OptionEntry
+#
+
+class OptionEntry(Entry):
+
+ def format(self, raw):
+ if isinstance(raw, list):
+ assert len(raw) > 0
+ if raw[0].startswith('--'):
+ raw.insert(0, ' ')
+ return ' '.join(raw)
+ else:
+ return raw
+
+#
+# Section ...
+#
+
+class Section(em.Root):
+
+ """A section in one of the usage tables."""
+
+ def __init__(self, topic, description, header):
+ self.topic = topic
+ self.description = description
+ self.header = header
+
+ def __str__(self):
+ return self.topic
+
+ def ok(self):
+ return True
+
+ def show(self, usage, useSeparator=True):
+ if not self.ok():
+ return
+ if useSeparator:
+ usage.separator()
+ usage.write("%s:\n" % self.topic.upper())
+ usage.write(self.header)
+ self.block(usage)
+
+ def block(self, usage):
+ pass
+
+class TableSection(Section):
+
+ """A section with a block that consists of a flat table of
+ entries."""
+
+ def __init__(self, topic, description, header, entries):
+ super(TableSection, self).__init__(topic, description, header)
+ self.entries = entries
+
+ def ok(self):
+ return bool(self.entries)
+
+ def block(self, usage):
+ usage.table(self.entries)
+
+class ConfigSection(TableSection):
+
+ """A section with a block that consists of each configuration
+ variable."""
+
+ def __init__(self, topic, description, header, config):
+ super(ConfigSection, self).__init__(topic, description, header, [])
+ for left in config._names:
+ right = config._descriptions[left]
+ fun = config._functions[left]
+ entry = Entry(left, right, var=left, fun=fun)
+ self.entries.append(entry)
+
+class MappingSection(TableSection):
+
+ """A section with a block that consists of a mapping type which is
+ transformed into a table of entries."""
+
+ def __init__(self, topic, description, header, mapping, factory=Entry):
+ super(MappingSection, self).__init__(topic, description, header, [])
+ for key, value in mapping.items():
+ if value is None:
+ continue
+ # Value can be an ordinal, a string, or a 2-tuple of (ordinal,
+ # name).
+ if isinstance(value, tuple):
+ ordinal, right = value
+ else:
+ ordinal = None
+ right = value
+ if isinstance(ordinal, (em.bytes, em.str)):
+ ordinal = ord(ordinal)
+ if isinstance(right, int):
+ right = em.chr(right)
+ entry = factory(key, right, ord=ordinal)
+ self.entries.append(entry)
+ self.entries.sort()
+
+class HelpSection(TableSection):
+
+ """A section with a block that consists of the help topics."""
+
+ def __init__(self, topic, description, header, usage):
+ super(HelpSection, self).__init__(topic, description, header, [])
+ self.usage = usage
+
+ def refresh(self):
+ """Refresh the list of topics. At creation time it won't
+ contain itself."""
+ payload = self.usage.payload
+ all = Usage.aliases['all']
+ for topic in all:
+ if topic in payload:
+ section = payload[topic]
+ if section.ok():
+ self.entries.append(
+ Entry(section.topic, section.description))
+
+#
+# Usage
+#
+
+class Usage(em.Root):
+
+ """A utility class to print usage and extended help."""
+
+ aliases = {
+ 'default': ['usage', 'options', 'markup', 'hints', 'topics'],
+ 'more': ['usage', 'options', 'markup', 'escapes', 'environ', 'hints',
+ 'topics'],
+ 'optional': ['emojis'],
+ 'config': ['variables', 'methods'],
+ 'all': ['usage', 'options', 'markup', 'escapes', 'environ', 'pseudo',
+ 'constructor', 'variables', 'methods', 'hooks', 'named',
+ 'diacritics', 'icons', 'emojis', 'hints', 'topics'],
+ }
+
+ defaultWidth = 6
+ columns = None # 81
+
+ def __init__(self, config=None, file=None):
+ if config is None:
+ config = em.Configuration()
+ self.config = config
+ if file is None:
+ file = sys.stdout
+ self.file = file
+ self.payload = {}
+ prepare(self)
+ self.fix()
+
+ def format(self, width):
+ return ' %%-%ds %%s\n' % max(width, Usage.defaultWidth)
+
+ def transform(self, topics):
+ """Transform a list of possible topics into a list of valid
+ topics."""
+ if topics is None:
+ topics = 'default'
+ results = []
+ if not isinstance(topics, list):
+ topics = [topics]
+ for topic in topics:
+ topic = topic.lower()
+ if topic in Usage.aliases:
+ results.extend(Usage.aliases[topic])
+ else:
+ results.append(topic)
+ return results
+
+ def add(self, section):
+ """Add a section to the payload."""
+ assert section.topic not in self.payload
+ self.payload[section.topic] = section
+
+ def fix(self):
+ """Fix the payload."""
+ self.payload['topics'].refresh()
+
+ def separator(self):
+ """Write a separator."""
+ self.write("\n")
+
+ def write(self, string):
+ """Write a string (with the correct prefix substitution)."""
+ if not self.config.hasDefaultPrefix():
+ string = string.replace(self.config.defaultPrefix,
+ self.config.prefix)
+ self.file.write(string)
+
+ def flush(self):
+ """Flush the underlying stream."""
+ self.file.flush()
+
+ def scan(self, table):
+ """Scan a table to find the minimum column width."""
+ result = 0
+ for entry in table:
+ left = entry.left
+ rights = entry.right
+ if len(left) > result:
+ result = len(left)
+ return result
+
+ def previewChars(self, ords):
+ """Return a preview of the (non-text) character ordinals,
+ or None."""
+ if ords is None:
+ return
+ if em.major < 3 or not sys.stdout.encoding.lower().startswith('utf'):
+ # Don't bother if this isn't Python 3.x or the encoding isn't
+ # UTF-8.
+ return
+ firstOrd = ords[0]
+ chars = ''.join([chr(x) for x in ords])
+ while not chars.isprintable():
+ # Some emoji blocks report as unprintable in various versions of
+ # Python.
+ if firstOrd >= 0x2600 and firstOrd < 0x2c00:
+ break
+ if firstOrd >= 0x1f000 and firstOrd < 0x1fb00:
+ break
+ return
+ if chars.isspace():
+ return
+ if firstOrd == 0x034f:
+ # Combining grapheme joiner.
+ return
+ if firstOrd == 0x303e:
+ # Ideographic variation indicator.
+ return
+ if firstOrd == 0xfffc:
+ # Object replacement character.
+ return
+ if firstOrd >= 0xfe00 and firstOrd < 0xfe10:
+ # Variation selectors 1-16.
+ return
+ if firstOrd >= 0xe0100 and firstOrd < 0xe01f0:
+ # Variation selectors 17-256.
+ return
+ if firstOrd >= 0x0300 and firstOrd < 0x0370:
+ # Combiners.
+ chars = chr(0x25cc) + chars
+ return chars
+
+ def entry(self, entry, format):
+ """Print a table entry."""
+ def _identity(x): return x
+ left = entry.left
+ lines = entry.right.split('\n')
+ fun = entry.fun or _identity
+ i = 0
+ for line in lines:
+ last = i == len(lines) - 1
+ fragments = []
+ if entry.ords is not None:
+ first = True
+ for x in entry.ords:
+ if first:
+ first = False
+ else:
+ fragments.append(' ')
+ fragments.append("U+%04X" % x)
+ fragments.append("; ")
+ fragments.append(line)
+ if last:
+ if entry.arg is not None:
+ fragments.append(": %s" % fun(entry.arg))
+ if entry.var is not None:
+ value = fun(getattr(self.config, entry.var))
+ if isinstance(value, dict):
+ value = "{%d}" % len(value)
+ fragments.append(" [%s]" % str(value))
+ if entry.ex is not None:
+ fragments.append(" (e.g., %s)" % fun(entry.ex))
+ preview = self.previewChars(entry.ords)
+ if preview:
+ fragments.append(': ')
+ fragments.append(preview)
+ right = ''.join(fragments).strip()
+ line = format % (left, right)
+ assert self.columns is None or len(line) < self.columns, line
+ self.write(line)
+ left = ''
+ i += 1
+
+ def table(self, table):
+ """Print a table at the current level with an optional header."""
+ width = self.scan(table)
+ format = self.format(width)
+ for entry in table:
+ self.entry(entry, format)
+
+ def hello(self):
+ self.write("Welcome to %s version %s.\n" % (
+ em.__project__, em.__version__))
+
+ def show(self, topics=None, useSeparator=True):
+ """Show usage."""
+ if topics is None:
+ topics = 'default'
+ topics = self.transform(topics)
+ for topic in topics:
+ topic = topic.lower()
+ if topic in self.payload:
+ self.payload[topic].show(self, useSeparator)
+ else:
+ self.write("*** Unknown usage topic: %s\n" % topic)
+
+#
+# functions
+#
+
+def prepare(usage):
+ """Lazily initialize the usage data and tables only if they're
+ actually needed. This is a standalone function so there's less
+ misleading indentation. Idempotent."""
+ payload = usage.payload
+ if payload:
+ return payload
+ E = Entry
+ OE = OptionEntry
+
+ usage.add(Section(
+ 'usage',
+ "Basic command line usage",
+ """\
+%s [<options>] [<filename, or `-` for stdin> [<argument>...]]
+ - Options begin with `-` or `--`
+ - Specify a filename (and arguments) to process that file as input
+ - Specify `-` (and arguments) to process stdin with standard buffering
+ - Specify no filename to enter interactive mode with line buffering
+ - Specify `--` to stop processing options
+""" % (sys.argv[0])))
+
+ usage.add(Section(
+ 'hints',
+ "Usage hints",
+ """\
+Whitespace immediately inside parentheses of `@(...)` are ignored. Whitespace
+immediately inside braces of `@{...}` are ignored, unless ... spans multiple
+lines. Use `@{ ... }@` to suppress newline following second `@`. Simple
+expressions ignore trailing punctuation; `@x.` means `@(x).`, not a parse
+error. A `#!` at the start of a file is treated as a comment. The full
+documentation is available at <%s>.
+""" % em.__url__))
+
+ usage.add(TableSection(
+ 'options',
+ "Command line options",
+ """\
+Valid command line options (defaults in brackets):
+""", [
+OE(["-V", "--version"], "Print version"),
+OE(["-W", "--info"], "Print version and system information"),
+OE(["-Z", "--details"], "Print extensive system and platform details"),
+OE(["-h", "--help"], "Print help; more -h options for more help"),
+OE(["-H", "--topics=TOPICS"], "Print usage for comma-separated topics"),
+OE(["-v", "--verbose"], "Show verbose debugging while processing"),
+OE(["-p", "--prefix=CHAR"], "Choose desired prefix", var='prefix', env=em.PREFIX_ENV),
+OE(["--no-prefix"], "Do not do any markup processing at all"),
+OE(["-q", "--no-output"], "Suppress all output"),
+OE(["-m", "--pseudomodule=NAME"], "Change internal pseudomodule name", var='pseudomoduleName', env=em.PSEUDO_ENV),
+OE(["-f", "--flatten"], "Flatten pseudomodule members at start", var='doFlatten', env=em.FLATTEN_ENV),
+OE(["-k", "--keep-going"], "Don't exit on errors; continue"),
+OE(["-e", "--ignore-errors"], "Ignore errors completely"),
+OE(["-r", "--raw-errors"], "Show full tracebacks of Python errors", var='rawErrors', env=em.RAW_ERRORS_ENV),
+OE(["-i", "--interactive"], "Enter interactive mode after processing", var='goInteractive', env=em.INTERACTIVE_ENV),
+OE(["-d", "--delete-on-error"], "Delete output file on error\n"
+ "(-o or -a needed)", var='deleteOnError', env=em.DELETE_ON_ERROR_ENV),
+OE(["-n", "--no-proxy"], "Do not override sys.stdout with proxy", var='useProxy', env=em.NO_PROXY_ENV),
+OE(["--config=STATEMENTS"], "Do configuration variable assignments"),
+OE(["-c", "--config-file=FILENAME"], "Load configuration resource path(s)", env=em.CONFIG_ENV),
+OE(["--config-variable=NAME"], "Configuration variable name while loading", var='configVariableName'),
+OE(["-C", "--ignore-missing-config"], "Don't raise for missing configuration files"),
+OE(["-o", "--output=FILENAME"], "Specify file for output as write"),
+OE(["-a", "--append=FILENAME"], "Specify file for output as append"),
+OE(["-O", "--output-binary=FILENAME"], "Specify file for binary output as write"),
+OE(["-A", "--append-binary=FILENAME"], "Specify file for binary output as append"),
+OE(["--output-mode=MODE"], "Explicitly specify the mode for output"),
+OE(["--input-mode=MODE"], "Explicitly specify the mode for input"),
+OE(["-b", "--buffering"], "Specify buffering strategy for files:\n"
+ "none (= 0), line (= 1), full (= -1), default,\n"
+ "or another value for fixed", var='buffering', env=em.BUFFERING_ENV),
+OE(["--default-buffering"], "Specify default buffering for files"),
+OE(["-N", "--no-buffering"], "Specify no buffering for reads on files"),
+OE(["-L", "--line-buffering"], "Specify line buffering for files"),
+OE(["-B", "--full-buffering"], "Specify full buffering for files"),
+OE(["-P", "--preprocess=FILENAME"], "Interpret EmPy file before main file"),
+OE(["-Q", "--postprocess=FILENAME"], "Interpret EmPy file after main file"),
+OE(["-I", "--import=MODULES"], "Import Python modules before processing"),
+OE(["-D", "--define=DEFN"], "Execute Python assignment statement"),
+OE(["-S", "--string=STR"], "Execute string literal assignment"),
+OE(["-E", "--execute=STATEMENT"], "Execute Python statement before main file"),
+OE(["-F", "--file=FILENAME"], "Execute Python file before main file"),
+OE(["-G", "--postfile=FILENAME"], "Execute Python file after main file"),
+OE(["-w", "--pause-at-end"], "Prompt at the ending of processing"),
+OE(["-l", "--relative-path"], "Add path of EmPy script to sys.path", var='relativePath'),
+OE(["--no-callback-error"], "Custom markup with no callback is ignored"),
+OE(["--no-replace-newlines"], "Don't replace expression newlines with spaces"),
+OE(["--no-ignore-bangpaths"], "Don't treat bangpaths as comments"),
+OE(["--no-expand-user"], "Don't expand user constructions in filenames"),
+OE(["--no-auto-validate-icons"], "Don't auto-validate icons"),
+OE(["--none-symbol"], "String to write when expanding None", var='noneSymbol'),
+OE(["--no-none-symbol"], "Write nothing when expanding None (default)"),
+OE(["--starting-line"], "Line number to start with", var='startingLine'),
+OE(["--starting-column"], "Column number to start with", var='startingColumn'),
+OE(["--emoji-modules"], "Comma-separated list of emoji modules to try\n", var='emojiModuleNames', fun=lambda x: ','.join(x)),
+OE(["--no-emoji-modules"], "Only use unicodedata for emoji markup"),
+OE(["--disable-emoji-modules"], "Disable emoji modules; use emojis dictionary"),
+OE(["--ignore-emoji-not-found"], "Emoji not found is not an error"),
+OE(["-u", "--binary", "--unicode"], "Read input file as binary?\n"
+ "(enables Unicode support in Python 2.x)", var='useBinary', env=em.BINARY_ENV),
+OE(["-x", "--encoding=E"], "Set both input and output Unicode encodings"),
+OE(["--input-encoding=E"], "Set input Unicode encoding", var='inputEncoding', env=em.INPUT_ENCODING_ENV, fun=lambda x: x == 'utf_8' and 'utf-8' or x),
+OE(["--output-encoding=E"], "Set output Unicode encoding", var='outputEncoding', env=em.OUTPUT_ENCODING_ENV, fun=lambda x: x == 'utf_8' and 'utf-8' or x),
+OE(["-y", "--errors=E"], "Set both input and output Unicode error handler"),
+OE(["--input-errors=E"], "Set input Unicode error handler", var='inputErrors', env=em.INPUT_ERRORS_ENV),
+OE(["--output-errors=E"], "Set output Unicode error handler", var='outputErrors', env=em.OUTPUT_ERRORS_ENV),
+OE(["-z", "--normalization-form=F"], "Specify Unicode normalization form", var='normalizationForm'),
+OE(["--no-auto-play-diversions"], "Don't autoplay diversions on exit", var='autoPlayDiversions'),
+OE(["--no-check-variables"], "Don't validate configuration variables", var='checkVariables'),
+OE(["--path-separator"], "Path separator for configuration paths", var='pathSeparator'),
+OE(["--context-format"], "Context format", var='contextFormat'),
+OE(["--success-code=N"], "Exit code to return on script success", var='successCode'),
+OE(["--failure-code=N"], "Exit code to return on script failure", var='failureCode'),
+OE(["--unknown-code=N"], "Exit code to return on bad configuration", var='unknownCode'),
+]))
+
+ usage.add(TableSection(
+ 'markup',
+ "Markup syntax",
+ """\
+The following markups are supported (NL means newline; WS means whitespace):
+""", [
+E("@# ... NL", "Line comment; remove everything including newline"),
+E("@* ... *", "Inline comment; remove everything inside"),
+E("@ WS", "Ignore whitespace; line continuation"),
+E("@@", "Literal @; @ is escaped (duplicated prefix)"),
+E("@' STRING '", "Replace with string literal contents"),
+E("@\" STRING \"", "Replace with string literal contents"),
+E("@''' STRING ... '''", "Replace with multiline string literal contents"),
+E("@\"\"\" STRING ... \"\"\"", "Replace with multiline string literal contents"),
+E("@` LITERAL `", "Write everything inside literally (no expansion)"),
+E("@( EXPRESSION )", "Evaluate expression and substitute with str"),
+E("@( TEST ? THEN )", "If test, evaluate then, otherwise do nothing"),
+E("@( TEST ? THEN ! ELSE )", "If test, evaluate then, otherwise evaluate else;\n"
+ "can be chained with repeated test/then/[else]"),
+E("@( TRY $ EXCEPT )", "Evaluate try expression, or except if it raises"),
+E("@ SIMPLE_EXPRESSION", "Evaluate simple expression and substitute;\n", ex="@x, @x.y, @f(a, b), @l[i], @f{...}, etc."),
+E("@$ EXPRESSION $ [DUMMY] $", "Evaluates to @$ EXPRESSION $ EXPANSION $"),
+E("@{ STATEMENTS }", "Statements are executed for side effects"),
+E("@[ CONTROL ]", "Control markups: if E; elif E; for N in E;\n"
+ "while E; try; except E as N; finally;\n"
+ "continue; break; else; defined N; def F(...);\n"
+ "end X"),
+E("@\\ ESCAPE_CODE", "A C-style escape sequence"),
+E("@^ CHAR DIACRITIC(S)", "A two-part diacritic sequence\n", ex="e' for an e with acute accent"),
+E("@| ICON", "A custom icon sequence\n", ex="'( for a single open curly quote"),
+E("@: EMOJI :", "Lookup emoji by name"),
+E("@% KEY NL", "Significator form of __KEY__ = None"),
+E("@% KEY WS VALUE NL", "Significator form of __KEY__ = VALUE"),
+E("@%! KEY NL", "Significator form of __KEY__ = \"\""),
+E("@%! KEY WS STRING NL", "Stringized significator form: __KEY__ = \"STRING\""),
+E("@%% KEY WS VALUE %% NL", "Multiline significator form"),
+E("@%%! KEY WS STRING %% NL", "Multiline stringized significator form"),
+E("@? NAME NL", "Set the current context name"),
+E("@! INTEGER NL", "Set the current context line number"),
+E("@< CONTENTS >", "Custom markup; meaning provided via callback"),
+]))
+
+ usage.add(TableSection(
+ 'escapes',
+ "Escape sequences",
+ """\
+Valid escape sequences are:
+""", [
+E("@\\0", "NUL, null", ord=0x0),
+E("@\\a", "BEL, bell", ord=0x7),
+E("@\\b", "BS, backspace", ord=0x8),
+E("@\\B{BIN}", "freeform binary code BIN", ex="{1000001} for A"),
+E("@\\dDDD", "three-digit decimal code DDD", ex="065 for A"),
+E("@\\D{DEC}", "freeform decimal code DEC", ex="{65} for A"),
+E("@\\e", "ESC, escape", ord=0x1b),
+E("@\\f", "FF, form feed", ord=0xc),
+E("@\\h", "DEL, delete", ord=0x7f),
+E("@\\k", "ACK, acknowledge", ord=0x6),
+E("@\\K", "NAK, negative acknowledge", ord=0x15),
+E("@\\n", "LF, linefeed; newline", ord=0xa),
+E("@\\N{NAME}", "Unicode character named NAME", ex="LATIN CAPITAL LETTER A"),
+E("@\\oOOO", "three-digit octal code OOO", ex="101 for A"),
+E("@\\O{OCT}", "freeform octal code OCT", ex="{101} for A"),
+E("@\\qQQQQ", "four-digit quaternary code QQQQ", ex="1001 for A"),
+E("@\\Q{QUA}", "freeform quaternary code QUA", ex="{1001} for A"),
+E("@\\r", "CR, carriage return", ord=0xd),
+E("@\\s", "SP, space", ord=0x20),
+E("@\\S", "NBSP, no-break space", ord=0xa0),
+E("@\\t", "HT, horizontal tab", ord=0x9),
+E("@\\uHHHH", "16-bit hexadecimal Unicode HHHH", ex="0041 for A"),
+E("@\\UHHHHHHHH", "32-bit hexadecimal Unicode HHHHHHHH", ex="00000041 for A"),
+E("@\\v", "VT, vertical tab", ord=0xb),
+E("@\\V{VS}", "VS, variation selector (1 .. 256)", ex="16 for emoji display"),
+E("@\\w", "VS15, variation selector 15; text display", ord=0xfe0e),
+E("@\\W", "VS16, variation selector 16; emoji display", ord=0xfe0f),
+E("@\\xHH", "8-bit hexadecimal code HH", ex="41 for A"),
+E("@\\X{HEX}", "freeform hexadecimal code HEX", ex="{41} for A"),
+E("@\\y", "SUB, substitution", ord=0x1a),
+E("@\\Y", "RC, replacement character", ord=0xfffd),
+E("@\\z", "EOT, end of transmission", ord=0x4),
+E("@\\Z", "ZWNBSP/BOM, zero-width no-break space/byte order mark", ord=0xfeff),
+E("@\\,", "THSP, thin space", ord=0x2009),
+E("@\\^C", "Control character C", ex="[ for ESC"),
+E("@\\^{NAME}", "Control character named NAME", ex="ESC"),
+E("@\\(", "Literal (", ord=0x28),
+E("@\\)", "Literal )", ord=0x29),
+E("@\\[", "Literal [", ord=0x5b),
+E("@\\]", "Literal ]", ord=0x5d),
+E("@\\{", "Literal {", ord=0x7b),
+E("@\\}", "Literal }", ord=0x7d),
+E("@\\<", "Literal <", ord=0x3c),
+E("@\\>", "Literal >", ord=0x3e),
+E("@\\\\", "Literal \\", ord=0x5c),
+E("@\\'", "Literal '", ord=0x27),
+E("@\\\"", "Literal \"", ord=0x22),
+E("@\\?", "Literal ?", ord=0x3f),
+]))
+
+ usage.add(TableSection(
+ 'environ',
+ "Environment variables",
+ """\
+The following environment variables are recognized (with corresponding
+command line arguments):
+""", [
+E(em.OPTIONS_ENV, "Specify additional options to be included"),
+E(em.CONFIG_ENV, "Specify configuration file(s) to load", arg="-c PATHS"),
+E(em.PREFIX_ENV, "Specify the default prefix", arg='-p PREFIX'),
+E(em.PSEUDO_ENV, "Specify name of pseudomodule", arg='-m NAME'),
+E(em.FLATTEN_ENV, "Flatten empy pseudomodule if defined", arg='-f'),
+E(em.RAW_ERRORS_ENV, "Show raw errors if defined", arg='-r'),
+E(em.INTERACTIVE_ENV, "Enter interactive mode if defined", arg='-i'),
+E(em.DELETE_ON_ERROR_ENV, "Delete output file on error", arg='-d'),
+E(em.NO_PROXY_ENV, "Do not install sys.stdout proxy if defined", arg='-n'),
+E(em.BUFFERING_ENV, "Buffer size (-1, 0, 1, or n)", arg='-b VALUE'),
+E(em.BINARY_ENV, "Open input file as binary (for Python 2.x Unicode)", arg='-u'),
+E(em.ENCODING_ENV, "Unicode both input and output encodings"),
+E(em.INPUT_ENCODING_ENV, "Unicode input encoding"),
+E(em.OUTPUT_ENCODING_ENV, "Unicode output encoding"),
+E(em.ERRORS_ENV, "Unicode both input and output error handlers"),
+E(em.INPUT_ERRORS_ENV, "Unicode input error handler"),
+E(em.OUTPUT_ERRORS_ENV, "Unicode output error handler"),
+]))
+
+ usage.add(TableSection(
+ 'pseudo',
+ "Pseudomodule attributes and functions",
+ """\
+The %s pseudomodule contains the following attributes and methods:
+""" % usage.config.pseudomoduleName, [
+E("version", "String representing EmPy version"),
+E("compat", "List of applied Python compatibility features"),
+E("executable", "The EmPy executable"),
+E("argv", "EmPy script name and command line arguments"),
+E("config", "The configuration for this interpreter"),
+E("ok", "Is the interpreter still active?"),
+E("error", "The last error to occur, or None"),
+E("__init__(**kwargs)", "The interpreter constructor"),
+E("__enter__/__exit__(...)", "Context manager support"),
+E("reset()", "Reset the interpreter state"),
+E("ready()", "Declare the interpreter ready"),
+E("shutdown()", "Shutdown the interpreter"),
+E("write(data)", "Write data to stream"),
+E("writelines(lines)", "Write a sequence of lines to stream"),
+E("flush()", "Flush the stream"),
+E("serialize(object)", "Write a string version of the object"),
+E("identify()", "Identify top context as name, line"),
+E("getContext()", "Return the current context"),
+E("newContext(...)", "Return a new context with name and counts"),
+E("pushContext(context)", "Push a context"),
+E("popContext()", "Pop the current context"),
+E("setContext(context)", "Replace the current context"),
+E("setContextName(name)", "Set the name of the current context"),
+E("setContextLine(line)", "Set the line number of the current context"),
+E("setContextColumn(column)", "Set the column number of the current context"),
+E("setContextData(...)", "Set any of the name, line, column number"),
+E("restoreContext(context)", "Replace the top context with an existing one"),
+E("removeFinalizers()", "Remove all finalizers"),
+E("appendFinalizer(finalizer)", "Append function to be called at shutdown"),
+E("prependFinalizer(finalizer)", "Prepend function to be called at shutdown"),
+E("getGlobals()", "Retrieve this interpreter's globals"),
+E("setGlobals(dict)", "Set this interpreter's globals"),
+E("updateGlobals(dict)", "Merge dictionary into interpreter's globals"),
+E("clearGlobals()", "Start globals over anew"),
+E("saveGlobals([deep])", "Save a copy of the globals"),
+E("restoreGlobals([pop])", "Restore the most recently saved globals"),
+E("include(file, [loc])", "Include filename or file-like object"),
+E("expand(string, [loc])", "Explicitly expand string and return"),
+E("defined(name, [loc])", "Find if the name is defined"),
+E("lookup(name, [loc])", "Lookup the variable name"),
+E("evaluate(expression, [loc])", "Evaluate the expression (and write?)"),
+E("execute(statements, [loc])", "Execute the statements"),
+E("single(source, [loc])", "Execute the expression or statement"),
+E("atomic(name, value, [loc])", "Perform an atomic assignment"),
+E("assign(name, value, [loc])", "Perform an arbitrary assignment"),
+E("significate(key, [value])", "Significate the given key, value pair"),
+E("quote(string)", "Quote prefixes in provided string and return"),
+E("escape(data)", "Escape EmPy markup in data and return"),
+E("flatten([keys])", "Flatten module contents to globals namespace"),
+E("getPrefix()", "Get current prefix"),
+E("setPrefix(char)", "Set new prefix"),
+E("stopDiverting()", "Stop diverting; data sent directly to output"),
+E("createDiversion(name)", "Create a diversion but do not divert to it"),
+E("retrieveDiversion(name, [def])", "Retrieve the actual named diversion object"),
+E("startDiversion(name)", "Start diverting to given diversion"),
+E("playDiversion(name)", "Recall diversion and then eliminate it"),
+E("replayDiversion(name)", "Recall diversion but retain it"),
+E("dropDiversion(name)", "Drop diversion"),
+E("playAllDiversions()", "Stop diverting and play all diversions"),
+E("replayAllDiversions()", "Stop diverting and replay all diversions"),
+E("dropAllDiversions()", "Stop diverting and drop all diversions"),
+E("getCurrentDiversionName()", "Get the name of the current diversion"),
+E("getAllDiversionNames()", "Get a sorted sequence of diversion names"),
+E("isExistingDiversionName(name)", "Is this the name of a diversion?"),
+E("getFilter()", "Get the first filter in the current chain"),
+E("getLastFilter()", "Get the last filter in the current chain"),
+E("getFilterCount()", "Get the number of filters in current chain"),
+E("resetFilter()", "Reset filter; no filtering"),
+E("setFilter(filter...)", "Install new filter(s), replacing any chain"),
+E("prependFilter(filter)", "Prepend filter to beginning of current chain"),
+E("appendFilter(filter)", "Append a filter to end of current chain"),
+E("setFilterChain(filters)", "Install a new filter chain"),
+E("areHooksEnabled()", "Return whether or not hooks are enabled"),
+E("enableHooks()", "Enable hooks (default)"),
+E("disableHooks()", "Disable hook invocation"),
+E("getHooks()", "Get all the hooks"),
+E("appendHook(hook)", "Append the given hook"),
+E("prependHook(hook)", "Prepend the given hook"),
+E("removeHook(hook)", "Remove an already-registered hook"),
+E("clearHooks()", "Clear all hooks"),
+E("invokeHook(_name, ...)", "Manually invoke hook"),
+E("hasCallback()", "Is there a custom callback?"),
+E("getCallback()", "Get custom callback"),
+E("registerCallback(callback)", "Register custom callback"),
+E("deregisterCallback()", "Deregister custom callback"),
+E("invokeCallback(contents)", "Invoke the custom callback directly"),
+E("defaultHandler(t, e, tb)", "The default error handler"),
+E("getHandler()", "Get the current error handler (or None)"),
+E("setHandler(handler, [eoe])", "Set the error handler"),
+E("invokeHandler(t, e, tb)", "Manually invoke the error handler"),
+E("initializeEmojiModules(names)", "Initialize the emoji modules"),
+E("getEmojiModule(name)", "Get an abstracted emoji module"),
+E("getEmojiModuleNames()", "Return the list of emoji module names"),
+E("substituteEmoji(text)", "Do an emoji substitution"),
+]))
+
+ usage.add(TableSection(
+ 'constructor',
+ "Keyword arguments for the Interpreter constructor",
+ """\
+The following keyword arguments for the Interpreter constructor are supported
+(defaults in brackets). All arguments have meaningful defaults:
+""", [
+E("argv", "The system arguments to use ['<->']"),
+E("callback", "A custom callback to register [None]"),
+E("config", "The configuration object [default]"),
+E("dispatcher", "Dispatch errors or raise to caller? [True]"),
+E("evalFunc", "Function to evaluate expressions [eval]"),
+E("execFunc", "Function to execute statements [exec]"),
+E("executable", "The path to the EmPy executable [\".../em.py\"]"),
+E("filespec", "A 3-tuple of the input filename, mode, and buffering [None]"),
+E("filters", "The list of filters to install [[]]"),
+E("globals", "The globals dictionary to use [{}]"),
+E("handler", "The error handler to use [default]"),
+E("hooks", "The list of hooks to install [[]]"),
+E("ident", "The identifier for the interpreter [None]"),
+E("immediately", "Declare the interpreter ready after initialization? [True]"),
+E("input", "The input file to use for interactivity [sys.stdin]"),
+E("output", "The output file to use [sys.stdout]"),
+E("root", "The root interpreter context filename ['<root>']"),
+E("serializerFunc", "Function to serialize objects [str]"),
+]))
+
+ usage.add(ConfigSection(
+ 'variables',
+ "Configuration variable attributes",
+ """\
+The following configuration variable attributes are supported (defaults in
+brackets, with dictionaries being summarized with their length):
+""",
+ usage.config))
+
+ usage.add(TableSection(
+ 'methods',
+ "Configuration methods",
+ """\
+The configuration instance contains the following methods:
+""", [
+E("initialize()", "Initialize the instance"),
+E("shutdown()", "Shutdown the instance"),
+E("isInitialize()", "Is this configuration initialized?"),
+E("pauseIfRequired()", "Pause if required"),
+E("check(in, out)", "Check file settings"),
+E("has(name)", "Is this variable defined?"),
+E("get(name[, default])", "Get this variable value"),
+E("set(name, value)", "Set this variable"),
+E("update(**kwargs)", "Update with dictionary"),
+E("clone([deep])", "Clone (optionally deep) this configuration"),
+E("run(statements)", "Run configuration commands"),
+E("load(filename, [required])", "Load configuration file"),
+E("path(filename, [required])", "Load configuration file(s) path"),
+E("hasEnvironment(name)", "Is this environment variable defined?"),
+E("environment(name, ...)", "Get the enviroment variable value"),
+E("hasDefaultPrefix()", "Is the prefix the default?"),
+E("hasFullBuffering()", "Is the buffering set to full?"),
+E("hasNoBuffering()", "Is the buffering set to none?"),
+E("hasLineBuffering()", "Is the buffering set to line?"),
+E("hasFixedBuffering()", "Is the buffering set to fixed?"),
+E("createFactory([tokens])", "Create token factory"),
+E("adjustFactory()", "Adjust token factory for non-default prefix"),
+E("getFactory([tokens], [force])", "Get a token factory"),
+E("restFactory()", "Clear the current token factory"),
+E("hasBinary()", "Is binary (Unicode) support enabled?"),
+E("enableBinary(...)", "Enable binary (Unicode) support"),
+E("disableBinary()", "Disable binary (Unicode) support"),
+E("isDefaultEncodingErrors()", "Is encoding/errors the default?"),
+E("getDefaultEncoding()", "Get the default file encoding"),
+E("open(filename, [mode], ...)", "Open a file"),
+E("significatorReString()", "Regular expression string for significators"),
+E("significatorRe()", "Regular expression pattern for significators"),
+E("significatorFor(key)", "Significator variable name for key"),
+E("setContextFormat(format)", "Set the context format"),
+E("renderContext(context)", "Render context using format"),
+E("calculateIconsSignature()", "Calculate icons signature"),
+E("signIcons()", "Sign the icons dictionary"),
+E("transmogrifyIcons()", "Process the icons dictionary"),
+E("validateIcons()", "Process the icons dictionaray if necessary"),
+E("intializeEmojiModules([names])", "Initialize emoji module support"),
+E("substituteEmoji(text)", "Substitute emoji"),
+E("isSuccessCode(code)", "Does this exit code indicate success?"),
+E("isExitError(error)", "Is this exception instance an exit?"),
+E("errorToExitCode(error)", "Return exit code for exception instance"),
+E("isNotAnError(error)", "Is this exception instance not an error?"),
+E("formatError(error[, p, s])", "Render an error string from instance"),
+]))
+
+ usage.add(TableSection(
+ 'hooks',
+ "Hook methods",
+ """\
+The following hook methods are supported. The return values are ignored except
+for the `pre...` methods which, when they return a true value, signal that the
+following token handling should be skipped:
+""", [
+E("atInstallProxy(proxy, new)", "Proxy being installed"),
+E("atUninstallProxy(proxy, new)", "Proxy being uninstalled"),
+E("atStartup()", "Interpreter started up"),
+E("atReady()", "Interpreter ready"),
+E("atFinalize()", "Interpreter finalizing"),
+E("atShutdown()", "Interpreter shutting down"),
+E("atParse(scanner, loc)", "Interpreter parsing"),
+E("atToken(token)", "Interpreter expanding token"),
+E("atHandle(info, fatal, contexts)", "Interpreter encountered error"),
+E("atInteract()", "Interpreter going interactive"),
+E("pushContext(context)", "Context being pushed"),
+E("popContext(context)", "Context was popped"),
+E("setContext(context)", "Context was set or modified"),
+E("restoreContext(context)", "Context was restored"),
+E("prePrefix()", "Pre prefix token"),
+E("preWhitespace()", "Pre whitespace token"),
+E("preString(string)", "Pre string literal token"),
+E("preLineComment(comment)", "Pre line comment"),
+E("postLineComment()", "Post line comment"),
+E("preInlineComment(comment)", "Pre inline comment"),
+E("postInlineComment()", "Post inline comment"),
+E("preBackquote(literal)", "Pre backquote literal"),
+E("postBackquote()", "Post backquote literal"),
+E("preSignificator(key, value, s)", "Pre significator"),
+E("postSignificator()", "post significator"),
+E("preContextName(name)", "Pre context name"),
+E("postContextName()", "Post context name"),
+E("preContextLine(line)", "Pre context line"),
+E("postContextLine()", "Post context line"),
+E("preExpression(pairs, except, loc)", "Pre expression"),
+E("postExpression(result)", "Post expression"),
+E("preSimple(code, sub, loc)", "Pre simple expression"),
+E("postSimple(result)", "Post simple expression"),
+E("preInPlace(code, loc)", "Pre in-place expression"),
+E("postInPlace(result)", "Post in-place expression"),
+E("preStatement(code, loc)", "Pre statement"),
+E("postStatement()", "Post statement"),
+E("preControl(type, rest, loc)", "Pre control"),
+E("postControl()", "Post control"),
+E("preEscape(code)", "Pre escape"),
+E("postEscape()", "Post escape"),
+E("preDiacritic(code)", "Pre diacritic"),
+E("postDiacritic()", "Post diacritic"),
+E("preIcon(code)", "Pre icon"),
+E("postIcon()", "Post icon"),
+E("preEmoji(name)", "Pre emoji"),
+E("postEmoji()", "Post emoji"),
+E("preCustom(contents)", "Pre custom"),
+E("postCustom()", "Post custom"),
+E("beforeProcess(command, n)", "Before command processing"),
+E("afterProcess()", "After command processing"),
+E("beforeInclude(file, loc, name)", "Before file inclusion"),
+E("afterInclude()", "After file inclusion"),
+E("beforeExpand(string, loc, name)", "Before expand call"),
+E("afterExpand(result)", "After expand call"),
+E("beforeTokens(tokens, loc)", "Before processing tokens"),
+E("afterTokens(result)", "After processing tokens"),
+E("beforeFileLines(file, loc)", "Before reading file by lines"),
+E("afterFileLines()", "After reading file by lines"),
+E("beforeFileChunks(file, loc)", "Before reading file by chunks"),
+E("afterFileChunks()", "After reading file by chunks"),
+E("beforeFileFull(file, loc)", "Before reading file in full"),
+E("afterFilFull()", "After reading file in full"),
+E("beforeString(string, loc)", "Before processing string"),
+E("afterString()", "After processing string"),
+E("beforeQuote(string)", "Before quoting string"),
+E("afterQuote()", "After quoting string"),
+E("beforeEscape(string)", "Before escaping string"),
+E("afterEscape()", "After escaping string"),
+E("beforeSignificate(key, value, loc)", "Before significator"),
+E("afterSignificate()", "After significator"),
+E("beforeCallback(contents)", "Before custom callback"),
+E("afterCallback()", "Before custom callback"),
+E("beforeAtomic(name, value, loc)", "Before atomic assignment"),
+E("afterAtomic()", "After atomic assignment"),
+E("beforeMulti(names, values, loc)", "Before complex assignment"),
+E("afterMulti()", "After complex assignment"),
+E("beforeImport(name, loc)", "Before module import"),
+E("afterImport()", "After module import"),
+E("beforeFunctional(code, lists, loc)", "Before functional expression"),
+E("afterFunctional(result)", "After functional expression"),
+E("beforeEvaluate(code, loc, write)", "Before expression evaluation"),
+E("afterEvaluate(result)", "After expression evaluation"),
+E("beforeExecute(statements, loc)", "Before statement execution"),
+E("afterExecute()", "After statement execution"),
+E("beforeSingle(source, loc)", "Before single execution"),
+E("afterSingle(result)", "After single execution"),
+E("beforeFinalizer(final)", "Before finalizer processing"),
+E("afterFinalizer()", "After finalizer processing"),
+]))
+
+ usage.add(MappingSection(
+ 'named',
+ "Named escapes",
+ "The following named escapes (control codes) (`@\\^{...}`) are supported:\n",
+ usage.config.controls))
+
+ usage.add(MappingSection(
+ 'diacritics',
+ "Diacritic combiners",
+ "The following diacritic combining characters (`@^C...`) are supported:\n",
+ usage.config.diacritics))
+
+ usage.add(MappingSection(
+ 'icons',
+ "Icons",
+ "The following icon sequences (`@|...`) are supported:\n",
+ usage.config.icons,
+ NameEntry))
+
+ usage.add(MappingSection(
+ 'emojis',
+ "Custom emojis",
+ "The following custom emojis have been made available:\n",
+ usage.config.emojis))
+
+ usage.add(HelpSection(
+ 'topics',
+ "This list of topics",
+ """\
+Need more help? Add more -h options (-hh, -hhh) for more help. Use -H <topic>
+for help on a specific topic, or specify a comma-separated list of topics. Try
+`default` (-h) for default help, `more` (-hh) for more common topics, `all`
+(-hhh) for all help topics, or `topics` for this list. Use -V for version
+information, -W for version and system information, or -Z for all debug
+details. Available topics:
+""",
+ usage))
+
+ return payload
+
+#
+# main
+#
+
+def main():
+ topics = sys.argv[1:]
+ if not topics:
+ topics = ['default']
+ usage = Usage()
+ usage.show(topics)
+
+if __name__ == '__main__': main()
--- /dev/null
+#!/usr/bin/env python3
+
+"""
+Optional support classes for EmPy.
+"""
+
+#
+# imports
+#
+
+import os
+import platform
+import sys
+
+import em
+
+#
+# Filter ...
+#
+
+class Filter(em.Root):
+
+ """An abstract filter."""
+
+ # Meta methods.
+
+ def follow(self):
+ """Return the next filter/file-like object in the sequence, or
+ None."""
+ raise NotImplementedError
+
+ def isAttached(self):
+ """Is a filter/file already attached to this one?"""
+ raise NotImplementedError
+
+ def attach(self, filter):
+ """Attach a filter to this one."""
+ raise NotImplementedError
+
+ def detach(self):
+ """Detach a filter from its sink."""
+ raise NotImplementedError
+
+ def last(self):
+ """Find the last filter in this chain."""
+ this, last = self, None
+ while this is not None:
+ last = this
+ this = this.follow()
+ return last
+
+ def _flush(self):
+ """The _flush method should always flush the underlying sinks."""
+ raise NotImplementedError
+
+ # File-like methods.
+
+ def write(self, data):
+ """The write method must be implemented."""
+ raise NotImplementedError
+
+ def writelines(self, lines):
+ """Write lines. This should not need to be overriden
+ for most filters."""
+ for line in lines:
+ self.write(line)
+
+ def flush(self):
+ """The flush method can be overridden."""
+ self._flush()
+
+ def close(self):
+ """The close method must be implemented."""
+ raise NotImplementedError
+
+
+class NullFilter(Filter):
+
+ """A filter that never sends any output to its sink."""
+
+ def follow(self): return None
+ def isAttached(self): return False
+ def attach(self, filter): pass
+ def detach(self): pass
+
+ def write(self, data): pass
+ def close(self): pass
+
+
+class ConcreteFilter(Filter):
+
+ """A concrete filter has a single sink."""
+
+ def __init__(self):
+ if self.__class__ is ConcreteFilter:
+ raise NotImplementedError
+ self.sink = None
+
+ def follow(self):
+ """Return the next filter/file-like object in the sequence, or None."""
+ return self.sink
+
+ def isAttached(self):
+ """Is a filter/file already attached to this one?"""
+ return self.sink is not None
+
+ def attach(self, filter):
+ """Attach a filter to this one."""
+ if self.sink is not None:
+ # If one's already attached, detach it first.
+ self.detach()
+ self.sink = filter
+
+ def detach(self):
+ """Detach a filter from its sink."""
+ self.flush()
+ self._flush() # do a guaranteed flush to just to be safe
+ self.sink = None
+
+ def last(self):
+ """Find the last filter in this chain."""
+ this, last = self, None
+ while this is not None:
+ last = this
+ this = this.follow()
+ return last
+
+ def _flush(self):
+ """This method should flush the concrete sink and should
+ not be overridden."""
+ self.sink.flush()
+
+ def flush(self):
+ self._flush()
+
+ def close(self):
+ """Close the filter. Do an explicit flush first, then close the
+ sink."""
+ self.flush()
+ self.sink.close()
+
+
+class IdentityFilter(ConcreteFilter):
+
+ """A filter which just sends any output straight through to its sink."""
+
+ def write(self, data):
+ self.sink.write(data)
+
+
+class FunctionFilter(ConcreteFilter):
+
+ """A filter that works simply by pumping its input through a
+ function which maps strings into strings."""
+
+ def __init__(self, function):
+ super(FunctionFilter, self).__init__()
+ self.function = function
+
+ def write(self, data):
+ self.sink.write(self.function(data))
+
+
+class IndentFilter(ConcreteFilter):
+
+ """Automatically indent a fixed number of spaces after every
+ newline."""
+
+ default = ' '
+
+ def __init__(self, indent):
+ super(IndentFilter, self).__init__()
+ if isinstance(indent, int):
+ self.indent = self.default * indent
+ else:
+ self.indent = indent
+
+ def write(self, data):
+ self.sink.write(data.replace('\n', '\n' + self.indent))
+
+
+class StringFilter(ConcreteFilter):
+
+ """A filter that takes a translation string (256 characters) and
+ filters any incoming data through it."""
+
+ def __init__(self, table):
+ if not (isinstance(table, (em.bytes, em.str)) and len(table) == 256):
+ raise em.FilterError("table must be 256-character string")
+ super(StringFilter, self).__init__()
+ self.table = table
+
+ def write(self, data):
+ self.sink.write(data.translate(self.table))
+
+
+class BufferedFilter(ConcreteFilter):
+
+ """A buffered filter is one that doesn't modify the source data
+ sent to the sink, but instead holds it for a time. The standard
+ variety only sends the data along when it receives a flush
+ command."""
+
+ def __init__(self):
+ super(BufferedFilter, self).__init__()
+ self.buffer = ''
+
+ def write(self, data):
+ self.buffer += data
+
+ def flush(self):
+ if self.buffer:
+ self.sink.write(self.buffer)
+ self._flush()
+
+
+class SizeBufferedFilter(BufferedFilter):
+
+ """A size-buffered filter only in fixed size chunks (excepting the
+ final chunk)."""
+
+ def __init__(self, bufferSize=em.Configuration.defaultBuffering):
+ super(SizeBufferedFilter, self).__init__()
+ assert bufferSize > 0
+ self.bufferSize = bufferSize
+
+ def write(self, data):
+ BufferedFilter.write(self, data)
+ while len(self.buffer) > self.bufferSize:
+ chunk, self.buffer = self.buffer[:self.bufferSize], self.buffer[self.bufferSize:]
+ self.sink.write(chunk)
+
+
+class FullyBufferedFilter(BufferedFilter):
+
+ """A maximally-buffered filter only lets its data through on the final
+ close. It ignores flushes."""
+
+ def flush(self): pass
+
+ def close(self):
+ if self.buffer:
+ BufferedFilter.flush(self)
+ self.sink.close()
+
+
+class DelimitedFilter(BufferedFilter):
+
+ """A delimited filter only lets data through when it sees
+ whole lines."""
+
+ def __init__(self, delimiter):
+ super(DelimitedFilter, self).__init__()
+ self.delimiter = delimiter
+
+ def write(self, data):
+ BufferedFilter.write(self, data)
+ chunks = self.buffer.split(self.delimiter)
+ for chunk in chunks[:-1]:
+ self.sink.write(chunk + self.delimiter)
+ self.buffer = chunks[-1]
+
+
+class LineDelimitedFilter(DelimitedFilter):
+
+ """A line-delimited filter only lets data through when it sees
+ whole lines."""
+
+ def __init__(self, delimiter=em.NEWLINE_CHAR):
+ super(LineDelimitedFilter, self).__init__(delimiter)
+
+ def write(self, data):
+ DelimitedFilter.write(self, data)
+ chunks = self.buffer.split(self.delimiter)
+ for chunk in chunks[:-1]:
+ self.sink.write(chunk + self.delimiter)
+ self.buffer = chunks[-1]
+
+
+class DroppingFilter(ConcreteFilter):
+
+ """A filter which drops any chunks that match the provided list of
+ chunks to ignore."""
+
+ def __init__(self, droppings):
+ super(DroppingFilter, self).__init__()
+ self.droppings = droppings
+
+ def write(self, data):
+ if data not in self.droppings:
+ self.sink.write(data)
+
+
+class SplittingFilter(Filter):
+
+ """A filter that splits the output stream n ways."""
+
+ def __init__(self, sinks):
+ super(SplittingFilter, self).__init__()
+ self.sinks = sinks[:]
+
+ def _flush(self):
+ for sink in self.sinks:
+ sink._flush()
+
+ def write(self, data):
+ for sink in self.sinks:
+ sink.write(data)
+
+ def flush(self):
+ for sink in self.sinks:
+ sink.flush()
+
+ def close(self):
+ for sink in self.sinks:
+ sink.close()
+
+#
+# Container
+#
+
+class Container:
+
+ """A container contains a reference to an interpreter. This is the
+ base class of several support classes."""
+
+ def __init__(self, interp=None):
+ self.interp = None
+ if interp is not None:
+ self.register(interp)
+
+ def register(self, interp):
+ self.interp = interp
+
+ def deregister(self, interp):
+ if interp is not self.interp:
+ raise em.ConsistencyError("container not associated with this interpeter")
+ self.interp = None
+
+ def push(self):
+ self.interp.push()
+
+ def pop(self):
+ self.interp.pop()
+
+#
+# AbstractHook, Hook ...
+#
+
+class AbstractHook(Container):
+
+ """An abstract base class for implementing hooks. All
+ hook invocations are not present. (Use this if you plan
+ to systematically handle all calls with something like
+ __getattr__.)"""
+
+ pass
+
+
+class Hook(AbstractHook):
+
+ """The base class for implementing hooks. All hook
+ invocations are present and no-ops."""
+
+ # Override these in a subclass.
+
+ def test(self): pass # used in tests
+
+ # Events
+
+ def atInstallProxy(self, proxy, new): pass
+ def atUninstallProxy(self, proxy, done): pass
+
+ def atStartup(self): pass
+ def atReady(self): pass
+ def atFinalize(self): pass
+ def atShutdown(self): pass
+ def atParse(self, scanner, locals): pass
+ def atToken(self, token): pass
+ def atHandle(self, info, fatal, contexts): pass
+ def atInteract(self): pass
+
+ # Contexts
+
+ def pushContext(self, context): pass
+ def popContext(self, context): pass
+ def setContext(self, context): pass
+ def restoreContext(self, context): pass
+
+ # Tokens
+
+ def preLineComment(self, comment): pass
+
+ def preInlineComment(self, comment): pass
+
+ def preWhitespace(self, whitespace): pass
+
+ def prePrefix(self): pass
+
+ def preString(self, string): pass
+ def postString(self): pass
+
+ def preBackquote(self, literal): pass
+ def postBackquote(self, result): pass
+
+ def preSignificator(self, key, value, stringized): pass
+ def postSignificator(self): pass
+
+ def preContextName(self, name): pass
+ def postContextName(self, context): pass
+
+ def preContextLine(self, line): pass
+ def postContextLine(self, context): pass
+
+ def preExpression(self, pairs, except_, locals): pass
+ def postExpression(self, result): pass
+
+ def preSimple(self, code, subtokens, locals): pass
+ def postSimple(self, result): pass
+
+ def preInPlace(self, code, locals): pass
+ def postInPlace(self, result): pass
+
+ def preStatement(self, code, locals): pass
+ def postStatement(self): pass
+
+ def preControl(self, type, rest, locals): pass
+ def postControl(self): pass
+
+ def preEscape(self, code): pass
+ def postEscape(self): pass
+
+ def preDiacritic(self, code): pass
+ def postDiacritic(self): pass
+
+ def preIcon(self, code): pass
+ def postIcon(self): pass
+
+ def preEmoji(self, name): pass
+ def postEmoji(self): pass
+
+ def preCustom(self, contents): pass
+ def postCustom(self, result): pass
+
+ # Interpreter actions
+
+ def beforeProcess(self, command, n): pass
+ def afterProcess(self): pass
+
+ def beforeInclude(self, file, locals, name): pass
+ def afterInclude(self): pass
+
+ def beforeExpand(self, string, locals, name, dispatcher): pass
+ def afterExpand(self, result): pass
+
+ def beforeFileLines(self, file, locals, dispatcher): pass
+ def afterFileLines(self): pass
+
+ def beforeFileChunks(self, file, bufferSize, locals, dispatcher): pass
+ def afterFileChunks(self): pass
+
+ def beforeFileFull(self, file, locals, dispatcher): pass
+ def afterFileFull(self): pass
+
+ def beforeString(self, string, locals, dispatcher): pass
+ def afterString(self): pass
+
+ def beforeTokens(self, tokens, locals): pass
+ def afterTokens(self, result): pass
+
+ def beforeQuote(self, string): pass
+ def afterQuote(self, result): pass
+
+ def beforeEscape(self, string, more): pass
+ def afterEscape(self, result): pass
+
+ def beforeSignificate(self, key, value, locals): pass
+ def afterSignificate(self): pass
+
+ def beforeCallback(self, contents): pass
+ def afterCallback(self, result): pass
+
+ def beforeAtomic(self, name, value, locals): pass
+ def afterAtomic(self): pass
+
+ def beforeMulti(self, names, values, locals): pass
+ def afterMulti(self): pass
+
+ def beforeImport(self, name, locals): pass
+ def afterImport(self): pass
+
+ def beforeClause(self, catch, locals): pass
+ def afterClause(self, exception, variable): pass
+
+ def beforeDictionary(self, code, locals): pass
+ def afterDictionary(self, result): pass
+
+ def beforeSerialize(self, expression, locals): pass
+ def afterSerialize(self): pass
+
+ def beforeDefined(self, name, locals): pass
+ def afterDefined(self, result): pass
+
+ def beforeLiteral(self, text, locals): pass
+ def afterLiteral(self, result): pass
+
+ def beforeFunctional(self, code, lists, locals): pass
+ def afterFunctional(self, result): pass
+
+ def beforeEvaluate(self, expression, locals, replace): pass
+ def afterEvaluate(self, result): pass
+
+ def beforeExecute(self, statements, locals): pass
+ def afterExecute(self): pass
+
+ def beforeSingle(self, source, locals): pass
+ def afterSingle(self, result): pass
+
+ def beforeFinalizer(self, finalizer): pass
+ def afterFinalizer(self): pass
+
+#
+# Callback
+#
+
+class Callback(Container):
+
+ """A root class for any callback utilities."""
+
+ pass
+
+#
+# Handler
+#
+
+class Handler(Container):
+
+ """A root class for any error handler."""
+
+ pass
+
+#
+# Finalizer
+#
+
+class Finalizer(Container):
+
+ """A root class for a finalizer."""
+
+ pass
+
+#
+# Document
+#
+
+class Document(em.Root):
+
+ """A representation of an individual EmPy document, as used by a
+ processor."""
+
+ def __init__(self, ident, filename):
+ self.ident = ident
+ self.filename = filename
+ self.significators = {}
+
+#
+# Processor
+#
+
+class Processor(em.Root):
+
+ """An entity which is capable of processing a hierarchy of EmPy
+ files and building a dictionary of document objects associated
+ with them describing their significator contents."""
+
+ defaultExtensions = ['.em']
+
+ def __init__(self, config, factory=Document):
+ self.config = config
+ self.factory = factory
+ self.documents = {}
+
+ def identifier(self, pathname, filename): return filename
+
+ def clear(self):
+ self.documents = {}
+
+ def scan(self, basename, extensions=None):
+ if extensions is None:
+ extensions = self.defaultExtensions
+ if isinstance(extensions, (em.bytes, em.str)):
+ extensions = [extensions]
+ def _noCriteria(x):
+ return True
+ def _extensionsCriteria(pathname, extensions=extensions):
+ if extensions:
+ for extension in extensions:
+ if pathname[-len(extension):] == extension:
+ return True
+ return False
+ else:
+ return True
+ self.directory(basename, _noCriteria, _extensionsCriteria, None)
+ self.postprocess()
+
+ def postprocess(self):
+ pass
+
+ def directory(self, basename, dirCriteria, fileCriteria, depth=None):
+ if depth is not None:
+ if depth <= 0:
+ return
+ else:
+ depth -= 1
+ filenames = os.listdir(basename)
+ for filename in filenames:
+ pathname = os.path.join(basename, filename)
+ if os.path.isdir(pathname):
+ if dirCriteria(pathname):
+ self.directory(pathname, dirCriteria, fileCriteria, depth)
+ elif os.path.isfile(pathname):
+ if fileCriteria(pathname):
+ documentID = self.identifier(pathname, filename)
+ document = self.factory(documentID, pathname)
+ self.file(document, open(pathname))
+ self.documents[documentID] = document
+
+ def file(self, document, file):
+ while True:
+ line = file.readline()
+ if not line:
+ break
+ self.line(document, line)
+
+ def line(self, document, line):
+ significatorRe = re.compile(self.config.significatorReString())
+ match = significatorRe.search(line)
+ if match:
+ key, valueS = match.groups()
+ valueS = valueS.strip()
+ if valueS:
+ value = eval(valueS)
+ else:
+ value = None
+ document.significators[key] = value
+
+#
+# Details
+#
+
+class Details(em.Root):
+
+ """Gather details on a running Python system for debugging
+ purposes."""
+
+ releaseFilenames = ['/etc/os-release', '/usr/lib/os-release']
+ delimiter = '/'
+
+ def __init__(self, useSanitization=False):
+ self.useSanitization = useSanitization
+ self.data = {}
+ self._system = None
+ self._os = None
+ self._machine = None
+ self._implementation = None
+ self._version = None
+ self._framework = None
+
+ def __contains__(self, key):
+ return key in self.data
+
+ def __getitem__(self, key):
+ return self.data[key]
+
+ def __iter__(self):
+ items = list(self.items())
+ items.sort()
+ return iter(items)
+
+ def empty(self):
+ return len(self.data) == 0
+
+ # System/OS information.
+
+ def transformName(self, value, pairs, defaultFormat='[%s]', blank='?'):
+ """Find the prefix of the value in the pairs and return
+ the resulting name."""
+ if not value:
+ return blank
+ for prefix, name in pairs:
+ if value.startswith(prefix):
+ return name
+ return defaultFormat % value
+
+ def getSystemName(self):
+ """Get a nice name for the system this interpreter is
+ running on. Cached."""
+ if self._system is None:
+ self._system = platform.system()
+ assert self._system is not None
+ return self._system
+
+ def getOSName(self):
+ """Get a nice name for the OS this interpreter is
+ running on. Cached."""
+ if self._os is None:
+ PAIRS = [
+ ('posix', 'POSIX'),
+ ('nt', 'NT'),
+ ('java', 'Java'),
+ ]
+ self._os = self.transformName(os.name, PAIRS)
+ assert self._os is not None
+ return self._os
+
+ # Python information.
+
+ def getPythonImplementation(self):
+ """Get the name of this implementation. Cached."""
+ if self._implementation is None:
+ DEFAULT = 'CPython'
+ try:
+ self._implementation = platform.python_implementation()
+ except AttributeError:
+ # If the module does not contain the function, then it's old
+ # enough that we're surely the default. Fall through.
+ pass
+ if not self._implementation:
+ self._implementation = DEFAULT
+ assert self._implementation is not None
+ return self._implementation
+
+ def getPythonVersion(self):
+ """Get the version of Python. Cached."""
+ if self._version is None:
+ self._version = platform.python_version()
+ return self._version
+
+ def getMachineType(self):
+ """Get the machine name. Cached."""
+ if self._machine is None:
+ self._machine = platform.machine()
+ if not self._machine:
+ self._machine = '?'
+ assert self._machine is not None
+ return self._machine
+
+ def getFramework(self):
+ """Get the framework and version this interpreter is
+ running under as a 2-tuple, or None. Cached."""
+ if self._framework is None:
+ implementation = self.getPythonImplementation()
+ if implementation == 'PyPy':
+ # The PyPy version is in the second line of the version string.
+ lines = sys.version.split('\n')
+ second = lines[1]
+ if second.startswith('['):
+ second = second[1:]
+ fields = second.split()
+ self._framework = 'PyPy', fields[1]
+ elif implementation == 'Jython':
+ from java.lang import System
+ self._framework = 'JDK', System.getProperty('java.version')
+ elif implementation == 'IronPython':
+ from System import Environment
+ self._framework = '.NET', Environment.Version
+ return self._framework
+
+ # Details.
+
+ def sanitize(self, suffix):
+ """Normalize this key suffix if necessary."""
+ if self.useSanitization:
+ if '_' in suffix:
+ words = suffix.split('_')
+ for i in range(len(words)):
+ if i == 0:
+ words[i] = words[i].lower()
+ else:
+ words[i] = words[i].capitalize()
+ suffix = ''.join(words)
+ if suffix.isupper():
+ suffix = suffix.lower()
+ if suffix[0].isupper():
+ suffix = suffix[0].lower() + suffix[1:]
+ return suffix
+
+ def key(self, prefix, suffix):
+ """Make a key out of this prefix and suffix."""
+ if prefix and suffix:
+ return prefix + self.delimiter + self.sanitize(suffix)
+ elif prefix:
+ return prefix
+ else: # if suffix:
+ return self.normalize(suffix)
+
+ def has(self, prefix, suffix):
+ """Is this key present?"""
+ return self.key(prefix, suffix) in self.data
+
+ def get(self, prefix, suffix, default=None):
+ """Get the value for this key."""
+ key = self.key(prefix, suffix)
+ if key in self:
+ return self.data[key]
+ else:
+ return default
+
+ def set(self, prefix, suffix, value):
+ """Set a key/value pair."""
+ self.data[self.key(prefix, suffix)] = value
+
+ def wrap(self, prefix, suffixes, func):
+ """Replace an existing entry by passing it through a
+ function."""
+ if not isinstance(suffixes, tuple):
+ suffixes = (suffixes,)
+ for suffix in suffixes:
+ key = self.key(prefix, suffix)
+ if key in self.data:
+ self.data[key] = func(self.data[key])
+
+ def accumulate(self, prefix, suffixes, object, name,
+ args=None, attr=None, func=None, kwargs=None, delim='/'):
+ """Accumulate the results of a method or attribute in a
+ dictionary. If the argument is None, just return the
+ attribute; if not, treat it as a function and call it
+ with the args and kwargs. If attr is not None, access
+ that named attribute on the result before returning. If
+ func is not None, pass the result through the function
+ before storing."""
+ assert name is not None
+ if prefix is None:
+ prefix = ''
+ result = getattr(object, name, None)
+ if result is None:
+ return
+ error = None
+ if not isinstance(suffixes, tuple):
+ suffixes = (suffixes,)
+ try:
+ if args is not None:
+ # It's a function call.
+ if kwargs is None:
+ kwargs = {}
+ result = result(*args, **kwargs)
+ if result is None:
+ return
+ if not isinstance(result, tuple):
+ # If it's not a tuple, make it one for uniformity.
+ result = (result,)
+ if len(suffixes) == 1 and len(result) > 1:
+ # If we have only one key but multiple values, then it's a
+ # single key with a value that's a tuple. Join up the tuple
+ # with the delimiter.
+ result = (delim.join(result),)
+ for suffix, value in zip(suffixes, result):
+ # Now iterate over the suffixes/values:
+ if suffix is None:
+ # Skip suffixes that are None.
+ continue
+ if attr is not None:
+ # We want an attribute of it.
+ value = getattr(value, attr)
+ if func is not None:
+ # If there's a function wrapper, call it.
+ value = func(value)
+ assert suffix not in self.data
+ self.set(prefix, suffix, value)
+ except:
+ # Some weird things can happen when calling/accessing the result:
+ #
+ # - Jython 2.5 raises an internal AttributeError when accessing
+ # platform.architecture.
+ # - IronPython 2.7 raises an internal NotImplementedError when
+ # calling platform.architecture.
+ # - Some older versions of IronPython 2.7 raise an ImportError when
+ # calling platform.platform which is then bizarrely reported as a
+ # TypeError with no traceback by the executive.
+ #
+ # Set the appropriate values with a question mark and the name of
+ # the exception which occurred to make it clear what happened.
+ type, error, traceback = sys.exc_info()
+ value = '?' + error.__class__.__name__
+ for suffix in suffixes:
+ self.set(prefix, suffix, value)
+
+ # Details.
+
+ def getBasicDetails(self):
+ """Collect basic details."""
+ self.accumulate('basic', 'system', self, 'getSystemName', ())
+ self.accumulate('basic', 'os', self, 'getOSName', ())
+ self.accumulate('basic', 'machine', self, 'getMachineType', ())
+ self.accumulate('basic', 'implementation', self, 'getPythonImplementation', ())
+ self.accumulate('basic', 'version', self, 'getPythonVersion', ())
+ self.accumulate('basic/framework', ('name', 'version'), self, 'getFramework', ())
+
+ def getPythonDetails(self):
+ """Collect details about this interpreter. Use the
+ platform module if available when the flag is set to
+ true."""
+ self.accumulate('python', 'implementation', self, 'getPythonImplementation', ())
+ self.accumulate('python', 'version', self, 'getPythonVersion', ())
+ self.accumulate('python', 'branch', platform, 'python_branch', ())
+ self.accumulate('python/build', ('name', 'date'), platform, 'python_build', ())
+ self.accumulate('python', 'compiler', platform, 'python_compiler', ())
+ self.accumulate('python', 'revision', platform, 'python_revision', ())
+
+ def getSystemDetails(self):
+ """Collect details about the system settings on this
+ interpreter."""
+ self.accumulate('system/api', 'flags', sys, 'abiflags')
+ self.accumulate('system/api', 'version', sys, 'api_version')
+ self.accumulate('system', 'byteorder', sys, 'byteorder')
+ self.accumulate('system', 'copyright', sys, 'copyright', func=repr)
+ self.accumulate('system/filesystem', 'encoding', sys, 'getfilesystemencoding', ())
+ self.accumulate('system/filesystem', 'errors', sys, 'getfilesystemencodeerrors', ())
+ self.accumulate('system/float', ('max', 'max_exp', None, 'min', 'min_exp', None, 'dig', 'mant_dig', 'epsilon', 'radix', 'rounds'), sys, 'float_info')
+ self.accumulate('system/hash', ('width', 'modulus', 'inf', 'nan', 'imag', 'algorithm', 'bits', 'seed_bits'), sys, 'hash_info')
+ self.wrap('system/hash', 'modulus', hex)
+ self.accumulate('system/int', ('bits', 'sizeof', 'default_max', 'check_threshold'), sys, 'int_info')
+ self.accumulate('system/path', 'executable', sys, 'executable')
+ self.accumulate('system/path', 'library', sys, 'platlibdir')
+ self.accumulate('system/path', 'prefix', sys, 'prefix')
+ self.accumulate('system', 'platform', sys, 'platform')
+ self.accumulate('system', 'size/max', sys, 'maxsize', func=hex)
+ self.set('system', 'unicode/build', ['wide', 'narrow'][em.narrow])
+ self.accumulate('system', 'unicode/max', sys, 'maxunicode', func=hex)
+ self.accumulate('system/version', 'hex', sys, 'hexversion', func=hex)
+ self.accumulate('system/version', 'str', sys, 'version', func=repr)
+
+ def getPlatformDetails(self):
+ """Collect details about this platform. Use the
+ platform module if available when the flag is set to
+ true."""
+ self.accumulate('platform/architecture', ('bits', 'linkage'), platform, 'architecture', ())
+ self.accumulate('platform', 'machine', platform, 'machine', ())
+ self.accumulate('platform', 'name', platform, 'platform', ())
+ self.accumulate('platform', 'node', platform, 'node', ())
+ self.accumulate('platform', 'processor', platform, 'processor', ())
+ self.accumulate('platform', 'release', platform, 'release', ())
+ self.accumulate('platform', 'system', platform, 'system', ())
+ self.accumulate('platform/thread', ('implementation', 'lock', 'version'), sys, 'thread_info')
+ self.accumulate('platform', 'version', platform, 'version', ())
+
+ def getReleaseDetails(self, system=None):
+ """Collect details about the given system release, or the
+ running one if None."""
+ if system is None:
+ system = self.getSystemName()
+ methodName = 'getReleaseDetails_' + system
+ method = getattr(self, methodName, None)
+ if method is not None:
+ method()
+
+ # Release details specializations.
+
+ def getReleaseDetails_Linux(self):
+ """Collect details about the Linux release."""
+ PREFIX = 'release/linux'
+ file = None
+ for filename in self.releaseFilenames:
+ try:
+ file = open(filename, 'r')
+ break
+ except IOError:
+ pass
+ if file is None:
+ return self.data
+ try:
+ while True:
+ line = file.readline()
+ if not line:
+ break
+ if line.endswith('\n'):
+ line = line[:-1]
+ key, value = line.split('=', 1)
+ if value.startswith('"') and value.endswith('"'):
+ value = value[1:-1]
+ self.set(PREFIX, key, value)
+ finally:
+ file.close()
+
+ def getReleaseDetails_Darwin(self):
+ """Collect details about the Darwin release."""
+ PREFIX = 'release/darwin'
+ PROGRAM = 'sw_vers'
+ FILENAME = '/tmp/sw_vers_%d.out' % os.getpid()
+ waitStatus = os.system('%s > %s 2> /dev/null' % (PROGRAM, FILENAME))
+ exitCode = waitStatus >> 8
+ if exitCode != 0:
+ return
+ file = None
+ try:
+ try:
+ file = open(FILENAME, 'r')
+ for line in file:
+ if line.endswith('\n'):
+ line = line[:-1]
+ key, value = line.split(':', 1)
+ key = key.strip()
+ value = value.strip()
+ self.set(PREFIX, key, value)
+ except OSError:
+ pass
+ finally:
+ if file is not None:
+ file.close()
+ try:
+ os.remove(FILENAME)
+ except OSError:
+ pass
+
+ def getReleaseDetails_Windows(self):
+ """Collect details about the Windows release."""
+ PREFIX = 'release/windows'
+ PRODUCT_TYPES = {
+ 1: 'VER_NT_WORKSTATION',
+ 2: 'VER_NT_DOMAIN_CONTROLLER',
+ 3: 'VER_NT_SERVER',
+ }
+ self.accumulate(PREFIX, 'dllhandle', sys, 'dllhandle', func=hex)
+ self.accumulate(PREFIX, 'registry', sys, 'winver')
+ self.accumulate(PREFIX, ('major', 'minor', 'build', 'platform', 'service_pack'), sys, 'getwindowsversion', ())
+ self.accumulate(PREFIX, 'suite_mask', sys, 'getwindowsversion', (), attr='suite_mask', func=hex)
+ self.accumulate(PREFIX, 'product_type', sys, 'getwindowsversion', (), attr='product_type', func=lambda x: PRODUCT_TYPES.get(x, x))
+ self.accumulate(PREFIX, 'platform_version', sys, 'getwindowsversion', (), attr='platform_version', func=lambda x: '.'.join([em.nativeStr(e) for e in x]))
+
+ # Summary.
+
+ def classify(self, version):
+ """Classify a release by version string."""
+ # First, normalize it.
+ if '-' in version and '.' not in version:
+ version = version.replace('-', '.')
+ major = version.split('.')[0]
+ if len(major) == 4 and major.isdigit():
+ # If the major version looks like a year, it's a preview version.
+ return 'preview'
+ PAIRS = [
+ ('a', 'alpha'),
+ ('b', 'beta'),
+ ('d', 'development'),
+ ('g', 'gamma'),
+ ('h', 'adhoc'),
+ ('r', 'revision'),
+ ('RC', 'release candidate'),
+ ('v', 'version'),
+ ('x', 'development'),
+ ]
+ for key, name in PAIRS:
+ if key in version:
+ return name
+ return None
+
+ def collect(self, level):
+ """Collect details."""
+ if level >= em.Version.BASIC:
+ self.getBasicDetails()
+ if level >= em.Version.PYTHON:
+ self.getPythonDetails()
+ if level >= em.Version.SYSTEM:
+ self.getSystemDetails()
+ if level >= em.Version.PLATFORM:
+ self.getPlatformDetails()
+ if level >= em.Version.RELEASE:
+ self.getReleaseDetails()
+
+ def show(self, level=em.Version.INFO, prelim="", postlim="", file=None):
+ """Show details."""
+ if file is None:
+ file = sys.stdout
+ write = file.write
+ if prelim:
+ write(prelim)
+ write("%s version %s" % (em.__project__, em.__version__))
+ classification = self.classify(em.__version__)
+ if classification:
+ write(" [%s]" % classification)
+ if level >= em.Version.INFO:
+ write(", in %s/%s" % (
+ self.getPythonImplementation(), self.getPythonVersion()))
+ write(", on %s (%s)" % (
+ self.getSystemName(), self.getOSName()))
+ write(", with %s" % self.getMachineType())
+ framework = self.getFramework()
+ if framework:
+ write(", under %s/%s" % framework)
+ if em.compat:
+ write(" (%s)" % ', '.join(em.compat))
+ if postlim:
+ write(postlim)
+ if self.empty():
+ self.collect(level)
+ if level >= em.Version.DATA:
+ if self.data:
+ write("Details:\n")
+ items = list(self.data.items())
+ items.sort()
+ for key, value in items:
+ if value is None or value == '':
+ value = '--'
+ write("- %s: %s\n" % (key, value))
+ else:
+ write("(No details available.)\n")
+
+#
+# main
+#
+
+def main():
+ if len(sys.argv) > 1:
+ arg = sys.argv[1]
+ try:
+ level = int(arg)
+ except ValueError:
+ level = getattr(em.Version, arg)
+ else:
+ level = em.Version.RELEASE
+ details = Details()
+ details.show(level, prelim="Welcome to ", postlim=".\n")
+
+if __name__ == '__main__': main()
--- /dev/null
+Metadata-Version: 2.1
+Name: empy
+Version: 4.0.1
+Summary: A templating system for Python.
+Home-page: http://www.alcyone.com/software/empy/
+Author: Erik Max Francis
+Author-email: software@alcyone.com
+License: BSD
+Platform: any
+Classifier: Development Status :: 6 - Mature
+Classifier: Environment :: Console
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Other Audience
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 3
+Classifier: Topic :: Software Development :: Interpreters
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Software Development :: Pre-processors
+Classifier: Topic :: Text Editors :: Text Processing
+Classifier: Topic :: Text Processing :: Filters
+Classifier: Topic :: Text Processing :: General
+Classifier: Topic :: Text Processing :: Markup
+Classifier: Topic :: Utilities
+License-File: LICENSE.md
+License-File: LICENSE.md.pre
+
+EmPy is a powerful, robust and mature
+templating system for inserting Python code in template text. EmPy
+takes a source document, processes it, and produces output. This is
+accomplished via expansions, which are signals to the EmPy system
+where to act and are indicated with markup. Markup is set off by a
+customizable prefix (by default the at sign, `@`). EmPy can expand
+arbitrary Python expressions, statements and control structures in
+this way, as well as a variety of additional special forms. The
+remaining textual data is sent to the output, allowing Python to be
+used in effect as a markup language.
+
+
--- /dev/null
+LICENSE.md
+LICENSE.md.pre
+README.md
+em.py
+emdoc.py
+emhelp.py
+emlib.py
+setup.py
+empy.egg-info/PKG-INFO
+empy.egg-info/SOURCES.txt
+empy.egg-info/dependency_links.txt
+empy.egg-info/top_level.txt
\ No newline at end of file
--- /dev/null
+em
+emdoc
+emhelp
+emlib
+++ /dev/null
-#! This line however will appear (not the first line in the script).
-This is text. It should appear in the processed output.
-This is a literal at sign: @.
-This is a line continuation; this will appear on the same line.
-Note that it will actually eat any whitespace (one word).
-
-This will appear on one line.
-This will appear on a separate line.
-This is separated by a tab: See?
-These are uppercase As (presuming ASCII): A, A, A, A, A.
-This is more text.
-
-The basics: The square of 4 is 16, or 16.
-Internal whitespace is fine: 4 squared is 16.
-Statements: 4**2 = 16.
-Whitespace too: 4**2 = 16 (still).
-But only on single-line statement expansions.
-Internal whitespace on multi-line statements is significant.
-Normal Python indentation rules must be followed here.
-Normal Python indentation rules must be followed here.
-Simple expressions: x is 4, l is [3, 2, 1], s is "alpha," and 4 squared is 16.
-Literals too: x is 4, but would be written @x.
-Trailing dots are ignored: The value of x is 4.
-Quotes outside of expansions are also ignored: This is quoted: "x is 4."
-Array subscription: The first element of l is 3.
-But this is not: The first element of l is not [3, 2, 1] [0].
-That was equivalent to: [3, 2, 1] and then [0], not 3.
-But whitespace can go inside the brackets: 3 is 3.
-Same with functions: 16 is 16.
-The same applies to the other forms.
-Involved: The contained value is 3.
-More involved: The square of the contained value is 9.
-Following expressions: Pluralize "book" as "books," or maybe "books."
-By default str is used (alpha), but you can use repr if you want ('alpha').
-Conditional expressions: x is true.
-Pluralization: How many words? 4 words.
-Protected expressions: foo is not defined.
-Also here, whitespace isn't important: bar isn't defined either.
-The math module has been imported.
-The re module has not been imported.
-Division by zero is illegal.
-To swallow errors, use None: [two spaces].
-This is self-expanding: @:2 + 2:4:
-You can expand multiple times: @:2 + 2:4:
-
-c's class is C.
-c's name is empy.
-Method call: Hello, empy.
-Note that None is not expanded: [two spaces].
-But the string 'None' is, of course, printed fine: None.
-So a function can return None for side effects only: Hello, empy.
-
-If: a is positive.
-If/else: b is negative.
-If/elif/else: cmp(a, b) is positive.
-Numbers: 0 1 2 3 4 5 6 7 8 9.
-Evens: 0 2 4 6 8.
-Integers less than 5: 0 1 2 3 4.
-Countdown: 10 9 8 7 6 5 4 3 2 1 0.
-While/else: works.
-For/else: 0 1 2 also works.
-Tuple unpacking: <1> <2> <3> <4>.
-Tuple unpacking: <1> <2> <3> <4>.
-Tuple unpacking: <1> <2> <3> <4>.
-Tuple unpacking: <1, 2> <3, 4>.
-Tuple unpacking: <1, 2> <3, 4>.
-Tuple unpacking: <1, 2> <3, 4>.
-Tuple unpacking: <1, 2> <3, 4>.
-Tuple unpacking: <1, 2> <3, 4>.
-Tuple unpacking: <1, 2> <3, 4>.
-Tuple unpacking: <1, 2> <3, 4>.
-Tuple unpacking: <1, 2> <3, 4>.
-More tuple unpacking: <1, 2> <3, 4>.
-Garbage is not defined.
-Division by zero is illegal.
-Catch all: something happened.
-Finally works: finally, and caught.
-Define: 5 is positive, -3 is negative, 0 is zero.
-
-A. This text is undiverted.
-B. This text is also undiverted.
-C. This text is diverted.
-D. Again, this text is undiverted.
-E. This text is diverted and then undiverted.
-E. This text is diverted and then undiverted (this should appear twice).
-F. This text is diverted and then cancelled.
-G. This text is again undiverted.
-H. There should be one remaining diversion: ['x'].
-I. But not after purging it: [].
-J. This should be the final diversion, created manually.
-
-Blanks: , , , .
-Single quotes: ', ', '.
-Double quotes: ", ", ".
-Triple quotes: """, """, ''', '''.
-Quotes surrounded by spaces: " , ' .
-At signs: @, @, @, @.
-Close parentheses: ), ), ), ).
-Close parentheses in quotes: ')', ')'.
-Close braces with an intervening space: } }.
-Repr of a backquote: '`'.
-Exes: x, x, x, x, x.
-Dollar signs: $, $, $.
-These are strings:
-single quoted string
-double quoted string
-single quoted string with escaped 'single quotes'
-double quoted string with escaped "double quotes"
-triple single quoted string
-triple double quoted string
-single quoted string with "double quotes"
-double quoted string with 'single quotes'
-triple single quoted continued string
-triple double quoted continued string
-triple single quoted
-...multi-line string
-triple double quoted
-... multi-line string
-
-Encountered significators:
-a and b should be None: None, None
-c and d should be 'x': 'x', 'x'
-e and f should be 'x y': 'x y', 'x y'
-
-This line should be in mixed case.
-this line should be all lowercase.
-THIS LINE SHOULD BE ALL UPPERCASE (HOW GAUCHE).
-[This line should be bracketed.]
-[So should this line.]
-*There* shou*ld be* star*s eve*ry fi*ve ch*aract*ers o*n thi*s lin*e.
-This line should be back to mixed case.
-[THIS LINE SHOULD BE ALL UPPERCASE WITH BRACKETS.]
-This line should be back to mixed case (again).
-
-The new context is sample.em:264.
-File inclusion [sample.em:265]: 2 + 2 = 4 [<<class 'FakeFile'>>:1].
-Expansion [sample.em:266]: This should be appear [<expand>:1] on the same line as this [sample.em:268].
-More expansion [sample.em:269]: Another expansion [<expand>:1].
-This is the next line [sample.em:271].
-Quoting: x when quoted would be '@x' or @@x.
-More quoting: This will be @@doubled but '''@this is not'''.
-Here's the last view of the old context: sample.em:274.
-Creating a new context ...
-The current context is: <unnamed>:1.
-The context name should now be 'NewName': NewName:3.
-The line number should now be 1000: NewName:1000.
-Back to the old context: sample.em:277.
-
-Interpreter's q is 1.
-Embedded interpreter's q is 10.
-Interpreter's q is still 1; the embedded interpreter had no effect.
-Standalone expansion: 1 + 1 is 2.
-With locals: 2 + 3 is 5.
-With globals: g's x is 10.
-Still with globals: g's x + 1 is 11.
-g's x is still 10.
-
-Invoking the sample hook: [SampleHook.null invoked].
-
-Using a custom markup: [This appears in brackets].
-Again: [<There are angle brackets in this one>].
-Once more: [This is a right angle bracket in quotes: ">"].
-
-This is the penultimate line.
+++ /dev/null
-#! $Id: sample.em 5359 2014-01-23 00:33:57Z max $ $Date: 2014-01-22 16:33:57 -0800 (Wed, 22 Jan 2014) $
-@# Bangpaths are handled properly (the above line will not appear).
-#! This line however will appear (not the first line in the script).
-@# This is a comment. This should not appear in the processed output.
-This is text. It should appear in the processed output.
-This is a literal at sign: @@.
-This is a line continuation; @
-this will appear on the same line.
-Note that it will actually eat any white@ space (one word).
-@{
-# The em.py script has to be somewhere in sys.path!
-import em
-}@
-
-@# Escape codes.
-This will appear on one line.@\nThis will appear on a separate line.
-This is separated by a tab:@\tSee?
-These are uppercase As (presuming ASCII): A, @\q1001, @\o101, @\d065, @\x41.
-@{
-import sys
-# This is just a normal Python comment.
-print("This is more text.")
-}@
-@# Note the @{ ... }@ convention to suppress the newline following the }.
-@# Also note that comments are completely tossed: This is not expanded: @(x).
-
-@# The basics.
-@{
-import sys, math
-x = 4
-s = 'alpha'
-word = "book"
-l = [3, 2, 1]
-def square(n):
- return n**2
-friends = ['Albert', 'Betty', 'Charles', 'Donald']
-class Container(object):
-
- def __init__(self, value):
- self.value = value
-
- def square(self):
- return square(self.value)
-c = Container(3)
-}@
-The basics: The square of @(x) is @(x**2), or @(square(x)).
-Internal whitespace is fine: @( x ) squared is @( square(x) ).
-Statements: @{sys.stdout.write("%d**2 = %d" % (x, square(x)))}.
-Whitespace too: @{ sys.stdout.write("%d**2 = %d (still)" % (x, square(x))) }.
-@{
-print("But only on single-line statement expansions.")
-if 1:
- print("Internal whitespace on multi-line statements is significant.")
-for i in range(2):
- print("Normal Python indentation rules must be followed here.")
-}@
-Simple expressions: x is @x, l is @l, s is "@s," and @x squared is @square(x).
-Literals too: x is @x, but would be written @@x.
-Trailing dots are ignored: The value of x is @x.
-Quotes outside of expansions are also ignored: This is quoted: "x is @x."
-@# Whitespace is important in simple expressions.
-Array subscription: The first element of l is @l[0].
-But this is not: The first element of l is not @l [0].
-That was equivalent to: @(l) and then [0], not @l[0].
-But whitespace can go inside the brackets: @l[0] is @l[ 0 ].
-Same with functions: @square(x) is @square( x ).
-The same applies to the other forms.
-Involved: The contained value is @c.value.
-More involved: The square of the contained value is @c.square().
-Following expressions: Pluralize "@word" as "@(word)s," or maybe "@word@ s."
-By default str is used (@s), but you can use repr if you want (@`s`).
-Conditional expressions: @(x ? "x is true" ! "x is false").
-Pluralization: How many words? @x word@(x != 1 ? 's').
-Protected expressions: @(foo $ "foo is not defined").
-Also here, whitespace isn't important: @(bar$"bar isn't defined either").
-The math module has @(math ? "been imported" $ "not been imported").
-The re module has @(re ? "been imported" $ "not been imported").
-Division by zero is @(x/0 $ "illegal").
-To swallow errors, use None: @(buh $ None) [two spaces].
-This is self-expanding: @:2 + 2:(this will get replaced with 4):
-You can expand multiple times: @
-@empy.expand("@empy.expand('@:2 + 2:hugalugahglughalug:')")
-
-@# More complex examples, including classes.
-@{
-class C:
- def __init__(self, name):
- self.name = name
-
- def greetString(self):
- return "Hello, %s" % self.name
-
- def printGreeting(self):
- sys.stdout.write("Hello, %s" % self.name) # implicit None return
-
-c = C("empy")
-}@
-c's class is @c.__class__.__name__.
-c's name is @c.name.
-Method call: @c.greetString().
-Note that None is not expanded: @(None) [two spaces].
-But the string 'None' is, of course, printed fine: @('None').
-So a function can return None for side effects only: @c.printGreeting().
-
-@# Control.
-@{
-a = 5 # something positive
-b = -3 # something negative
-z = 0 # zero
-}@
-If: a is @[if a > 0]positive@[end if].
-If/else: b is @[if b > 0]positive@[else]negative@[end if].
-If/elif/else: cmp(a, b) is @
-@[if a < b]negative@[elif a > b]positive@[else]zero@[end if].
-Numbers:@
-@[for i in range(10)] @i@[end for].
-Evens:@
-@[for i in range(10)]@[if i % 2 == 1]@[continue]@[end if] @i@[end for].
-Integers less than 5:@
-@[for i in range(10)]@[if i >= 5]@[break]@[end if] @i@[end for].
-Countdown:@
-@{j = 10}@[while j >= 0] @j@{j = j - 1}@[end while].
-While/else: @[while z]shouldn't get here@[else]works@[end while].
-For/else:@
-@[for i in range(3)] @i@[else] also works@[end for].
-Tuple unpacking:@[for x in [1, 2, 3, 4]] <@x>@[end for].
-Tuple unpacking:@[for x, in [[1], [2], [3], [4]]] <@x>@[end for].
-Tuple unpacking:@[for (x,) in [[1], [2], [3], [4]]] <@x>@[end for].
-Tuple unpacking:@[for x, y in [[1, 2], [3, 4]]] <@x, @y>@[end for].
-Tuple unpacking:@[for (x), (y) in [[1, 2], [3, 4]]] <@x, @y>@[end for].
-Tuple unpacking:@[for (x, y) in [[1, 2], [3, 4]]] <@x, @y>@[end for].
-Tuple unpacking:@[for x, (y) in [[1, 2], [3, 4]]] <@x, @y>@[end for].
-Tuple unpacking:@[for x, (y,) in [[1, [2]], [3, [4]]]] <@x, @y>@[end for].
-Tuple unpacking:@[for (x), y in [[1, 2], [3, 4]]] <@x, @y>@[end for].
-Tuple unpacking:@[for (x,), y in [[[1], 2], [[3], 4]]] <@x, @y>@[end for].
-Tuple unpacking:@[for (x,), (y,) in [[[1], [2]], [[3], [4]]]] <@x, @y>@[end for].
-More tuple unpacking:@[for (((x))), ((y),) in [[1, [2]], [3, [4]]]] <@x, @y>@[end for].
-Garbage is @[try]@hglhagulahguha@[except NameError]not defined@[end try].
-Division by zero is @[try]@(a/z)@[except ZeroDivisionError]illegal@[end try].
-Catch all: @[try]@ghlaghlhagl@[except]something happened@[end try].
-Finally works: @
-@[try]@[try]@(1/0)@[finally]finally, @[end try]@[except]and caught@[end try].
-@[def sign(x)]@x is @[if x > 0]positive@[elif x < 0]negative@[else]zero@[end if]@[end def]@
-Define: @sign(a), @sign(b), @sign(z).
-
-@# Diversions. Again, a trailing @ is used to suppress the following newline.
-A. This text is undiverted.
-@empy.startDiversion(1)@
-C. This text is diverted.
-@empy.stopDiverting()@
-B. This text is also undiverted.
-@empy.playDiversion(1)@
-D. Again, this text is undiverted.
-@empy.startDiversion('a')@
-E. This text is diverted and then undiverted@
-@empy.stopDiverting()@
-@empy.replayDiversion('a').
-@empy.playDiversion('a') (this should appear twice).
-@empy.startDiversion('q')@
-F. This text is diverted and then cancelled.
-@empy.playDiversion('q')@
-G. This text is again undiverted.
-@empy.startDiversion('x')@
-X. This text will be purged and should not appear!
-@empy.stopDiverting()@
-H. There should be one remaining diversion: @empy.getAllDiversions().
-@empy.purgeDiversion('x')@
-I. But not after purging it: @empy.getAllDiversions().
-@{
-# Finally, make a manual diversion and manipulate it.
-empy.createDiversion('z')
-zDiversion = empy.retrieveDiversion('z')
-zDiversion.write("J. This should be the final diversion, created manually.\n")
-empy.playDiversion('z')
-}@
-
-@# Parsing checks.
-Blanks: @(''), @(""), @(''''''), @("""""").
-Single quotes: @('\''), @("'"), @("""'""").
-Double quotes: @("\""), @('"'), @('''"''').
-Triple quotes: @("\"\"\""), @('"""'), @('\'\'\''), @("'''").
-Quotes surrounded by spaces: @(""" " """), @(''' ' ''').
-At signs: @('@'), @("@"), @('''@'''), @("""@""").
-Close parentheses: @(')'), @(")"), @((")")), @((')')).
-Close parentheses in quotes: @("')'"), @('\')\'').
-Close braces with an intervening space: @
-@{sys.stdout.write("}")} @{sys.stdout.write('}')}.
-Repr of a backquote: @`'`'`.
-Exes: @("?"?'x'), @(0?"!"!'x'), @(0?":":'x'), @("]"?'x'), @(1?"x"!"]").
-Dollar signs: @("$"$None), @(asdf?"$"$"$"), @(1?asdf$"$").
-These are strings:
-@'single quoted string'
-@"double quoted string"
-@'single quoted string with escaped \'single quotes\''
-@"double quoted string with escaped \"double quotes\""
-@'''triple single quoted string'''
-@"""triple double quoted string"""
-@'single quoted string with "double quotes"'
-@"double quoted string with 'single quotes'"
-@'''triple single quoted continued \
-string'''
-@"""triple double quoted continued \
-string"""
-@'''triple single quoted
-...multi-line string'''
-@"""triple double quoted
-... multi-line string"""
-
-@# Significators.
-@%a
-@%b
-@%c "x"
-@%d "x"
-@%e "x y"
-@%f "x y"
-Encountered significators:
-a and b should be None: @`__a__`, @`__b__`
-c and d should be 'x': @`__c__`, @`__d__`
-e and f should be 'x y': @`__e__`, @`__f__`
-
-@# Filters.
-This line should be in mixed case.
-@empy.setFilter(lambda x: x.lower())@
-This line should be all lowercase.
-@empy.setFilter(lambda x: x.upper())@
-This line should be all uppercase (how gauche).
-@empy.setFilter([em.LineBufferedFilter(), lambda x: '[%s]\n' % x[:-1]])@
-This line should be bracketed.
-So should this line.
-@empy.setFilter([em.SizeBufferedFilter(5), lambda x: '*' + x])@
-There should be stars every five characters on this line.
-@empy.nullFilter()@
-This line should not appear at all!
-@empy.resetFilter()@
-This line should be back to mixed case.
-@empy.attachFilter(lambda x: x.upper())@
-@empy.attachFilter(em.LineBufferedFilter())@
-@empy.attachFilter(lambda x: '[%s]\n' % x[:-1])@
-This line should be all uppercase with brackets.
-@empy.resetFilter()@
-This line should be back to mixed case (again).
-
-@# Contexts, metaoperations.
-@{
-class FakeFile(object):
-
- def __init__(self, line):
- self.lines = [line]
-
- def read(self):
- return '\n'.join(self.lines) + '\n'
-
- def readline(self):
- if self.lines:
- return self.lines.pop(0)
- else:
- return ''
-
- def close(self): pass
-def context():
- return "%s:%d" % empy.identify()
-stringFile = FakeFile("2 + 2 = @(2 + 2) [@context()].\n")
-}@
-The new context is @context().
-File inclusion [@context()]: @empy.include(stringFile)@
-Expansion [@context()]: @
-@empy.expand("This should be appear [@context()]") @
-on the same line as this [@context()].
-More expansion [@context()]: @
-@{sys.stdout.write(empy.expand("Another expansion [@context()]"))}.
-This is the next line [@context()].
-Quoting: @empy.quote("x when quoted would be '@x' or @x").
-More quoting: @empy.quote("This will be @doubled but '''@this is not'''").
-Here's the last view of the old context: @context().
-Creating a new context ...
-@empy.pushContext()@
-The current context is: @context().
-@?NewName
-The context name should now be 'NewName': @context().
-@!1000
-The line number should now be 1000: @context().
-@empy.popContext()@
-Back to the old context: @context().
-
-@# Embedded interpreters and standalone expansion.
-@{
-q = 1
-}@
-Interpreter's q is @q.
-@{
-try:
- i = em.Interpreter()
- i.string("@{q = 10}")
- i.string("Embedded interpreter's q is @q.\n")
-finally:
- i.shutdown()
-}@
-Interpreter's q is still @q; the embedded interpreter had no effect.
-Standalone expansion: @em.expand("1 + 1 is @(1 + 1).")
-With locals: @em.expand("@x + @y is @(x + y).", x=2, y=3)
-@{
-g = {}
-}@
-With globals: @em.expand("@{x = 10}g's x is @x.", g)
-Still with globals: @em.expand("g's x + 1 is @(x + 1).", g)
-g's x is still @g['x'].
-
-@# Hooks.
-@{
-class SampleHook(em.Hook):
- def null(self):
- self.interpreter.write('[SampleHook.null invoked]')
-
-sampleHook = SampleHook()
-empy.addHook(sampleHook)
-}@
-Invoking the sample hook: @empy.invokeHook('null').
-@{
-empy.removeHook(sampleHook)
-}@
-
-@# Custom.
-@{
-def customCallback(contents, empy=empy):
- empy.write('[%s]' % contents)
-empy.registerCallback(customCallback)
-}@
-Using a custom markup: @<This appears in brackets>.
-Again: @<<There are angle brackets in this one>>.
-Once more: @<This is a right angle bracket in quotes: ">">.
-@{
-empy.deregisterCallback()
-}@
-
-@# Finals; note these are evaluated in reverse order.
-@empy.atExit(lambda: empy.write("This is the penultimate line.\n"))@
--- /dev/null
+[egg_info]
+tag_build =
+tag_date = 0
+
-#!/usr/bin/env python
-#
-# $Id: setup.py.pre 3116 2004-01-14 02:53:02Z max $ $Date: 2004-01-13 18:53:02 -0800 (Tue, 13 Jan 2004) $
+#!/usr/bin/env python3
-from distutils.core import setup
+import sys
+
+if sys.version_info >= (3, 10):
+ from setuptools import setup
+else:
+ from distutils.core import setup
+
+PROGRAM = "empy"
+VERSION = "4.0.1"
+AUTHOR = "Erik Max Francis <max@alcyone.com>".split(' <')[0]
+CONTACT = "software@alcyone.com"
+URL = "http://www.alcyone.com/software/empy/"
+LICENSE = "BSD"
DESCRIPTION = "A templating system for Python."
LONG_DESCRIPTION = """\
- EmPy is a system for embedding Python expressions and statements
- in template text; it takes an EmPy source file, processes it, and
- produces output. This is accomplished via expansions, which are
- special signals to the EmPy system and are set off by a special
- prefix (by default the at sign, '@'). EmPy can expand arbitrary
- Python expressions and statements in this way, as well as a
- variety of special forms. Textual data not explicitly delimited
- in this way is sent unaffected to the output, allowing Python to
- be used in effect as a markup language. Also supported are "hook"
- callbacks, recording and playback via diversions, and dynamic,
- chainable filters. The system is highly configurable via command
- line options and embedded commands.
+EmPy is a powerful, robust and mature
+templating system for inserting Python code in template text. EmPy
+takes a source document, processes it, and produces output. This is
+accomplished via expansions, which are signals to the EmPy system
+where to act and are indicated with markup. Markup is set off by a
+customizable prefix (by default the at sign, `@`). EmPy can expand
+arbitrary Python expressions, statements and control structures in
+this way, as well as a variety of additional special forms. The
+remaining textual data is sent to the output, allowing Python to be
+used in effect as a markup language.
"""
setup(
- name="empy",
- version="3.3.2",
- author="Erik Max Francis",
- author_email="software@alcyone.com",
- url="http://www.alcyone.com/software/empy",
- license="%LICENSE",
- py_modules=["em", "emlib"],
- platforms=["unix", "linux", "win32"],
+ name=PROGRAM,
+ version=VERSION,
+ author=AUTHOR,
+ author_email=CONTACT,
+ url=URL,
+ license=LICENSE,
+ py_modules=[
+ "em",
+ "emlib",
+ "emhelp",
+ "emdoc",
+ ],
+ scripts=[
+ "em.py",
+ ],
+ platforms="any",
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
+ classifiers=[
+ "Development Status :: 6 - Mature",
+ "Environment :: Console",
+ "Intended Audience :: Developers",
+ "Intended Audience :: Other Audience",
+ "License :: OSI Approved :: BSD License",
+ "Operating System :: OS Independent",
+ "Programming Language :: Python :: 2",
+ "Programming Language :: Python :: 3",
+ "Topic :: Software Development :: Interpreters",
+ "Topic :: Software Development :: Libraries :: Python Modules",
+ "Topic :: Software Development :: Pre-processors",
+ "Topic :: Text Editors :: Text Processing",
+ "Topic :: Text Processing :: Filters",
+ "Topic :: Text Processing :: General",
+ "Topic :: Text Processing :: Markup",
+ "Topic :: Utilities",
+ ],
)
+++ /dev/null
-#!/bin/sh
-#
-# $Id: test.sh 5359 2014-01-23 00:33:57Z max $ $Date: 2014-01-22 16:33:57 -0800 (Wed, 22 Jan 2014) $
-
-if [ $# = 1 ]
-then
- PYTHON="$1"
-else
- PYTHON=python
-fi
-
-EMPY=em.py
-SAMPLE=sample.em
-BENCH=sample.bench
-
-if $PYTHON -c 'import sys; print(sys.version)' > /dev/null
-then
- :
-else
- echo "EmPy was not checked; $PYTHON looks broken." 1>&2
- exit 1
-fi
-
-if $PYTHON $EMPY $SAMPLE | diff $BENCH -
-then
- echo "EmPy checks out." 1>&2
-else
- echo "EmPy does not check out! Please mail output to author." 1>&2
-fi