On Wed, Jun 18, 2025 at 8:24 PM Stefan Monnier <monnier@iro.umontreal.ca> wrote:
> 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


Yes, I believe your solution is also how eglot works, it's probably best to batch changes before assembling a bigger JSON document for notifying the LSP server at regular intervals.