LaTeX::TOM(3pm)
π LaTeX::TOM π
okay bestie, welcome to LaTeX::TOM(3pm) β a Perl module for parsing, analyzing, and manipulating LaTeX documents. yes, that LaTeX. the one that makes your thesis compile at 3am. she's here, she's a User Contributed Perl Documentation page, and she's ready to spill. π
β¨ NAME β¨
LaTeX::TOM β a module for parsing, analyzing, and manipulating LaTeX documents. no cap, that's literally the whole vibe. π
πΈ SYNOPSIS πΈ
here's the tea, bestie β this is how you actually use her:
use LaTeX::TOM;
$parser = LaTeX::TOM->new;
$document = $parser->parseFile('mypaper.tex');
$latex = $document->toLaTeX;
$specialnodes = $document->getNodesByCondition(sub {
my $node = shift;
return (
$node->getNodeType eq 'TEXT'
&& $node->getNodeText =~ /magic string/
);
});
$sections = $document->getNodesByCondition(sub {
my $node = shift;
return (
$node->getNodeType eq 'COMMAND'
&& $node->getCommandName =~ /section$/
);
});
$indexme = $document->getIndexableText;
$document->print;
look at her go π¦ she parses, she queries, she prints. main character energy fr fr.
π DESCRIPTION π
so this module gives you a parser that parses and interprets (though not fully, okay, let's be honest about that) LaTeX documents, and hands you back a tree-based representation of everything it finds. that tree? it's a LaTeX::TOM::Tree. and that tree is full of LaTeX::TOM::Node nodes. it's trees all the way down, bestie. π
this module should be especially useful to anyone who wants to do processing of LaTeX documents that requires extraction of plain-text information, or altering of the plain-text components (or alternatively, the math-text components). so like, if you've ever wanted to reach into a .tex file and pull out the actual words without all the \command noise β yeah. this is your girl. β¨
π§ COMPONENTS π§
π LaTeX::TOM::Parser π
the parser recognizes 3 parameters upon creation by LaTeX::TOM->new. the parameters, in order, are:
- parse error handling (
= 0 || 1 || 2) β this one decides what happens when a parse error gets encountered.0results in a warning.1results in a die.2results in silence. π«’ note that particular groupings in LaTeX (i.e. newcommands and the like) contain invalid TeX or LaTeX, so you nearly always need this parameter to be0or2to completely parse the document. don't say I didn't warn you. π - read inputs flag (
= 0 || 1) β this flag determines whether a scan for\inputand\input-likecommands is performed, and the resulting called files parsed and added to the parent parse tree.0means no,1means do it. π₯ note that this will happen recursively if it is turned on. also, bibliographies (.bblfiles) are detected and included. she's thorough, okay?! - apply mappings flag (
= 0 || 1) β this flag determines whether (most) user-defined mappings are applied. that means\defs,\newcommands, and\newenvironments. this is critical for properly analyzing the content of the document, as this must be phrased in terms of the semantics of the original TeX and LaTeX commands, not ad hoc user macros. so, for instance, do not expect plain-text extraction to work properly with this option off. periodt. π
the parser returns a LaTeX::TOM::Tree ($document in the SYNOPSIS, if you were wondering who that mystery variable was). π
π¦ LaTeX::TOM::Node π¦
nodes may be of the following types, and honestly, get to know them, they're the whole cast:
TEXTβTEXTnodes can be thought of as representing the plain-text portions of the LaTeX document. this includes math and anything else that is not a recognized TeX or LaTeX command, or user-defined command. in reality,TEXTnodes contain commands that this parser does not yet recognize the semantics of. so it's giving "we know it's a command, we just don't know what it does yet." πCOMMANDβ aCOMMANDnode represents a TeX command. it always has child nodes in a tree, though the tree might be empty if the command operates on zero parameters. an example of a command is:
\textbf{blah}
this would parse into a COMMAND node for textbf, which would have a subtree containing the TEXT node with text ``blah.'' π
ENVIRONMENTβ similarly, TeX environments parse intoENVIRONMENTnodes, which have metadata about the environment, along with a subtree representing what is contained in the environment. for example:
\begin{equation}
r = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
\end{equation}
would parse into an ENVIRONMENT node of the class equation'' with a child tree containing the result of parsing r = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}.'' slay. π₯
GROUPβ aGROUPis like an anonymousCOMMAND. since you can put whatever you want in curly-braces ({}) in TeX in order to make semantically isolated regions, this separation is preserved by the parser. aGROUPis just the subtree of the parsed contents of plain curly-braces.
it is important to note that currently only the first GROUP in a series of GROUPs following a LaTeX command will actually be parsed into a COMMAND node. π the reason is that, for the initial purposes of this module, it was not necessary to recognize additional GROUPs as additional parameters to the COMMAND. however, this is something that this module really should do eventually. currently if you want all the parameters to a multi-parametered command, you'll need to pick out all the following GROUP nodes yourself. bestie, you're on your own for that part. π
eventually this will become something like a list which is stored in the COMMAND node, much like XML::DOM's treatment of attributes. these are, in a sense, apart from the rest of the document tree. then GROUP nodes will become much more rare. future goals, we love to see it. β¨
COMMENTβ aCOMMENTnode is very similar to aTEXTnode, except it is specifically for lines beginning with%'' (the TeX comment delimiter) or the right-hand portion of a line that has%'' at some internal point. so like, everything you thought was "invisible" in your source? she sees it. π
π LaTeX::TOM::Trees π
as mentioned before, the Tree is the return result of a parse.
the tree is nothing more than an arrayref of Nodes, some of which may contain their own trees. this is useful knowledge at this point, since the user isn't provided with a full suite of convenient tree-modification methods. π however, Trees do already have some very convenient methods, described in the next section. so like, don't panic, we've got some tools, and the next part of this page is gonna walk you through them. stay tuned, bestie. π
β¨ METHODS β¨
okay so here's the whole method rundown, grouped by component. Every method for every component is listed and described, no skips, periodt. π
π LaTeX::TOM
newβ instantiate a new parser object. And fr, in this section all of the methods for each of the components are listed and described. No gatekeeping.
π¦ LaTeX::TOM::Parser
The methods for the parser are:
parseFile (filename)β read in the contents offilenameand parse them, returning aLaTeX::TOM::Tree.parse (string)β parse thestringstring and return aLaTeX::TOM::Tree.
πΈ LaTeX::TOM::Tree
This section contains methods for the Trees returned by the parser.
copyβ duplicate a tree into new memory. clone era.printβ a debug print of the structure of the tree. for when you need to see the vibes.plainTextβ returns an arrayref which is a list of strings representing the text of allgetNodePlainTextFlag = 1TEXTnodes, in an inorder traversal.indexableTextβ a method like the above but which goes one step further; it cleans all of the returned text and concatenates it into a single string which one could consider having all of the standard information retrieval value for the document, making it useful for indexing.toLaTeXβ return a string representing the LaTeX encoded by the tree. This is especially useful to get a normal document again, after modifying nodes of the tree.getTopLevelNodesβ return a list ofLaTeX::TOM::Nodesat the top level of the Tree.getAllNodesβ return an arrayref with all nodes of the tree. This "flattens" the tree.getCommandNodesByName (name)β return an arrayref with allCOMMANDnodes in the tree which have a name matchingname.getEnvironmentsByName (name)β return an arrayref with allENVIRONMENTnodes in the tree which have a class matchingname.getNodesByCondition (code reference)β this is a catch-all search method which can be used to pull out nodes that match pretty much any perl expression, without manually having to traverse the tree.code referenceis a perl code reference which receives as its first argument the node of the tree that is currently scrutinized and is expected to return a boolean value. See the SYNOPSIS for examples.getFirstNodeβ returns the first node of the tree. This is useful if you want to walk the tree yourself, starting with the first node.
π LaTeX::TOM::Node
This section contains the methods for nodes of the parsed Trees.
getNodeTypeβ returns the type, one ofTEXT,COMMAND,ENVIRONMENT,GROUP, orCOMMENT, as described above.getNodeTextβ applicable forTEXTorCOMMENTnodes; this returns the document text they contain. This is undef for other node types.setNodeTextβ set the node text, also forTEXTandCOMMENTnodes.getNodeStartingPositionβ get the starting character position in the document of this node. ForTEXTandCOMMENTnodes, this will be where the text begins. ForENVIRONMENT,COMMAND, orGROUPnodes, this will be the position of the last character of the opening identifier.getNodeEndingPositionβ same as above, but for last character. ForGROUP,ENVIRONMENT, orCOMMANDnodes, this will be the first character of the closing identifier.getNodeOuterStartingPositionβ same asgetNodeStartingPosition, but forGROUP,ENVIRONMENT, orCOMMANDnodes, this returns the first character of the opening identifier.getNodeOuterEndingPositionβ same asgetNodeEndingPosition, but forGROUP,ENVIRONMENT, orCOMMANDnodes, this returns the last character of the closing identifier.getNodeMathFlagβ this applies to any node type. It is1if the node sets, or is contained within, a math mode region.0otherwise.TEXTnodes which have this flag as1can be assumed to be the actual mathematics contained in the document.getNodePlainTextFlagβ this applies only toTEXTnodes. It is1if the node is non-math and is visible (in other words, will end up being a part of the output document). One would only want to indexTEXTnodes with this property, for information retrieval purposes.getEnvironmentClassβ this applies only toENVIRONMENTnodes. Returns what class of environment the node represents (theXin\begin{X}and\end{X}).getCommandNameβ this applies only toCOMMANDnodes. Returns the name of the command (theXin\X{...}).getChildTreeβ this applies only toCOMMAND,ENVIRONMENT, andGROUPnodes: it returns theLaTeX::TOM::Treewhich is "under" the calling node.getFirstChildβ this applies only toCOMMAND,ENVIRONMENT, andGROUPnodes: it returns the first node from the first level of the child subtree.getLastChildβ same as above, but for the last node of the first level.getPreviousSiblingβ return the prior node on the same level of the tree.getNextSiblingβ same as above, but for following node.getParentβ get the parent node of this node in the tree.getNextGroupNodeβ this is an interesting function, and kind of a hack because of the way the parser makes the current tree. Basically it will give you the next sibling that is aGROUPnode, until it either hits the end of the tree level, aTEXTnode which doesn't match/^\s*$/, or aCOMMANDnode.
This is useful for finding all GROUPed parameters after a COMMAND node (see comments for GROUP in the COMPONENTS / LaTeX::TOM::Node section). You can just have a while loop that calls this method until it gets undef, and you'll know you've found all the parameters to a command.
Note: this may be bad, but TEXT Nodes matching /^\s*\[[0-9]+\]$/ (optional parameter groups) are treated as if they were 'blank'.
π« CAVEATS π«
Because there aren't tree-modification methods, currently this module is mostly useful for minor modifications to the parsed document, for instance, altering the text of TEXT nodes but not deleting the nodes. Of course, the user can still do this by breaking abstraction and directly modifying the Tree.
Also note that the parsing is not complete. This module was not written with the intention of being able to produce output documents the way latex does. The intent was instead to be able to analyze and modify the document on a logical level with regards to the content; it doesn't care about the document formatting and outputting side of TeX/LaTeX.
There is much work still to be done. See the TODO list in the TOM.pm source.
π BUGS π
Probably plenty. However, this module has performed fairly well on a set of ~1000 research publications from the Computing Research Repository, so I deemed it "good enough" to use for purposes similar to mine.
Please let the maintainer know of parser errors if you discover any.
π CREDITS π
Thanks to (in order of appearance) who have contributed valuable suggestions and patches:
- Otakar Smrz
- Moritz Lenz
- James Bowlin
- Jesse S. Bangs
- Cord Merrell
- Debian Perl Group
- Eli Billauer
π AUTHORS π
Written by Aaron Krowne <akrowne@vt.edu>
Maintained by Steven Schubiger <schubiger@cpan.org>
π LICENSE π
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
See <http://dev.perl.org/licenses/>
and that's the whole page, bestie! This one's from perl v5.36.0, dated 2023-04-03, and it's the LaTeX::TOM(3pm) manpage. slay, go parse something cute π
β¨
π¦ where this page comes from
- debian bookworm: liblatex-tom-perl 1.06-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: liblatex-tom-perl 1.06-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: liblatex-tom-perl 1.06-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: liblatex-tom-perl 1.06-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: liblatex-tom-perl 1.06-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms