Returns attach_attrs(key, value, fmt, meta) action that reads and
    attaches attributes to unattributed elements generated by the
    pandocfilters function f (e.g. pandocfilters.Math, etc).

    The extract_attrs() function should read the attributes and raise a
    ValueError or IndexError if attributes are not found.

def attach_attrs_factory(f, extract_attrs=extract_attrs, allow_space=False):
    """Returns attach_attrs(key, value, fmt, meta) action that reads and
    attaches attributes to unattributed elements generated by the
    pandocfilters function f (e.g. pandocfilters.Math, etc).

    The extract_attrs() function should read the attributes and raise a
    ValueError or IndexError if attributes are not found.
    """

    # Get the name
    name = f.__closure__[0].cell_contents

    def _attach_attrs(x):
        """Extracts and attaches the attributes."""
        for i, v in enumerate(x):
            if v and v['t'] == name:  # Find where the attributes start
                n = i+1
                if allow_space and n < len(x) and x[n]['t'] == 'Space':
                    n += 1
                try:  # Extract the attributes
                    attrs = extract_attrs(x, n)
                    x[i]['c'].insert(0, attrs)
                except (ValueError, IndexError):
                    pass

    def attach_attrs(key, value, fmt, meta):  # pylint: disable=unused-argument
        """Attaches attributes to an element."""
        if key in ['Para', 'Plain']:
            _attach_attrs(value)

            # Image: Add pandoc's figure marker if warranted
            if len(value) == 1 and value[0]['t'] == 'Image':
                value[0]['c'][-1][1] = 'fig:'

    return attach_attrs