This is the documentation for the unsupported version 1.5. Please consider upgrading your code to the latest stable version

Abstract Syntax Tree

This library uses a doubly-linked list Abstract Syntax Tree (AST) to represent the parsed block and inline elements. All such elements extend from the Node class.

Document

The root node of the AST will always be a Document object. You can obtain this node a few different ways:

Traversal

The following methods can be used to traverse the AST:

Iteration / Walking the Tree

If you’d like to iterate through all the nodes, use the walker() method to obtain an instance of NodeWalker. This will walk through the entire tree, emitting NodeWalkerEvents along the way.

use League\CommonMark\Node\NodeWalker;

/** @var NodeWalker $walker */
$walker = $document->walker();
while ($event = $walker->next()) {
    echo 'I am ' . ($event->isEntering() ? 'entering' : 'leaving') . ' a ' . get_class($event->getNode()) . ' node' . "\n";
}

This walker doesn’t use recursion, so you won’t blow the stack when working with deeply-nested nodes.

Modification

The following methods can be used to modify the AST:

DocumentParsedEvent

The best way to access and manipulate the AST is by adding an event listener for the DocumentParsedEvent.


Edit this page