A module for parsing, analyzing, and manipulating latex documents.
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;
This module provides a parser which parses and interprets (though not fully) LaTeX documents and returns a tree-based representation of what it finds. This tree is a \*(C`LaTeX::TOM::Tree\*(C'. The tree contains \*(C`LaTeX::TOM::Node\*(C' nodes.
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).
The parser recognizes 3 parameters upon creation. The parameters, in order, are
Determines what happens when a parse error is encountered. 0 results in a warning. 1 results in a die. 2 results 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 be 0 or 2 to completely parse the document.
This flag determines whether a scan for \*(C`\input\*(C' and \*(C`\input-like\*(C' commands is performed, and the resulting called files parsed and added to the parent parse tree. 0 means no, 1 means do it. Note that this will happen recursively if it is turned on. Also, bibliographies (.bbl files) are detected and included.
This flag determines whether (most) user-defined mappings are applied. This means \*(C`\defs\*(C', \*(C`\newcommands\*(C', and \*(C`\newenvironments\*(C'. 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.
The parser returns a \*(C`LaTeX::TOM::Tree\*(C' ($document in the \s-1SYNOPSIS\s0).
Nodes may be of the following types:
\*(C`TEXT\*(C' nodes 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, \*(C`TEXT\*(C' nodes contain commands that this parser does not yet recognize the semantics of.
A \*(C`COMMAND\*(C' node 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 \*(C`COMMAND\*(C' node for \*(C`textbf\*(C', which would have a subtree containing the \*(C`TEXT\*(C' node with text ``blah.''
Similarly, TeX environments parse into \*(C`ENVIRONMENT\*(C' nodes, 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 \*(C`ENVIRONMENT\*(C' node of the class ``equation'' with a child tree containing the result of parsing ``r = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}.''
A \*(C`GROUP\*(C' is like an anonymous \*(C`COMMAND\*(C'. Since you can put whatever you want in curly-braces (\*(C`{}\*(C') in TeX in order to make semantically isolated regions, this separation is preserved by the parser. A \*(C`GROUP\*(C' is just the subtree of the parsed contents of plain curly-braces. It is important to note that currently only the first \*(C`GROUP\*(C' in a series of \*(C`GROUP\*(C's following a LaTeX command will actually be parsed into a \*(C`COMMAND\*(C' node. The reason is that, for the initial purposes of this module, it was not necessary to recognize additional \*(C`GROUP\*(C's as additional parameters to the \*(C`COMMAND\*(C'. 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 \*(C`GROUP\*(C' nodes yourself. Eventually this will become something like a list which is stored in the \*(C`COMMAND\*(C' node, much like \s-1XML::DOM\s0's treatment of attributes. These are, in a sense, apart from the rest of the document tree. Then \*(C`GROUP\*(C' nodes will become much more rare.
A \*(C`COMMENT\*(C' node is very similar to a \*(C`TEXT\*(C' node, except it is specifically for lines beginning with ``%'' (the TeX comment delimeter) or the right-hand portion of a line that has ``%'' at some internal point.
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.
new Instantiate a new parser object.
In this section all of the methods for each of the components are listed and described.
The methods for the parser (aside from the constructor, discussed above) are :
parseFile (filename) Read in the contents of filename and parse them, returning a \*(C`LaTeX::TOM::Tree\*(C'.
parse (string) Parse the string string and return a \*(C`LaTeX::TOM::Tree\*(C'.
This section contains methods for the Trees returned by the parser.
copy Duplicate a tree into new memory.
print A debug print of the structure of the tree.
plainText Returns an arrayref which is a list of strings representing the text of all \*(C`getNodePlainTextFlag = 1\*(C' \*(C`TEXT\*(C' nodes, 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 of \*(C`LaTeX::TOM::Nodes\*(C' at the top level of the Tree.
getAllNodes Return an arrayref with all nodes of the tree. This \*(L"flattens\*(R" the tree.
getCommandNodesByName (name) Return an arrayref with all \*(C`COMMAND\*(C' nodes in the tree which have a name matching name.
getEnvironmentsByName (name) Return an arrayref with all \*(C`ENVIRONMENT\*(C' nodes in the tree which have a class matching name.
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 reference is 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 \s-1SYNOPSIS\s0 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.
This section contains the methods for nodes of the parsed Trees.
getNodeType Returns the type, one of \*(C`TEXT\*(C', \*(C`COMMAND\*(C', \*(C`ENVIRONMENT\*(C', \*(C`GROUP\*(C', or \*(C`COMMENT\*(C', as described above.
getNodeText Applicable for \*(C`TEXT\*(C' or \*(C`COMMENT\*(C' nodes; this returns the document text they contain. This is undef for other node types.
setNodeText Set the node text, also for \*(C`TEXT\*(C' and \*(C`COMMENT\*(C' nodes.
getNodeStartingPosition Get the starting character position in the document of this node. For \*(C`TEXT\*(C' and \*(C`COMMENT\*(C' nodes, this will be where the text begins. For \*(C`ENVIRONMENT\*(C', \*(C`COMMAND\*(C', or \*(C`GROUP\*(C' nodes, this will be the position of the last character of the opening identifier.
getNodeEndingPosition Same as above, but for last character. For \*(C`GROUP\*(C', \*(C`ENVIRONMENT\*(C', or \*(C`COMMAND\*(C' nodes, this will be the first character of the closing identifier.
getNodeOuterStartingPosition Same as getNodeStartingPosition, but for \*(C`GROUP\*(C', \*(C`ENVIRONMENT\*(C', or \*(C`COMMAND\*(C' nodes, this returns the first character of the opening identifier.
getNodeOuterEndingPosition Same as getNodeEndingPosition, but for \*(C`GROUP\*(C', \*(C`ENVIRONMENT\*(C', or \*(C`COMMAND\*(C' nodes, this returns the last character of the closing identifier.
getNodeMathFlag This applies to any node type. It is 1 if the node sets, or is contained within, a math mode region. 0 otherwise. \*(C`TEXT\*(C' nodes which have this flag as 1 can be assumed to be the actual mathematics contained in the document.
getNodePlainTextFlag This applies only to \*(C`TEXT\*(C' nodes. It is 1 if 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 index \*(C`TEXT\*(C' nodes with this property, for information retrieval purposes.
getEnvironmentClass This applies only to \*(C`ENVIRONMENT\*(C' nodes. Returns what class of environment the node represents (the \*(C`X\*(C' in \*(C`\begin{X}\*(C' and \*(C`\end{X}\*(C').
getCommandName This applies only to \*(C`COMMAND\*(C' nodes. Returns the name of the command (the \*(C`X\*(C' in \*(C`\X{...}\*(C').
getChildTree This applies only to \*(C`COMMAND\*(C', \*(C`ENVIRONMENT\*(C', and \*(C`GROUP\*(C' nodes: it returns the \*(C`LaTeX::TOM::Tree\*(C' which is ``under'' the calling node.
getFirstChild This applies only to \*(C`COMMAND\*(C', \*(C`ENVIRONMENT\*(C', and \*(C`GROUP\*(C' nodes: 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 a \*(C`GROUP\*(C' node, until it either hits the end of the tree level, a \*(C`TEXT\*(C' node which doesn't match \*(C`/^\s*$/\*(C', or a \*(C`COMMAND\*(C' node. This is useful for finding all \*(C`GROUP\*(C'ed parameters after a \*(C`COMMAND\*(C' node (see comments for \*(C`GROUP\*(C' in the \*(C`COMPONENTS\*(C' / \*(C`LaTeX::TOM::Node\*(C' section). You can just have a while loop that calls this method until it gets \*(C`undef\*(C', and you'll know you've found all the parameters to a command. Note: this may be bad, but \*(C`TEXT\*(C' Nodes matching \*(C`/^\s*\[[0-9]+\]$/\*(C' (optional parameter groups) are treated as if they were 'blank'.
Due to the lack of tree-modification methods, currently this module is mostly useful for minor modifications to the parsed document, for instance, altering the text of \*(C`TEXT\*(C' 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 \s-1TODO\s0 list in the \s-1TOM\s0.pm source.
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 authors know of parser errors if you discover any.
Thanks to (in order of appearance) who have contributed valuable suggestions & patches:
Otakar Smrz Moritz Lenz James Bowlin Jesse S. Bangs
Written by Aaron Krowne <[email protected]>
Maintained by Steven Schubiger <[email protected]>
Please see http://br.endernet.org/~akrowne/elaine/latex_tom/ for this module's home on the \s-1WWW\s0.
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
See <http://www.perl.com/perl/misc/Artistic.html>