Subject: Re: bug#78777: 30.1; insert-file-contents should not set buffer-file-name to nil

From: Stefan Monnier <[email-masked]>
Date: Wed, 18 Jun 2025 15:24:42 -0400

> When investigating https://github.com/emacs-lsp/lsp-mode/issues/4782 and
> https://github.com/purcell/emacs-reformatter/issues/63, I've discovered
> the following bug in insert-file-contents.
[...]
> insert-file-contents should not set buffer-file-name to nil

I have not tracked lsp-mode's code closely enough to fully understand
what's going on, but IIUC from the above bug reports,
`lsp-diagnostics--request-pull-diagnostics` is executed (indirectly)
from `before/after-change-functions`.

While I can agree that binding `buffer-file-name` to nil within
`insert-file-contents` is a bug, I think lsp-mode would do well to
change its code so it does not run things like
`lsp-diagnostics--request-pull-diagnostics` directly from
`before/after-change-functions`, because those hooks are a bit like
POSIX signal handlers, i.e. you should do as little work in there as
possible.  IOW, lsp-mode should try to just record the change there and
move all the rest of the processing to some other place, such as
`post-command-hook` or a timer.

This would not only circumvent the current problem but also have further
benefits, typically for operations which run `after-change-functions`
many times, where lsp-mode could combine the corresponding LSP requests.

        Stefan