4

I have configured lsp-mode as follows:

(use-package lsp-mode
  :straight t
  :init (setq lsp-keymap-prefix "C-c l")
  :hook ((python-mode . lsp))
  :commands lsp)

I am also using desktop-save-mode to restore my editing state upon restart. When I have several projects open and quit Emacs, the restart takes a long time as it starts each lsp server. Is there a way to start each server only when I run an lsp-related command in the buffer?

2 Answers2

3

How about:

(use-package lsp-mode
  :straight t
  :init (setq lsp-keymap-prefix "C-c l")
  :hook (python-mode . lsp-deferred))

The doc for lsp-deferred:

Signature
(lsp-deferred)

Documentation
Entry point that defers server startup until buffer is visible.

lsp-deferred will wait until the buffer is visible before invoking lsp.
This avoids overloading the server with many files when starting Emacs.

Edit: I've encountered some issues with this as described by scry, if the above doesn't work, try his workaround (I've opened a PR here: https://github.com/emacs-lsp/lsp-mode/pull/3975).

C4ffeine Add1ct
  • 460
  • 3
  • 8
3

The accepted answer didn't work for me, since when lsp-mode is already listed as a minor mode in the saved buffers, desktop-read will activate it before lsp-deferred runs.

Instead, I'm using this:

(defun my-lsp-deferred-on (_)
  (lsp-deferred))
(setq desktop-minor-mode-table
   '((lsp-mode my-lsp-deferred) 
     ...))

desktop-minor-mode-table tells Desktop how to restore the minor mode:

Table mapping minor mode variables to minor mode functions.
Each entry has the form (NAME RESTORE-FUNCTION).
NAME is the name of the buffer-local variable indicating that the minor
mode is active.  RESTORE-FUNCTION is the function to activate the minor mode.

Note that the function is called with one argument like a minor-mode function, but lsp-deferred takes none, hence the placeholder; also, it has to be mapped by its name, so we can't just use a lambda.

scry
  • 133
  • 4
  • 1
    I've encountered similar issues, I opened a PR a while ago: https://github.com/emacs-lsp/lsp-mode/pull/3975, the approach I think is similar to your snippet. I'll edit my answer. – C4ffeine Add1ct May 13 '23 at 11:08