6.1 plasTeX — The Python Macro and Document Interfaces

While plasTeX does a respectable job expanding LaTeX macros, some macros may be too complicated for it to handle. These macros may have to be re-coded as Python objects. Another reason you may want to use Python-based macros is for performance reasons. In most cases, macros coded using Python will be faster than those expanded as true LaTeX macros.

The API for Python macros is much higher-level than that of LaTeX macros. This has good and bad ramifications. The good is that most common forms of LaTeX macros can be parsed and processed very easily using Python code which is easier to read than LaTeX code. The bad news is that if you are doing something that isn’t common, you will have more work to do. Below is a basic example.

from plasTeX import Command

class mycommand(Command):
    """ \mycommand[name]{title} """
    args = '[ name ] title'

The code above demonstrates how to create a Python-based macro corresponding to LaTeX macro with the form \mycommand[name]{title} where ‘name’ is an optional argument and ‘title’ is a mandatory argument. In the Python version of the macro, you simply declare the arguments in the args attribute as they would be used in the LaTeX macro, while leaving the braces off of the mandatory arguments. When parsed in a LaTeX document, an instance of the class mycommand in created and the arguments corresponding to ‘name’ and ‘title’ are set in the attributes dictionary for that instance. This is very similar to the way an XML DOM works, and there are more DOM similarities yet to come. In addition, there are ways to handle casting of the arguments to various data types in Python. The API documentation below goes into more detail on these and many more aspects of the Python macro API.