I am trying to configure Emacs to save UTF-8 files with a Byte Order Mark. (Yes, I know that the BOM is evil and unnecessary for UTF-8 files. However, Microsoft has decided they know better, so I want to make sure I'm able to save files with BOM.)

However, for some reason my choice of utf-8-with-signature for buffer-file-coding-system won't stick when I save the file.

I'm using Emacs 24.5.1 on Windows 10. To reproduce:

  1. emacs -Q
  2. Open a file (optionally one that already has a BOM).
  3. (setq buffer-file-coding-system 'utf-8-with-signature) (Or M-x set-buffer-file-coding-system RET utf-8-with-signature RET.)
  4. C-x C-s
  5. C-h v buffer-file-coding-system. It is now set to utf-8-dos. I also verified that the existing BOM was removed from the file.

Why is this happening, and how can I fix it?

1 Answer 1


Pityingly I can only give an answer to the second question "How can I fix this".

Let emacs guess the file encoding after finding the file via html-mode-hook and use it for saving the file via save-buffer-coding-system. You can do that with the following lisp snippet in your init file.

(defun TZA-html-set-coding-system ()
  "Retain the byte order marker of `html-mode' buffers."
  (setq save-buffer-coding-system buffer-file-coding-system))

(add-hook 'html-mode-hook #'TZA-html-set-coding-system)
  • This seems like a useful workaround. I no longer do much development on Windows, so it might be a while before I can get around to testing it. Commented Oct 20, 2017 at 22:56
  • Is there a way to apply this to all buffers instead of just those with a given mode? Commented Oct 20, 2017 at 22:57
  • 1
    @ScottWeldon You can use after-change-major-mode-hook instead of html-mode-hook. But I think this is not necessary. From what I read about the problem it is special to html-mode-hook. Note, that it is not limited to Windows.
    – Tobias
    Commented Oct 23, 2017 at 15:24
  • 1
    Okay, thanks. IIRC, I wasn't using html-mode when I ran into this problem; I think it was web-mode and/or csharp-mode. Commented Oct 23, 2017 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.