Avoid calling saveReferences recursively

This makes it possible to have circular references in documents without
creating an infinite loop when saving.