WP_HTML_Processor::seek( string $bookmark_name ): bool

Moves the internal cursor in the HTML Processor to a given bookmark’s location.

Description

In order to prevent accidental infinite loops, there’s a maximum limit on the number of times seek() can be called.

Parameters

$bookmark_namestringrequired
Jump to the place in the document identified by this bookmark name.

Return

bool Whether the internal cursor was successfully moved to the bookmark’s location.

Source

public function seek( $bookmark_name ) {
	$actual_bookmark_name = "_{$bookmark_name}";
	$processor_started_at = $this->state->current_token
		? $this->bookmarks[ $this->state->current_token->bookmark_name ]->start
		: 0;
	$bookmark_starts_at   = $this->bookmarks[ $actual_bookmark_name ]->start;
	$direction            = $bookmark_starts_at > $processor_started_at ? 'forward' : 'backward';

	switch ( $direction ) {
		case 'forward':
			// When moving forwards, re-parse the document until reaching the same location as the original bookmark.
			while ( $this->step() ) {
				if ( $bookmark_starts_at === $this->bookmarks[ $this->state->current_token->bookmark_name ]->start ) {
					return true;
				}
			}

			return false;

		case 'backward':
			/*
			 * When moving backwards, clear out all existing stack entries which appear after the destination
			 * bookmark. These could be stored for later retrieval, but doing so would require additional
			 * memory overhead and also demand that references and bookmarks are updated as the document
			 * changes. In time this could be a valuable optimization, but it's okay to give up that
			 * optimization in exchange for more CPU time to recompute the stack, to re-parse the
			 * document that may have already been parsed once.
			 */
			foreach ( $this->state->stack_of_open_elements->walk_up() as $item ) {
				if ( $bookmark_starts_at >= $this->bookmarks[ $item->bookmark_name ]->start ) {
					break;
				}

				$this->state->stack_of_open_elements->remove_node( $item );
			}

			foreach ( $this->state->active_formatting_elements->walk_up() as $item ) {
				if ( $bookmark_starts_at >= $this->bookmarks[ $item->bookmark_name ]->start ) {
					break;
				}

				$this->state->active_formatting_elements->remove_node( $item );
			}

			return parent::seek( $actual_bookmark_name );
	}
}

Changelog

VersionDescription
6.4.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.