I think this implementation has the same behavior, but maybe the style/efficiency could be improved. I'm using it because copy_term/4 isn't available on 8.0.2 (default Debian buster install).
copy_term(VarsIn, In, VarsOut, Out) :- term_variables(In, AllVarsIn), maplist(list_to_ord_set, [AllVarsIn, VarsIn], [AllVarsInOrdSet, VarsInOrdSet]), ord_subtract(AllVarsInOrdSet, VarsInOrdSet, PreservedVars), copy_term(PreservedVars-VarsIn-In, PreservedVars-VarsOut-Out).