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

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


;;; Pairs

(with-eval-after-load 'evil-surround
  ;; In Elisp, `' is a much more common pair than ``.
  (syd-add-hook 'emacs-lisp-mode-hook
    (defun syd-elisp-evil-surround-pairs-h ()
      (push '(?` . ("`" . "'")) evil-surround-pairs-alist))))


;;; Ielm

;; Keep junk out of `user-emacs-directory'.
(setq ielm-history-file-name
      (file-name-concat syd-data-dir "ielm-history.eld"))


;;; Define handlers

(defun syd-elisp-open-repl ()
  (interactive)
  (pop-to-buffer
   (or (get-buffer "*ielm*")
       (progn (ielm) ; Creates the *ielm* buffer.
              (let ((b (get-buffer "*ielm*")))
                ;; We leave it to the enclosing `pop-to-buffer' to display the
                ;; buffer.
                (bury-buffer b)
                b)))))

(defun syd-elisp-handle-docs (identifier)
  "Lookup IDENTIFIER with `describe-symbol'"
  ;; HACK: Much to my frustration, `describe-symbol' has no defined return
  ;; value.  To test if the call was successful or not, we check if any window
  ;; is displaying the help buffer.  This breaks if
  ;; `syd-emacs-lisp-lookup-documentation' is called while the help buffer is
  ;; already open.
  (describe-symbol (intern identifier))
  (let ((buffer (get-buffer (help-buffer))))
    (and (get-buffer-window-list buffer)
         buffer)))

(defun syd-elisp-eval-region (beg end)
  (eval-region beg end t))

(defun syd-elisp-load-buffer ()
  (eval-buffer))

(syd-handle '(emacs-lisp-mode lisp-interaction-mode)
  :docs #'syd-elisp-handle-docs
  :repl #'syd-elisp-open-repl
  :eval-region #'syd-elisp-eval-region
  :load-buffer #'syd-elisp-load-buffer)

(syd-add-hook '(emacs-lisp-mode-hook lisp-interaction-mode-hook)
  #'syd-lisp-mode)



(provide 'syd/emacs-lisp)
