import uuid


def protect_from_wrap(text, groups, restore_info=None):
    """
    Protect each match in groups that appears in text from wrapping by
    replacing it with a UUID in hex format (which won't be wrapped).

    Parameters
    ----------

    text : str
        The text in which groups (like markdown links or latex) are to be
        protected from wrapping.

    groups : list of ``re.Match`` objects
        Matches from a regex search for whatever it is that needs to be
        protected.

    restore_info : dict, optional
        Dictionary of protected items. UUIDs are the keys and the string they
        represent are the values. Allows ``protect_from_wrap`` to be called
        multiple times with different `groups`, building up the dictionary
        needed to undo the protection.
    """
    wrapped_text = text
    if restore_info is None:
        restore_info = {}

    # Reverse the groups so that the start positions in the string stays the
    # same as the text is processed.
    for group in groups[::-1]:
        link_id = uuid.uuid4().hex
        restore_info[link_id] = text[group.start(): group.end()]
        wrapped_text = (wrapped_text[:group.start()] + str(link_id) +
                        wrapped_text[group.end():])

    return wrapped_text, restore_info