I attach a patch for consideration, along the lines I previously proposed. It seems to work: at least, it deletes a single trailing extra newline, while still leaving a newline at the end of the buffer, and doesn't delete a single newline at the end of the buffer.