Force Emacs to use a particular encoding if and only if that causes no trouble
In my .emacs file, I use the line
'(setq coding-system-for-write 'iso-8859-1-unix)
to have Emacs save files in the iso-8859-1-unix encoding. When I enter characters that cannot be encoded that way ("Łódź" for example), I get prompted to select a different encoding, but upon entering `iso-8859-1-unix' into the minibuffer, the file is saved and the offending characters are lost.
If I just hit enter at the prompt, the file is saved in Unicode, and when I close and reopen Emacs it is interpreted as a Unicode file again. If I then remove the offending characters, save the file and close and reopen Emacs another time, it is still interpreted as a Unicode file -- from which I deduce that it has still been saved in Unicode, even though saving in iso-8859-1-unix would have been possible.
So is there a way to force Emacs to write a file in iso-8859-1 whenever p开发者_开发问答ossible, and never save it in that encoding if doing so would gobble characters?
Many thanks in advance,
Thure Dührsen
As per the doc string for coding-system-for-write
, you should not be setting it globally.
Perhaps what you are looking for is (prefer-coding-system 'iso-8859-1-unix)
?
I'd try to write a save time hook function which would check the content of the buffer and set the encoding correspondingly. By using find-coding-system-region there shouldn't be much work.
Try
(setq-default buffer-file-coding-system 'iso-8859-1)
Edit:
Incorporating AProgrammer's suggestion, we get
(defun enforce-coding-system-priority ()
(let ((pref (car (coding-system-priority-list)))
(list (find-coding-systems-region (point-min) (point-max))))
(when (or (memq 'undecided list) (memq pref list))
(setq buffer-file-coding-system pref))))
(add-hook 'before-save-hook 'enforce-coding-system-priority)
(prefer-coding-system 'iso-8859-1)
The following should make Emacs ask when the buffer encoding is not that with which emacs is set up to save the file. Emacs will then prompt you to chose one among "safe" encodings.
(setq select-safe-coding-system-accept-default-p
'(lambda (coding)
(string=
(coding-system-base coding)
(coding-system-base buffer-file-coding-system))))
精彩评论