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

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

;; A better PDF reader for Emacs.
(use-package pdf-tools
  ;; Managed by Nix: pdf-tools depends on a standalone compiled binary.
  :straight nil
  :mode ("\\.pdf\\'" . pdf-view-mode)
  :magic ("%PDF" . pdf-view-mode)
  :general (:keymaps 'pdf-view-mode-map
            :states 'motion
            "q" #'kill-current-buffer
            "d" #'pdf-view-scroll-up-or-next-page
            "u" #'pdf-view-scroll-down-or-previous-page)
  :custom ((pdf-view-display-size 'fit-page))
  :config
  ;; HACK: Fix "Symbol's function definition is void:
  ;; pdf-occur-global-minor-mode" errors on load.
  ;; https://github.com/politza/pdf-tools/issues/206#issuecomment-614885793
  (use-package pdf-occur
    :straight nil
    :commands (pdf-occur-global-minor-mode))
  (use-package pdf-history
    :straight nil
    :commands (pdf-history-minor-mode))
  (use-package pdf-links
    :straight nil
    :commands (pdf-links-minor-mode))
  (use-package pdf-outline
    :straight nil
    :commands (pdf-outline-minor-mode))
  (use-package pdf-annot
    :straight nil
    :commands (pdf-annot-minor-mode))
  (use-package pdf-sync
    :straight nil
    :commands (pdf-sync-minor-mode))
  ;; Despite its namesake, this does not call `pdf-tools-install', it only sets
  ;; up hooks, auto-mode-alist/magic-mode-alist entries, global modes, and
  ;; refreshes pdf-view-mode buffers, if any.
  ;;
  ;; I avoid calling `pdf-tools-install' directly because `pdf-tools' is easy to
  ;; prematurely load in the background (e.g. when exporting an org file or by
  ;; packages like org-pdftools), and I don't want pdf-tools to suddenly block
  ;; Emacs and spew out compiler output for a few minutes in those cases. It's
  ;; abysmal UX. The `pdf-view-mode' advice above works around this with a less
  ;; cryptic failure message, at least.
  (pdf-tools-install-noverify)
  (syd-add-hook 'pdf-view-mode-hook
    #'pdf-view-themed-minor-mode
    #'hide-mode-line-mode
    #'pdf-view-auto-slice-minor-mode
    (defun syd-pdf--init-ui-h ()
      ;; HACK: Flickering pdfs when evil-mode is enabled.
      (setq-local evil-normal-state-cursor (list nil))))
  (syd-push shackle-rules
    '(("^\\*Outline*" :side right :size 40 :select nil)
      ("^\\*Edit Annotation " :inhibit-window-quit t)
      ("\\(?:^\\*Contents\\|'s annots\\*$\\)" :ignore t)))
  ;; Silence "File *.pdf is large (X MiB), really open?" prompts for PDFs.
  (syd-defadvice syd-pdf--suppress-large-file-prompts-a
    (fn size op-type filename &optional offer-raw)
    :around #'abort-if-file-too-large
    (unless (string-match-p "\\.pdf\\'" filename)
      (funcall fn size op-type filename offer-raw))))

(use-package saveplace-pdf-view
  :after pdf-view)

(provide 'syd/pdf)
