;;; -*- lexical-binding: t -*-

(require 'syd/base)
(require 'syd/popups)
(require 'syd/handle)

(use-package lsp-mode
  :init
  ;; We'll bind things ourselves.
  (setq lsp-keymap-prefix nil)
  ;; Keep state out of my config dir.
  (setq lsp-session-file (file-name-concat syd-data-dir "lsp-session")
        ;; We disable `lsp-install-server', but I don't want this to be nil.
        lsp-server-install-dir (file-name-concat syd-data-dir "lsp"))
  ;; Disable features that have great potential to be slow.  LSPs tend to be
  ;; quite slow compared to non-LSP equivalents.
  (setq lsp-enable-folding nil
        lsp-enable-text-document-color nil)
  ;; Reduce unexpected modifications to code
  (setq lsp-enable-on-type-formatting nil)
  ;; Make breadcrumbs opt-in; they're redundant with the modeline and imenu
  (setq lsp-headerline-breadcrumb-enable nil)
  :hook (lsp-mode . lsp-enable-which-key-integration)
  :commands lsp
  :general (:keymaps 'syd-leader-code-map
                     "a" #'lsp-execute-code-action
                     "r" #'lsp-rename)
  :custom (; Fixes type error when using rename.
           (lsp-rename-use-prepare nil))
  :config
  (syd-defadvice syd-lsp-install-server-a ()
    "Override and disbale `lsp-install-server'"
    :override #'lsp-install-server
    (user-error (concat "Ignoring a call to `lsp-install-server'"
                        " — tell the caller to use Nix!")))
  (syd-push
   shackle-rules
   `(("*lsp-help*" "*lsp-install*")
     :select nil :size 0.42 :popup t :align bottom))
  (defun syd-lsp-handle-docs ()
    (interactive)
    (save-excursion
      (when evil-mode (forward-char)) ; evil-mode cope
      (lsp-describe-thing-at-point))
    (with-current-buffer (get-buffer "*lsp-help*")
      (and (not (string-empty-p (string-trim (buffer-string))))
           (current-buffer))))
  (syd-handle 'lsp-mode
    :docs #'syd-lsp-handle-docs))

(provide 'syd/lsp)
