;;; syd-tooling.el -*- lexical-binding: t; -*-

(defun syd-lsp-lookup-documentation ()
  (interactive)
  (when-let* ((buf (get-buffer "*lsp-help*")))
    (kill-buffer buf))
  (call-interactively #'lsp-describe-thing-at-point)
  (when-let* ((buf (get-buffer "*lsp-help*")))
    (when (get-buffer-window-list buf)
      ;; Bury the buffer so the popup system has full control over how it's
      ;; selected.
      (bury-buffer buf)
      buf)))

(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!")))
  (set-popup-rule! (rx line-start "*lsp-" (or "help" "install"))
    :size 13 :quit t :select nil)

  ;; DEPRECATED: Remove once syd-strategies is working.
  (syd-add-hook 'lsp-mode-hook
    (defun syd-lsp-set-handlers-h ()
      (setq-local syd-lookup-documentation-handlers
                  (list #'syd-lsp-lookup-documentation)))))

(use-package envrc
  ;; REVIEW: Can we load this any later/better?
  :hook (on-first-file . envrc-global-mode)
  :general
  (:prefix-map 'syd-leader-file-env-map
   "a" #'envrc-allow
   "r" #'envrc-reload)
  (:keymaps 'syd-leader-file-map
   "e" `("Environment" . ,syd-leader-file-env-map))
  :config
  (set-popup-rule! (rx "*envrc*")
    :quit t :ttl 0))

(provide 'syd-tooling)
