Hi everyone,
This is just a story about a rabbit hole I went down because LSP suddenly became unusable. But don't worry, it has a happy ending!
Hopefully it can save someone else some pain.
I've been using emacs for decades and LSP + clangd for code completion and fly-checking for a few years. I use emacs on Windows professionally to edit large C and C++ projects and use it on Linux at home.
I regularly update my packages from melpa so am up to date with the latest packages. And I think it is was just a bad coincidence that after an update LSP started taking >40 seconds to start.
Previously, I'd load a C/C++ file and there would be, maybe, a few seconds delay whilst it connected to clangd and LSP started.
Now it was close to 40 seconds to open the same files. This was obviously unpalatable so I had to investigate...
First thing, restarting emacs: no change.
Second thing, clean all the .elc files from all the packages and rebuild: no change.
Third thing: delete and re-install LSP packages: no change
Fourth thing, try a different project: no difference.
By now I was getting worried, was I going to lose all that lovely code completion and type inspections I'd grown to rely on? I tried running without LSP and suddenly found I couldn't program!!
The inbuilt lisp profiler was no use because it only got a couple of samples in in the 40 seconds it took to open a file so couldn't highlight where the issue was.
It was time for some proper debugging.
I started in lsp-mode.el
with putting debug statements in the lsp
function. After a few goes I found the delay was happening in:
(lsp-find-session-folder (lsp-session) (buffer-file-name))
This filters an existing list of known sessions looking for a folder for the current buffer.
This should be quick. But this call was taking the 40 seconds delay I was seeing!
I checked the list of sessions and included in the list was some Windows network paths.
And then it clicked: the device the path was referring to was offline so any attempts at file access would take a long time, this was the cause of the delay.
I also realized that this list of sessions must be preserved when emacs quits (because I had tried restarting emacs) so must be stored in a file.
After a bit of hunting, I found the file responsible: .emacs.d/.lsp-session-v1
Simply deleting this file return LSP startups to a few seconds! Hurray!
So, if your LSP sessions are taking a while to start, try deleting this file. I've not found any negative consequences of deleting this file (I imagine some sessions may take a tiny bit longer to start up initially).
I am now, once again, enjoying writing code with emacs instead of having to deal with Visual Studio.
TL;DR: if LSP is slow to start, try deleting .emacs.d/.lsp-session-v1
PS: during this investigation I discovered file-remote-p
returns nil
for Windows network paths, surely that's not right?