How can I open a file with a BOM Byte Order Mark and ensure that BOM is gone when I save the file.
Check out the file encoding with C-h C RET. If there is a byte order mark in the file, you may see something like this in the
Coding system for saving this buffer: U -- utf-8-with-signature-unix
-unix, it might say
-mac, and possibly it might start with some variant of
utf-16 instead of
If you don't want the byte order mark, just switch to the corresponding encoding without the
-with-signature part. Use C-x C-m f (
set-buffer-file-coding-system) to achieve this.
(Disclaimer: I don't know for how long the
-with-signature UTF encodings have been part of emacs. If you run an old emacs, this may not work for you.)
A comment by SabreWolfy really should be provided as an answer: As explained in a blog post by Bojan Nikolic, the BOM (which really is the Unicode character U+FEFF ZERO WIDTH NON-BREAKING SPACE placed at the beginning of a file) is sometimes used to indicate the file encoding (and byte order, in the case of UTF-16). When emacs opens a file with a BOM, it will not show it as part of the buffer, so you can't get rid of it.
The remedy is to visit the file with
M-x find-file-literally. If the encoding was UTF-8, the BOM will show up at the beginning of the file as three binary characters:
\357\273\277 (they may look like twelve characters, but there really are only three). Delete those three characters, then save the file.