AutoFormat.java, Mk III

This is a finished copy of what was #2560.
Fix #2540, fix #1041.