Karl Johan Kleist:

Original code by Rune Kallhovd. I have just removed the unnecessary dollar signs in variable names and added single quotes round PREPEND at the very end.

function clean_unused_gfxents(doc,op) {

    local entArr[], gfxArr[];
    local entArrlen = 0;
    local gfxCnt = 1;

    if (op != 2) {
        return 0;
    }

# Building an Array of declared entities:
    entArrlen = graphic_entity_names(entArr, doc);

# Building an Array of used entities:
    for (o = oid_first(doc); oid_valid(o); o = oid_forward(o)) {
        # Do we have a Graphic tag?
        if (graphic_tag(oid_name(o))) {

            # Get the attribute name holding the ENTITY
            local gfxentnam = graphic_entity_attr_name(oid_name(o));

            if (gfxentnam != "") {
                gfxArr[gfxCnt] = oid_attr(o, gfxentnam);
                gfxCnt++;
            }
        }
    }

# Iterate over declared entities, and delete unused ones:
    for (i = 1; i <= entArrlen; i++) {
        local found = 0;
        ent = entArr[i];

        for (gfx in gfxArr) {
            if (gfxArr[gfx] == ent) {
                found = 1;
            }
        }

        if (!found) {
            # NOTE: dollar sign needed here / kjk
            undeclare_entity $ent;  

        }
    }
}

# Add the following to e.g. a init() function:

doc_add_callback(0, 'save', 'cor_utils::clean_unused_gfxents', 'PREPEND');

Download code code-acl0006.txt.