phfaist / pylatexenc

Simple LaTeX parser providing latex-to-unicode and unicode-to-latex conversion
https://pylatexenc.readthedocs.io
MIT License
301 stars 37 forks source link

Best way to to go into LatexGroupNodes? #108

Closed flimofly closed 2 months ago

flimofly commented 3 months ago

Congratulations on thank you for this magnificent tool!

I was wondering whether a recursive function is needed to parse LatexGroupNodes?

E.g.

def traverse(node):
    #Parsing for enumerate environments
        if node.isNodeType(LatexEnvironmentNode) and node.environmentname == "enumerate":

[omitted]

#check for enumeration nested within LatexGroupNodes
        if node.isNodeType(LatexGroupNode): #Recurse into groupnodes
            traverse(node)

#loop through nodes 
for node in nodes:
    traverse(node)

If so, what's the best approach to avoid infinite recursion?

phfaist commented 2 months ago

In the v3 alpha prerelease, there's a LatexNodesVisitor class that implements the visitor design pattern and can help you out to interate through group nodes. Essentially, you should create a subclass of LatexNodesVisitor and reimplement the methods you're interested in, such as visit_group_node(), visit_macro_node(), etc. To start the visitor you run visitor.start(node).

See https://pylatexenc.readthedocs.io/en/latest/latexnodes.nodes/#pylatexenc.latexnodes.nodes.LatexNodesVisitor (the doc isn't complete yet, sorry) and https://github.com/phfaist/pylatexenc/blob/main/pylatexenc/latexnodes/nodes.py#L1259 .