def make_page_bookmark_tree(page, skipped_levels, last_by_depth,
                            previous_level, page_number, matrix):
    """Make a tree of all bookmarks in a given page."""
    for level, label, (point_x, point_y), state in page.bookmarks:
        if level > previous_level:
            # Example: if the previous bookmark is a <h2>, the next
            # depth "should" be for <h3>. If now we get a <h6> we’re
            # skipping two levels: append 6 - 3 - 1 = 2
            skipped_levels.append(level - previous_level - 1)
        else:
            temp = level
            while temp < previous_level:
                temp += 1 + skipped_levels.pop()
            if temp > previous_level:
                # We remove too many "skips", add some back:
                skipped_levels.append(temp - previous_level - 1)

        previous_level = level
        depth = level - sum(skipped_levels)
        assert depth == len(skipped_levels)
        assert depth >= 1

        children = []
        point_x, point_y = matrix.transform_point(point_x, point_y)
        subtree = (label, (page_number, point_x, point_y), children, state)
        last_by_depth[depth - 1].append(subtree)
        del last_by_depth[depth:]
        last_by_depth.append(children)
    return previous_level
Make a tree of all bookmarks in a given page.
weasyprint/anchors.py