latex2text — Simple Latex to Text Converter

A simplistic, heuristic LaTeX code parser allowing to returns a text-only approximation. Suitable, e.g. for indexing tex code in a database for full text searching.

The main class is LatexNodes2Text. For a quick start, try:

from pylatexenc.latex2text import LatexNodes2Text

latex = "... LaTeX code ..."
text = LatexNodes2Text().latex_to_text(latex)

You may also use the command-line version of latex2text:

$ echo '\textit{italic} \`acc\^ented text' | latex2text
𝑖𝑡𝑎𝑙𝑖𝑐 àccênted text

Note the support for unicode bold and italic font styles, introduced in pylatexenc v3. (See the LatexNodes2Text class doc and What’s new in pylatexenc 3 for how to customize the output, e.g., disabling unicode fonts.)

Custom latex conversion rules: A simple template

Here is a short introduction on how to customize the way that LatexNodes2Text converts LaTeX constructs (macros, environments, and specials) to unicode text. You can start off with the example template below and adapt it to your needs.

Macros, environments and specials are parsed as corresponding node objects by the parser (see pylatexenc.latexwalker.LatexMacroNode, pylatexenc.latexwalker.LatexEnvironmentNode, and pylatexenc.latexwalker.LatexSpecialsNode). These node objects are then converted to unicode text by the LatexNodes2Text object.

You can define new macros, environments, or specials, or override existing definitions. The definitions need to be provided twice. First, at the level of the parser using the macrospec module; the parser needs to know the argument structure of your macros, environments, and specials, along with which characters to recognize as “specials”. Second, at the level of latex2text, you need to specify what the replacement strings are for the different LaTeX constructs after they have been parsed into the latex node tree by the parser.

The following template is a simple illustrative example that implements the following definitions:

  • A new macro \putinquotes[`][']{text} that puts its mandatory argument into quotes defined by the two optional arguments. Let’s say that the default quotes that are used are the unicode double quotation marks “ and ”. Another simpler macro \putindblquotes{text} is also provided for the sake of the example.

  • A new environment \begin{inquotes}[`]['] ... \end{inquotes} that does the same thing as its macro equivalent. Another simpler environment \begin{indblquotes}...\end{indblquotes} is also provided for the sake of the example.

  • The usual LaTeX quote symbols `, ``, ', and '' for unicode quotes. (See also issue #39)

Here is the code (see also docs for pylatexenc.macrospec.MacroSpec, pylatexenc.macrospec.EnvironmentSpec, pylatexenc.macrospec.SpecialsSpec, as well as pylatexenc.latex2text.MacroTextSpec, pylatexenc.latex2text.EnvironmentTextSpec, pylatexenc.latex2text.SpecialsTextSpec):

from pylatexenc import latexwalker, latex2text, macrospec
from pylatexenc.latexnodes.parsers import LatexGeneralNodesParser

#
# Define macros, environments, specials for the *parser*
#
lw_context_db = latexwalker.get_default_latex_context_db()
lw_context_db.add_context_category(
    'my-quotes',
    prepend=True,
    macros=[
        macrospec.MacroSpec("putindblquotes", "{"),
        macrospec.MacroSpec("putinquotes", "[[{"),
    ],
    environments=[
        macrospec.EnvironmentSpec("indblquotes", ""),
        macrospec.EnvironmentSpec("inquotes", "[["),
    ],
    specials=[
        macrospec.SpecialsSpec("`"),
        macrospec.SpecialsSpec("'"),
        macrospec.SpecialsSpec("``"),
        macrospec.SpecialsSpec("''"),
    ],
)

#
# Implement macros, environments, specials for the *conversion to text*
#

def _get_optional_arg(node, default, l2tobj):
    """Helper that returns the `node` converted to text, or `default`
    if the node is `None` (e.g. an optional argument that was not
    specified)"""
    if node is None:
        return default
    return l2tobj.nodelist_to_text([node])

def put_in_quotes_macro_repl(n, l2tobj):
    r"""Get the text replacement for the macro
    \putinquotes[open-quote][close-quote]{text}"""
    if not n.nodeargd:
        # n.nodeargd can be empty if e.g. \putinquotes was a single
        # token passed as an argument to a macro,
        # e.g. \newcommand\putinquotes...
        return ''
    open_q_s = _get_optional_arg(n.nodeargd.argnlist[0], '“', l2tobj)
    close_q_s = _get_optional_arg(n.nodeargd.argnlist[1], '”', l2tobj)
    return (open_q_s + l2tobj.nodelist_to_text([n.nodeargd.argnlist[2]])
            + close_q_s)

def in_quotes_env_repl(n, l2tobj):
    """Get the text replacement for the {inquotes} environment"""
    open_q_s = _get_optional_arg(n.nodeargd.argnlist[0], '“', l2tobj)
    close_q_s = _get_optional_arg(n.nodeargd.argnlist[1], '”', l2tobj)
    return open_q_s + l2tobj.nodelist_to_text(n.nodelist) + close_q_s

l2t_context_db = latex2text.get_default_latex_context_db()
l2t_context_db.add_context_category(
    'my-quotes',
    prepend=True,
    macros=[
        latex2text.MacroTextSpec("putindblquotes",
                                 simplify_repl=r'“%(1)s”'),
        latex2text.MacroTextSpec("putinquotes",
                                 simplify_repl=put_in_quotes_macro_repl),
    ],
    environments=[
        latex2text.EnvironmentTextSpec("indblquotes",
                                       simplify_repl=r'“%(body)s”'),
        latex2text.EnvironmentTextSpec("inquotes",
                                       simplify_repl=in_quotes_env_repl),
    ],
    specials=[
        latex2text.SpecialsTextSpec('`', "‘"),
        latex2text.SpecialsTextSpec("'", "’"),
        latex2text.SpecialsTextSpec('``', "“"),
        latex2text.SpecialsTextSpec("''", "”"),
    ],
)


#
# Here is an example usage:
#

def custom_latex_to_text( input_latex ):
    # the latex parser instance with custom latex_context
    lw_obj = latexwalker.LatexWalker(input_latex,
                                     latex_context=lw_context_db)
    # parse to node list
    nodelist, parsing_state_delta = lw_obj.parse_content(LatexGeneralNodesParser())
    # initialize the converter to text with custom latex_context
    l2t_obj = latex2text.LatexNodes2Text(latex_context=l2t_context_db)
    # convert to text
    return l2t_obj.nodelist_to_text( nodelist )


print(custom_latex_to_text(
    r"""\begin{inquotes}[`][']Hello, world\end{inquotes}"""))
# ‘Hello, world’

print(custom_latex_to_text(r"""\putinquotes[``]['']{Hello, world}"""))
# “Hello, world”

print(custom_latex_to_text(r"""\putinquotes{Hello, world}"""))
# “Hello, world”

print(custom_latex_to_text(r"""\putinquotes[`][']{Hello, world}"""))
# ‘Hello, world’

Latex to Text Converter Class

class pylatexenc.latex2text.LatexNodes2Text(latex_context=None, **flags)

Simplistic Latex-To-Text Converter.

This class parses a nodes structure generated by the latexwalker module, and creates a text representation of the structure.

It is capable of parsing \input directives safely, see set_tex_input_directory() and read_input_file(). By default, \input and \include directives are ignored.

Arguments to the constructor:

Additional keyword arguments are flags which may influence the behavior:

  • math_mode=’fancy’|’text’|’with-delimiters’|’verbatim’|’remove’: Specify how to treat chunks of LaTeX code that correspond to math modes. If ‘fancy’ (the default), the formula is rendered as described just below. If ‘text’, then the math mode contents is incorporated as normal text. If ‘with-delimiters’, the content is incorporated as normal text but it is still included in the original math-mode delimiters, such as ‘$…$’. If ‘verbatim’, then the math mode chunk is kept verbatim, including the delimiters. The value ‘remove’ means to remove the math mode sections entirely and not to produce any replacement text.

    This option selects the engine that renders a formula. It has nothing to say about the fonts the letters are set in; those are chosen by the math_fontstyle= and text_fontstyle= options below, in every math mode alike. Output that has to be plain ASCII therefore needs both: see the note at the end of this entry.

    The default value ‘fancy’ selects a rendering of the formula that aims to be as visually appealing as possible, and draws similar rendering ideas from how LaTeX itself would typeset the equation. It is meant for text that a person is going to read — in a terminal, in an e-mail, in a search result. It differs from ‘text’ in four ways.

    • The whitespace of the source is ignored, exactly as LaTeX ignores it, and spaces are put back only where they help the reader. So $4 \pi c$ and $4\pi c$ both give 4π𝑐, keeping the implicit multiplication tight, whereas $x+y$ gives 𝑥 + 𝑦, setting the binary operator apart. What decides this is LaTeX’s own table of the spacing between neighboring atoms, reduced from four widths of space to two.

    • The engine emits unicode sub/superscripts whenever possible.

    • A sub-expression is put in delimiters only where its extent would otherwise be unclear, and where a separating space is enough, a space is used instead. So $x_{abc}$ gives 𝑥_𝑎𝑏𝑐 and $x_{abc} p$ gives 𝑥_𝑎𝑏𝑐 𝑝, while $x_{abc}^2$, where a second script attaches to the same base, does need the delimiters and gives 𝑥_(𝑎𝑏𝑐)².

    • A text-mode fragment such as \text{...} is left alone. The spaces it brings along survive, and no space of ours is added right next to one of them, so that $\text{if } x > 0$ gives if 𝑥 > 0 with exactly one space after the “if”.

    The rendering stays one-dimensional: there is no two-dimensional layout and nothing is drawn out of characters. A matrix, for instance, is rendered inline as [ 1 2; 3 4 ], in math mode and in display math alike.

    The examples above are written with the default font styles in force, so the letters of the formulas appear in them as the unicode math italics. To get the rendering of pylatexenc 2 back, ask for that version’s engine and for its fonts:

    LatexNodes2Text(math_mode='text', math_fontstyle=None,
                    text_fontstyle=False)
    

    Note the None rather than False for the math font: pylatexenc 2 applied no alphabet of its own to a formula, leaving the x of $x + \mathbb{Z}$ plain, but its \math..{} macros did install theirs, giving x + ℤ. See the two options below.

    Changed in version 3.0: The math_mode=’fancy’ value was introduced in pylatexenc 3.0, and is the default there. Use math_mode='text' to restore pylatexenc 2’s behavior.

  • math_expression_in=’braces’|’parens’|(left, right)|None: Specify which delimiters to place around a mathematical sub-expression that we were not able to render directly in plain text. Say we meet the superscript x^{abc}; there are no unicode superscript characters for all of ‘a’, ‘b’ and ‘c’, so the superscript is written out as ordinary text after a ‘^’ character. The delimiters are what makes it possible to still see where the superscript ends, i.e., to tell x^{ab}c from x^{abc}.

    The value ‘braces’ uses the characters ‘{’ and ‘}’, and ‘parens’ uses ‘(’ and ‘)’. You may also give a pair (a two-item tuple) with the opening and the closing delimiter of your choice. Finally, the value None means that no delimiters are added at all, as was the case up to pylatexenc 2.

    Delimiters are only added where they are needed, that is, around sub-expressions that are longer than a single character. Apart from superscripts and subscripts, the delimiters are used for the numerator and the denominator of the fraction macros (\frac and friends), which are rendered as numerator/denominator.

    The default value is given by the module-level constant default_math_expression_in. The setting can also be changed for one part of the document only, see the math_expression_in field of TextConversionState.

    Added in version 3.0: The math_expression_in= option was introduced in pylatexenc 3.0.

  • math_fontstyle=’italic’|None|False|<style name>: The font style in which the letters of a formula are typeset, using the unicode math alphanumeric symbols (see fmt_math_text_style(), whose style names are the accepted values here). The default ‘italic’ follows the convention of mathematical typesetting, where a variable name is set in italics; the value None leaves the letters upright, and the value False switches the unicode alphabets off altogether (see below).

    Note that None sets the style that the letters of a formula start out in, and that \mathbf{} and friends still install their own style for the duration of their contents, so $x + \mathbf{a}$ still gives x + 𝐚. The value False is the stronger one: it says that no unicode alphabet is to be used in math mode at all, and the font style macros then leave the letters alone, so the same formula gives x + a. Use it together with text_fontstyle=False for output that is plain ASCII throughout.

    The value math_fontstyle=None reproduces pylatexenc v2’s behavior: While the default math alphabet remained upright, every \math..{} macro installed a custom alphabet in pylatexenc v2 so that $x + \mathbb{Z}$ gave x + ℤ and $\mathcal{C}$ gave 𝒞.

    There is a small price for switching the styling off. A run of two or more upright latin letters is what the renderer takes for the name of a function, which is how \sin and \log are told apart from a product of variables without every such macro having to be annotated; that guess is only sound as long as the variables are being italicized. With math_fontstyle=None or False, $2xy$ still comes out as 2xy and $2\sin x$ still as 2 sin x, but a construct that relies on the guess, such as $\mathrm{max} x$, loses the space that separates the function name from its argument.

    This is the initial value of the math_fontstyle field of the conversion state; macros such as \mathbf{} change it for their contents, and it can also be changed for one part of the document only, see TextConversionState and push_state().

    The option is independent of math_mode=, which selects the engine that renders a formula. Each engine consults math_fontstyle to render math alphabets as appropriate (e.g., while font styles are honored in math_mode='text', both math_mode='verbatim' and math_mode='remove' ignore math font styles entirely).

    Added in version 3.0: The math_fontstyle= option was introduced in pylatexenc 3.0.

  • text_fontstyle=None|False|<style name>: The same thing for the text outside of the formulas. It is the font style that ordinary text starts out in, given as one of the style names of fmt_math_text_style(), or None — the default — for the upright style that ordinary text is normally set in.

    As above, None only sets the style that text starts out in, and \textbf{}, \textsf{}, \emph{} and friends still install their own for the duration of their contents, so \textbf{bold} gives 𝐛𝐨𝐥𝐝. The value False switches the unicode alphabets off for text mode altogether: the font style macros then leave the letters alone and \textbf{bold} gives bold. Use text_fontstyle=False, math_fontstyle=False to disable font styles if you prefer ASCII output.

    Note that a style name here applies to the text that is not inside one of the font style macros: those macros select a whole font and not one of the axes (family, weight, shape) that LaTeX varies independently, so with text_fontstyle=’sans’ the argument of \textbf{} still comes out in the serif bold alphabet.

    This is the initial value of the text_fontstyle field of the conversion state, and as with math_fontstyle= it can be changed for one part of the document only, see TextConversionState and push_state().

    Added in version 3.0: The text_fontstyle= option was introduced in pylatexenc 3.0.

  • keep_comments=True|False: If set to True, then LaTeX comments are kept (including the percent-sign); otherwise they are discarded. (By default this is False)

  • fill_text: If set to True or to a positive integer, then the whitespace of LaTeX char blocks is re-layed out to fill at the given number of characters or 80 by default. The fill is by far not perfect, but the resulting text might be slightly more readable.

  • strict_latex_spaces=True|False: If set to True, then we follow closely LaTeX’s handling of whitespace. For instance, whitespace following a bare macro (i.e. without any delimiting characters like ‘{’) is consumed/removed. If set to False (the default), then some liberties are taken with respect to whitespace [hopefully making the result slightly more aesthetic, but this behavior is mostly there for historical reasons].

    You may also use one of the presets strict_latex_spaces=’based-on-source’|’macros’|’except-in-equations’, which allow for finer control of how whitespace is handled:

    • The value ‘based-on-source’ is the option that is furthest from latex’s behavior with spaces, and takes liberties in incuding spaces that are present in the source file in several situations where LaTeX would remove them, including after macros. This is meant to be hopefully slightly more aesthetic. However, this option might inadvertently break up words: For instance:

      Sk\l odowska
      

      would be replaced by:

      Skł odowska
      
    • The value ‘macros’ is the same as specifying strict_latex_spaces=False, and it is the default. It will make macros and other sequences of LaTeX constructions obey LaTeX space rules, but will keep indentations after comments and keep more liberal whitespace rules in equations for a hopefully more aesthetic result.

    • The ‘except-in-equations’ preset goes as you would expect, setting strict latex spacing only outside of equation contexts.

    Finally, the argument strict_latex_spaces may also be set to a dictionary with keys ‘between-macro-and-chars’, ‘after-comment’, ‘between-latex-constructs’, and ‘in-equations’, with individual values either True or False, dictating whitespace behavior in specific cases (True indicates strict latex behavior). The value for ‘in-equations’ may even be another dictionary with the same keys to override values in equations. A value of False for ‘in-equation’ has the same meaning as ‘macros’.

    Changed in version 2.0: Since pylatexenc 2.0, the default value of strict_latex_spaces is ‘macros’, and no longer ‘based-on-source’.

    Deprecated since version 2.0: The value ‘default’ is also accepted, but it is no longer the default! It is an alias for ‘based-on-source’

    Changed in version 2.6: In pylatexenc versions 2.0–2.5, contrary to the documentation, the default value of strict_latex_spaces was actually still ‘based-on-source’. This bug was fixed in version 2.6, so that now, the default setting is actually ‘macros’.

  • keep_braced_groups=True|False: If set to True, then braces delimiting a TeX group {Like this} will be kept in the output, with the contents of the group converted to text as usual. (By default this is False)

  • keep_braced_groups_minlen=<int>: If keep_braced_groups is set to True, then we keep braced groups only if their contents length (after conversion to text) is longer than the given value. E.g., if keep_braced_groups_minlen=2, then {\'e}tonnant still goes to étonnant but {\'etonnant} becomes {étonnant}.

Additionally, the following arguments are accepted for backwards compatibility:

  • keep_inline_math=True|False: Obsolete since pylatexenc 2. If set to True, then this is the same as math_mode=’verbatim’, and if set to False, this is the same as math_mode=’text’.

    Deprecated since version 2.0: The keep_inline_math= option is deprecated because it had a weird behavior and was poorly implemented, especially given that a similarly named option in LatexWalker had a different effect. See issue #14.

  • text_replacements this argument is ignored starting from pylatexenc 2.

    Deprecated since version 2.0: Text replacements are no longer made at the end of the text conversion. This feature is replaced by the concept of LaTeX specials—see, e.g., pylatexenc.latexwalker.LatexSpecialsNode.

    To keep existing code working, add a call to apply_text_replacements() immediately after nodelist_to_text() to achieve the same effect as in pylatexenc 1.x. See apply_text_replacements().

  • env_dict, macro_dict: Obsolete since pylatexenc 2. If set, they are dictionaries of known environment and macro definitions. They default to default_env_dict and default_macro_dict, respectively.

    Deprecated since version 2.0: You should now use the more powerful option latex_context_db=. You cannot specify both macro_list (or env_list) and latex_context_db.

state

The current conversion state, as a TextConversionState object. It keeps track of the surroundings in which the node currently being converted appears. Use push_state() to temporarily override some of its fields.

Added in version 3.0: This attribute was introduced in pylatexenc 3.0.

property strict_latex_spaces

The whitespace behavior that applies where we currently are in the node tree. This is a shorthand for the strict_latex_spaces field of the current state.

property math_expression_in

The delimiters that are placed around a mathematical sub-expression which we could not render directly, where we currently are in the node tree. This is a shorthand for the math_expression_in field of the current state.

push_state(**kwargs)

Install a new current state in which the fields given as keyword arguments take the given new values (see TextConversionState.sub_state()), and restore the present state when we are done.

The return value is meant to be used as a context manager:

with l2tobj.push_state(in_math_mode=True):
    contents = l2tobj.nodelist_to_text(node.nodelist)

Any conversion that happens within the with block, including in simplify_repl callables that are invoked there, sees the new state.

Added in version 3.0: This method was introduced in pylatexenc 3.0.

set_tex_input_directory(tex_input_directory, latex_walker_init_args=None, strict_input=True)

Set where to look for input files when encountering the \input or \include macro.

Alternatively, you may also override read_input_file() to implement a custom file lookup mechanism.

The argument tex_input_directory is the directory relative to which to search for input files.

If strict_input is set to True, then we always check that the referenced file lies within the subtree of tex_input_directory, prohibiting for instance hacks with ‘..’ in filenames or using symbolic links to refer to files out of the directory tree.

The argument latex_walker_init_args allows you to specify the parse flags passed to the constructor of pylatexenc.latexwalker.LatexWalker when parsing the input file.

read_input_file(fn)

This method may be overridden to implement a custom lookup mechanism when encountering \input or \include directives.

The default implementation looks for a file of the given name relative to the directory set by set_tex_input_directory(). If strict_input=True was set, we ensure strictly that the file resides in a subtree of the reference input directory (after canonicalizing the paths and resolving all symlinks).

If set_tex_input_directory() was not called, or if it was called with a value of None, then no file system access is attempted an an empty string is returned.

You may override this method to obtain the input data in however way you see fit. In that case, a call to set_tex_input_directory() may not be needed as that function simply sets properties which are used by the default implementation of read_input_file().

This function accepts the referred filename as argument (the argument to the \input macro), and should return a string with the file contents (or generate a warning or raise an error).

latex_to_text(latex, **parse_flags)

Parses the given latex code and returns its textual representation.

This is equivalent to constructing a pylatexenc.latexwalker.LatexWalker with the given latex string, parsing the string into general nodes with a LatexGeneralNodesParser (see parse_content()), and providing the outcome to nodelist_to_text().

The parse_flags are keyword arguments to provide to the pylatexenc.latexwalker.LatexWalker constructor.

nodelist_to_text(nodelist, state=None)

Extracts text from a node list. nodelist is a list of latexwalker nodes, typically parsed using a LatexGeneralNodesParser (see parse_content()).

This function basically applies node_to_text() to each node and concatenates the results into one string. (This is not quite actually the case, since we take some care as to where we add whitespace according to the class options.)

If state is given, it is a TextConversionState instance that is used as the current conversion state while converting the given nodes. By default (state=None) we keep the current state, which is what you want in the vast majority of cases; see push_state() to install a modified state.

In math mode with math_mode='fancy', the return value is a math piece (see make_math_piece()) rather than a string, because the result of rendering a formula still has something to say about how it wants to be joined to whatever surrounds it. Use str() on the result if you need the text itself; every other case returns an ordinary string as it always did.

Added in version 3.0: The state argument was introduced in pylatexenc 3.0, as was the math piece return value of math_mode='fancy'.

node_to_text(node, prev_node_hint=None, textcol=0, state=None)

Return the textual representation of the given node.

If prev_node_hint is specified, then the current node is formatted suitably as following the node given in prev_node_hint. This might affect how much space we keep/discard, etc.

The state argument has the same meaning as in nodelist_to_text().

Added in version 3.0: The state argument was introduced in pylatexenc 3.0.

chars_node_to_text(node, textcol=0)

Return the textual representation of the given node representing a block of simple latex text with no special characters or macros. The node is LatexCharsNode.

The font style of the current conversion state, if there is one, is applied here, at the leaves of the node tree, so that it also reaches the characters that are nested inside groups and inside the arguments of macros. See the text_fontstyle and math_fontstyle fields of TextConversionState.

comment_node_to_text(node)

Return the textual representation of the given node representing a latex comment. The node is LatexCommentNode.

group_node_to_text(node)

Return the textual representation of the given node representing a latex group. The node is LatexGroupNode.

macro_node_to_text(node)

Return the textual representation of the given node representing a latex macro invocation. The node is LatexMacroNode.

environment_node_to_text(node)

Return the textual representation of the given node representing a full latex environment. The node is LatexEnvironmentNode.

specials_node_to_text(node)

Return the textual representation of the given node representing special a latex character (or characters). The node is LatexSpecialsNode.

math_node_to_text(node)

Return the textual representation of the given node representing a block of math mode latex. The node is either a LatexMathNode or a LatexEnvironmentNode.

This method is responsible for honoring the math_mode=… option provided to the constructor.

make_math_piece(*, text=None, cls=None, inner_text=None, prefix='', cls_wrapped=None, inner_cls=None, script_kind=None, script_latex_notation=False)

Create a math piece, the object that a simplify_repl callable returns instead of an ordinary string when it wants to say something about how its rendering should be joined to its neighbors in a formula.

This is only meaningful with math_mode='fancy', and only for a node that sits in math mode; anywhere else a simplify_repl callable must keep returning an ordinary string.

A math piece carries the rendered text along with a pair of atom classes, one describing its left edge and one describing its right edge. The atom classes are the ones that TeX itself uses to decide how much space to leave between two neighboring items of a formula, plus a few of ours:

  • ‘ord’: ordinary — a variable, a digit, an ordinary symbol. This is the default, and it means “join me tightly to my neighbor”.

  • ‘op’: the name of a function or a large operator, such as ‘sin’ or ‘∑’.

  • ‘bin’: a binary operator, such as ‘+’.

  • ‘rel’: a relation, such as ‘=’ or ‘→’.

  • ‘open’ and ‘close’: an opening or a closing delimiter.

  • ‘punct’: the punctuation marks ‘,’ and ‘;’.

  • ‘openend’: a rendering that has no visible extent on that side, such as ‘x^q’ or ‘a/b’; whatever comes next would look as if it were part of it.

  • ‘text’: a fragment of ordinary text, which is treated as opaque.

  • ‘script’: a superscript or a subscript, which binds to the piece on its left.

  • ‘block’: a large object such as a matrix, which brings its own delimiters.

The arguments are keyword-only:

  • text is the rendered text of the piece.

  • cls is its atom class: either one of the names above, which then applies to both edges, or a pair of names for the left and the right edge. The default, None, means ordinary on both edges.

  • inner_text, if it is given instead of text, asks for a piece that decides only once it knows its neighbors whether to enclose its contents in delimiters. This is what the superscript ‘x_{abc}’ needs: it can be written bare when nothing follows it, but it has to become ‘x_(abc)’ in ‘x_{abc}^2’, where a space would not be enough to show where the subscript ends. The delimiters are the ones given by the math_expression_in= option, taken from the current conversion state.

  • prefix is text that always precedes the contents of such a piece and always stays outside the delimiters, such as the ‘^’ or ‘_’ of a script.

  • cls_wrapped is the atom class that such a piece presents when its contents did end up enclosed in delimiters. It defaults to the left edge class of cls along with a right edge class of ‘close’, since a closing delimiter is then the last thing in the rendering.

  • inner_cls is the atom class of the contents themselves, used to find out whether the contents are open-ended. It defaults to a classification of inner_text by inspecting its characters.

  • script_kind is ‘superscript’ or ‘subscript’ if this piece is a superscript or a subscript, and None otherwise. A superscript that is immediately followed by a subscript is swapped with it, so that the subscript attaches to the base first.

  • script_latex_notation says that a superscript or subscript piece had to fall back onto LaTeX’s own ‘^’ and ‘_’ notation instead of the unicode superscript and subscript characters. A space is then also placed in front of the base that the script attaches to, so that one can see where the base begins.

Added in version 3.0: This method was introduced in pylatexenc 3.0.

apply_simplify_repl(node, simplify_repl, what)

Utility to get the replacement text associated with a node for which we have a simplify_repl object (given by e.g. a MacroTextSpec or similar).

The argument what is used in error messages.

node_arg_to_text(node, k)

Return the textual representation of the k-th argument of the given node. This might be useful for substitution lambdas in macro and environment specs.

apply_text_replacements(s, text_replacements)

Convenience function for code that used text_replacements= in pylatexenc 1.x.

If you used custom text_replacements= in pylatexenc 1.x then you will have to change:

# pylatexenc 1.x with text_replacements
text_replacements = ...
l2t = LatexNodes2Text(..., text_replacements=text_replacements)
text = l2t.nodelist_to_text(...)

to:

# pylatexenc 2 text_replacements compatibility code
text_replacements = ...
l2t = LatexNodes2Text(...)
temp = l2t.nodelist_to_text(...)
text = l2t.apply_text_replacements(temp, text_replacements)

as a quick fix. It is recommended however to treat text replacements instead as “latex specials”. (Otherwise the brutal text replacements might act on text generated from macros and environments and give unwanted results.) See pylatexenc.macrospec.SpecialsSpec and SpecialsTextSpec.

Deprecated since version 2.0: The apply_text_replacements() method was introduced in pylatexenc 2.0 as a deprecated method. You can use it as a quick fix to make existing code run as it did in pylatexenc 1.x. Its use is however not recommended for new code. You should use “latex specials” instead for characters that have special LaTeX meaning.

class pylatexenc.latex2text.TextConversionState(strict_latex_spaces=None, in_math_mode=False, list_stack=None, math_expression_in='parens', text_fontstyle=None, math_fontstyle='italic')

Describes the surroundings in which a node is being converted to text, that is, everything that the text representation of a node may depend on beyond the node itself.

This is the latex2text counterpart of pylatexenc.latexnodes.ParsingState, which plays the same role while the LaTeX code is being parsed. Note that the latex context database (pylatexenc.macrospec.LatexContextDb) is a different thing altogether: it holds the definitions of macros, environments and specials, and it does not change as we walk the node tree.

A LatexNodes2Text object always has a “current state”, stored in its state attribute. The state is inherited by the nodes that are converted deeper down in the node tree; a node that changes the surroundings of its contents (say, an equation, or a list environment) installs a modified state for the duration of the conversion of its contents. See LatexNodes2Text.push_state().

A simplify_repl callable in a MacroTextSpec, EnvironmentTextSpec or SpecialsTextSpec receives the current state if it declares an argument named l2tstate (see LatexNodes2Text.apply_simplify_repl()).

strict_latex_spaces

The whitespace behavior that applies here, as a dictionary in the form returned by parsing the strict_latex_spaces= option of LatexNodes2Text (with the keys ‘between-macro-and-chars’, ‘between-latex-constructs’, ‘after-comment’ and ‘in-equations’).

in_math_mode

Whether or not the node being converted lies in math mode.

list_stack

The list environments that we are currently inside of, outermost first. Each entry describes one nesting level and provides the attributes environmentname, kind, depth and counter. The list is empty outside of any list environment.

math_expression_in

The delimiters that are placed here around a mathematical sub-expression which could not be rendered directly in plain text, for instance the argument of a superscript for which there is no rendering with unicode superscript characters. This is a pair of strings with the opening and the closing delimiter, or None if no delimiters are to be added.

This field is set up from the math_expression_in= option of LatexNodes2Text, where the accepted values are documented. Because it is part of the state, it can be changed for one part of the document only, see LatexNodes2Text.push_state().

text_fontstyle

The font style that applies to the characters that are typeset here in text mode, as one of the style names accepted by fmt_math_text_style(), or None for the upright style. It is what \textbf{}, \textsf{}, \emph{} and friends install for the duration of their contents; its initial value comes from the text_fontstyle= option of LatexNodes2Text.

The value False is special: it says that the characters typeset here are to be left as they are, with no unicode alphabet applied to them at all. The font style macros do not replace it — they leave a False where they find one — so it holds for the entire document, which is what the text_fontstyle=False option is for.

math_fontstyle

The font style that applies to the characters that are typeset here in math mode, as one of the style names accepted by fmt_math_text_style(), or None for the upright style. It is what \mathbf{}, \mathcal{} and friends install for the duration of their contents; its initial value comes from the math_fontstyle= option of LatexNodes2Text.

Math mode italicizes the variable names, so this field starts out as ‘italic’ where text_fontstyle starts out upright.

As for text_fontstyle, the value False says that no unicode alphabet is to be applied to these characters at all, and the font style macros leave it alone where they find it.

The two font styles are kept apart because they are stacked independently: crossing into math mode and back out of it, as in \textit{... $\mathbf{a+\text{[b]}}$}, has to restore the text style that was in force outside, which the excursion into math mode never disturbed.

Added in version 3.0: This class was introduced in pylatexenc 3.0.

sub_state(**kwargs)

Return a copy of this state in which the fields given as keyword arguments take the given new values. All other fields keep the value they have in the present state.

This state object itself is left unchanged.

pylatexenc.latex2text.get_default_latex_context_db()

Return a pylatexenc.macrospec.LatexContextDb instance initialized with a collection of text replacements for known macros and environments.

The text replacements are grouped into the following categories, which you can select or discard individually with pylatexenc.macrospec.LatexContextDb.filter_context():

  • 'latex-base' — the bulk of the standard LaTeX constructs, including sectioning commands, font commands, accents, Greek letters, and the common math symbols, each mapped to a unicode text rendering.

  • 'latex-base-subsuperscripts' — the text rendering of the ^ and _ specials, i.e., the unicode superscripts and subscripts. This category matches the one of the same name in pylatexenc.latexwalker.get_default_latex_context_db(), so that discarding it in both databases restores the pylatexenc 2 behavior in which ^ and _ were ordinary characters.

  • 'latex-approximations' — constructs for which the text rendering can only be an approximation of the typeset result, such as the alignment environments, the list environments, and matrix environments.

  • 'latex-placeholders' — constructs that are replaced by a placeholder rather than by their contents, such as \includegraphics, the cross-referencing macros (rendered as <ref>) and the citation macros (rendered as <cit.>).

  • 'nonascii-specials' — the character sequences that LaTeX gives a special meaning, mapped to the corresponding unicode character (~ to a no-break space, --- to an em dash, and so on).

  • 'advanced-symbols' — the symbol macros that correspond to the built-in rules of pylatexenc.latexencode, i.e., the reverse direction of the unicode-to-LaTeX conversion.

If you want to add your own definitions, you should use the pylatexenc.macrospec.LatexContextDb.add_context_category() method. If you would like to override some definitions, use that method with the argument prepend=True. See docs for pylatexenc.macrospec.LatexContextDb.add_context_category().

If there are too many macro/environment definitions, or if there are some irrelevant ones, you can always filter the returned database using pylatexenc.macrospec.LatexContextDb.filter_context().

Added in version 2.0: The pylatexenc.macrospec.LatexContextDb class as well as this method, were all introduced in pylatexenc 2.0.

Define replacement texts

class pylatexenc.latex2text.MacroTextSpec(macroname, simplify_repl=None, discard=None)

A specification of how to obtain a textual representation of a macro.

macroname

The name of the macro (no backslash)

simplify_repl

The replacement text of the macro invocation. This is either a string or a callable:

  • If simplify_repl is a string, this string is used as the text representation of this macro node.

    The string may contain a single ‘%s’ replacement placeholder which will be replaced by the concatenated textual representation of all macro arguments. Alternatively, the string may contain ‘%(<n>)s’ (where <n> is an integer) to refer to the n-th argument (starting at ‘%(1)s’). You cannot mix the two %-formatting styles.

  • If simplify_repl is a callable, it should accept the corresponding pylatexenc.latexwalker.LatexMacroNode as an argument.

    The callable will be inspected to see what other arguments it accepts. If it accepts an argument named l2tobj, the LatexNodes2Text instance is provided to that argument. If it accepts an argument named macroname, the name of the macro is provided to that argument. If it accepts an argument named l2tstate, the TextConversionState that applies where this macro sits in the node tree is provided to that argument.

discard

If set to True, then the macro call is discarded, i.e., it is converted to an empty string.

Added in version 2.0: The class MacroTextSpec was introduced in pylatexenc 2.0 to succeed to the previously named MacroDef class.

class pylatexenc.latex2text.EnvironmentTextSpec(environmentname, simplify_repl=None, discard=False)

A specification of how to obtain a textual representation of an environment.

environmentname

The name of the environment

simplify_repl

The replacement text of the environment. This is either a string or a callable:

  • If simplify_repl is a string, this string is used as the text representation of this environment node.

    The string may contain a single ‘%s’ replacement placeholder, in which the (processed) environment body will be substituted.

    Alternatively, the simplify_repl string may contain ‘%(<n>)s’ (where <n> is an integer) to refer to the n-th argument after egin{environment} (starting at ‘%(1)s’). The body of the environment has to be referred to with %(body)s.

    You cannot mix the two %-formatting styles.

  • If simplify_repl is a callable, it should accept the corresponding pylatexenc.latexwalker.LatexEnvironmentNode as an argument.

    The callable will be inspected to see what other arguments it accepts. If it accepts an argument named l2tobj, the LatexNodes2Text instance is provided to that argument. If it accepts an argument named environmentname, the name of the environment is provided to that argument. If it accepts an argument named l2tstate, the TextConversionState that applies where this environment sits in the node tree is provided to that argument.

discard

If set to True, then the full environment is discarded, i.e., it is converted to an empty string.

Added in version 2.0: The class EnvironmentTextSpec was introduced in pylatexenc 2.0 to succeed to the previously named EnvDef class.

class pylatexenc.latex2text.SpecialsTextSpec(specials_chars, simplify_repl=None)

A specification of how to obtain a textual representation of latex specials.

specials_chars

The sequence of special LaTeX characters

simplify_repl

The replacement text for the given latex specials. This is either a string or a callable:

  • If simplify_repl is a string, this string is used as the text representation of this specials node.

    The string may contain a single ‘%s’ replacement placeholder which will be replaced by the concatenated textual representation of all macro arguments.

    Alternatively, the string may contain ‘%(<n>)s’ (where <n> is an integer) to refer to the n-th argument (starting at ‘%(1)s’). You cannot mix the two %-formatting styles.

  • If simplify_repl is a callable, it should accept the corresponding pylatexenc.latexwalker.LatexSpecialsNode as an argument.

    The callable will be inspected to see what other arguments it accepts. If it accepts an argument named l2tobj, the LatexNodes2Text instance is provided to that argument. If it accepts an argument named specials_chars, the characters that were parsed this “latex specials” node are provided to that argument. If it accepts an argument named l2tstate, the TextConversionState that applies where these specials sit in the node tree is provided to that argument.

Added in version 2.0: Latex specials were introduced in pylatexenc 2.0.

Formatting helpers

Most of the following functions are meant to be used directly as the simplify_repl callable of a MacroTextSpec, EnvironmentTextSpec or SpecialsTextSpec. They implement the default rendering of the corresponding LaTeX constructs, and can be reused (or wrapped) when you define your own replacement rules. The last two are plain string helpers that convert text to the corresponding unicode styled or superscript/subscript characters.

pylatexenc.latex2text.fmt_equation_environment(envnode, l2tobj)

Can be used as callback for display equation environments.

Added in version 2.0: This function was introduced in pylatexenc 2.0.

pylatexenc.latex2text.fmt_input_macro(macronode, l2tobj)

This function can be used as callback in MacroTextSpec for \input or \include macros. The macronode must be a macro node with a single argument. If set_tex_input_directory() was called with a nonempty input directory in the LatexNodes2Text object, then this method reads the contents of the file name in the macro argument according to the provided settings. Otherwise, returns an empty string.

Added in version 2.0: This function was introduced in pylatexenc 2.0.

pylatexenc.latex2text.placeholder_node_formatter(placeholdertext, block=True)

This function returns a callable that can be used in MacroTextSpec, EnvironmentTextSpec, or SpecialsTextSpec for latex nodes that do not have a good textual representation, providing as text replacement the simple placeholder text '< P L A C E H O L D E R   T E X T >'.

If block=True (the default), the placeholder text is typeset in an indented block on its own. Otherwise, it is typeset inline.

Added in version 2.0: This function was introduced in pylatexenc 2.0.

pylatexenc.latex2text.fmt_placeholder_node(node, l2tobj)

This function can be used as callable in MacroTextSpec, EnvironmentTextSpec, or SpecialsTextSpec for latex nodes that do not have a good textual representation. The text replacement is the placeholder text '< N A M E   O F   T H E   M A C R O   O R   E N V I R O N M E N T >'.

Added in version 2.0: This function was introduced in pylatexenc 2.0.

pylatexenc.latex2text.fmt_matrix_environment_node(node, l2tobj)

This function can be used as a callable in EnvironmentTextSpec for matrix-like environments like \begin{bmatrix}...\end{bmatrix}.

The contents is parsed by separating columns with &’s and rows with \\’s, and is rendered in the form [  a11  a12  ;  a21  a22  ].

Added in version 2.8: This function was introduced in pylatexenc 2.8.

Changed in version 3.0: In math mode with math_mode='fancy', this function returns a math piece (see LatexNodes2Text.make_math_piece()) instead of a string, so that the formula joiner treats the whole object as a single item and does not look inside it. The rendering itself is unchanged.

pylatexenc.latex2text.fmt_list_environment(node, l2tobj, environmentname)

This function can be used as a callable in EnvironmentTextSpec for list environments like \begin{itemize}...\end{itemize} and \begin{enumerate}...\end{enumerate}.

The environment contents is split at the \item macros and each item is rendered as an indented block introduced by an item marker. Items are numbered where relevant, and the marker style is chosen according to the lists that we are already inside of, as recorded in the list_stack field of the current TextConversionState, so that nested lists are rendered correctly.

An explicit item label given as \item[label] is used as the item marker and, as in LaTeX, does not advance the item counter.

Added in version 3.0: This function was introduced in pylatexenc 3.0.

pylatexenc.latex2text.fmt_list_item(itemnode, itembody, l2tobj, level)

Render a single item of a list environment. The itemnode is the \item macro node (or None), itembody is the list of nodes that make up the contents of the item, and level describes the list level in which this item appears (see fmt_list_environment()).

Added in version 3.0: This function was introduced in pylatexenc 3.0.

pylatexenc.latex2text.fmt_item_macro(node, l2tobj)

This function can be used as a callable in MacroTextSpec for the \item macro. It is only used for \item macros that appear outside of any list environment that we know how to format; items within a known list environment are rendered by fmt_list_environment().

Added in version 3.0: This function was introduced in pylatexenc 3.0.

pylatexenc.latex2text.fmt_math_text_style(text, style)

Return the text with letters replaced by unicode characters so that the style style is applied. (We use the unicode math alphanumeric symbols, see the unicode chart.)

The style must be one of ‘bold’, ‘italic’, ‘bold-italic’, ‘script’, ‘bold-script’, ‘fraktur’, ‘doublestruck’, ‘bold-fraktur’, ‘sans’, ‘sans-bold’, ‘sans-italic’, ‘sans-bold-italic’, or ‘monospace’.

The character c is essentially expected to be an ascii letter, and any other character will be returned unchanged. (Possible exceptions might be implemented in the future, for instance to implement the double-struck one/identity operator \mathbbm{1}.)

pylatexenc.latex2text.fmt_subsuperscript_text(text, which, normalize_math_style_chars=False)

Return text typeset with unicode superscript characters (which=’superscript’) or with unicode subscript characters (which=’subscript’).

Unicode only offers superscript and subscript versions of a limited set of characters. If any character in text does not have a corresponding superscript/subscript character, then None is returned. It is then up to the caller to represent the superscript or subscript in some other way.

If normalize_math_style_chars is set, then a letter of the unicode math alphanumeric symbols (see fmt_math_text_style()) is taken back to the plain ascii letter it was made from before it is looked up, because unicode offers no styled superscript or subscript characters; the style of such a letter is then lost, but the superscript or subscript can still be typeset. This is what LatexNodes2Text needs whenever the letters of a formula are being styled — italicized, say, which is the default — because the argument of a superscript then reaches this function already styled. By default the option is off, and a styled letter simply has no superscript or subscript version.

The default text replacement specs fall back onto writing out the ‘^’ or ‘_’ character followed by the superscript or subscript rendered as ordinary text; whether and how that text is enclosed in delimiters is decided by the math_expression_in= option of LatexNodes2Text (see fmt_math_expression_in_delimiters()).

Added in version 3.0: This function was introduced in pylatexenc 3.0.

Obsolete members

pylatexenc.latex2text.EnvDef(envname, simplify_repl=None, discard=False)

Deprecated since version 2.0: Instantiate a EnvironmentTextSpec instead.

Since pylatexenc 2.0, EnvDef is a function which returns a EnvironmentTextSpec instance. In this way the earlier idiom EnvDef(...) still works in pylatexenc 2.

pylatexenc.latex2text.MacroDef(macname, simplify_repl=None, discard=None)

Deprecated since version 2.0: Instantiate a MacroTextSpec instead.

Since pylatexenc 2.0, MacroDef is a function which returns a MacroTextSpec instance. In this way the earlier idiom MacroDef(...) still works in pylatexenc 2.

pylatexenc.latex2text.default_env_dict

Deprecated since version 2.0: Use get_default_latex_context_db() instead, or create your own pylatexenc.macrospec.LatexContextDb object.

Provide an access to the default environment text replacement specs for latex2text in a form that is compatible with pylatexenc 1.x‘s default_macro_dict module-level dictionary.

This is implemented using a custom lazy mutable mapping, which behaves just like a regular dictionary but that loads the data only once the dictionary is accessed. In this way the default latex specs into a python dictionary unless they are actually queried or modified, and thus users of pylatexenc 2.0 that don’t rely on the default macro/environment definitions shouldn’t notice any decrease in performance.

pylatexenc.latex2text.default_macro_dict

Deprecated since version 2.0: Use get_default_latex_context_db() instead, or create your own pylatexenc.macrospec.LatexContextDb object.

Provide an access to the default macro text replacement specs for latex2text in a form that is compatible with pylatexenc 1.x‘s default_macro_dict module-level dictionary.

This is implemented using a custom lazy mutable mapping, which behaves just like a regular dictionary but that loads the data only once the dictionary is accessed. In this way the default latex specs into a python dictionary unless they are actually queried or modified, and thus users of pylatexenc 2.0 that don’t rely on the default macro/environment definitions shouldn’t notice any decrease in performance.

pylatexenc.latex2text.default_text_replacements

Deprecated since version 2.0: Text replacements are deprecated since pylatexenc 2.0 with the advent of “latex specials”. See LatexNodes2Text.apply_text_replacements() for a quick solution to keep existing code working if it uses custom text replacements.