def annotate_pages(pages):
    """A generator to annotate pages with nesting information.

    This is required to build a nested list of pages from the flat mptree list of pages.

    Returns:
        tuple(page, nb_open, nb_close, is_leaf):
            - page: the current page to wrap in a <li> tag,
            - nb_open(int): number of opening <ul> tags. Should be 1 when the nesting level
                increases, 0 otherwise,
            - nb_close(int): number of closing </ul> tags. Should be the gap between one page
                and the next when less nested. When reaching the last page we should close all
                the tags still open.
            - is_leaf(boolean): True if the current <li> tag is a leaf, False otherwise. If
                the page is not empty, it has children and we should delay closing the <li>.
    """
    nb_open = nb_close = 0
    nb_pages = len(pages)
    for i in range(nb_pages):
        if i == 0:
            nb_open = 0
        else:
            nb_open = max(pages[i].level - pages[i - 1].level, 0)
        is_leaf = True
        if i == nb_pages - 1:
            nb_close = pages[i].level - 1
        else:
            gap = pages[i].level - pages[i + 1].level
            nb_close = max(gap, 0)
            is_leaf = gap >= 0
        yield pages[i], nb_open, nb_close, is_leaf
