Subject: Re: bug#66825: last-coding-system-used in basic-save-buffer

From: Eli Zaretskii <[email-masked]>
Date: Sun, 29 Oct 2023 21:27:19 +0200

> From: Juri Linkov <[email-masked]>
> Date: Sun, 29 Oct 2023 20:40:32 +0200
> 
> Indeed, the problem is in basic-save-buffer on the following line:
> 
>     (setq buffer-file-coding-system last-coding-system-used)
> 
> It's hard to guess why this code relies on the value that
> can be changed by other functions during saving the buffer.

Because this is the protocol: functions that determine the encoding of
buffer text dynamically set this variable, so it could later be used
to reflect the detection in buffer-file-coding-system.

> For example,
> 
>   (progn
>     (setq last-coding-system-used 'prefer-utf-8-unix)
>     (project-name (project-current))
>     (message "%S" last-coding-system-used))
> 
> prints "raw-text-unix" because it enables 'flyspell-mode'
> that calls:
> 
>   (defun ispell-buffer-local-parsing ()
>     (ispell-send-string "!\n")
> 
> where 'process-send-string' changes 'last-coding-system-used'
> to "raw-text-unix" in:
> 
>   send_process (Lisp_Object proc, const char *buf, ptrdiff_t len,
>                 Lisp_Object object)
>   {
>     ...
>     Vlast_coding_system_used = CODING_ID_NAME (coding->id);
> 
> A possible workaround would be to protect the value of
> last-coding-system-used in 'project-mode-line-format':

That's not a workaround, that's what we should do in such cases.
Alternatively, the "important" setting of last-coding-system-used
should be done later, after the inner functions already returned.

> However, I noticed that occasionally this bug occurs even
> when this function is not used.  So the proper fix needed
> in 'basic-save-buffer', but I don't know if it's intended
> that some function should change 'last-coding-system-used'
> during saving the buffer.

Yes, it's intended: saving the buffer can change
buffer-file-coding-system if it detects characters which cannot be
encoded by the original buffer-file-coding-system.