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

(require 'syd/base)
(require 'syd/org)
(require 'syd/leader)

(defun syd-org-latex-preview-recompile-preamble ()
  (interactive)
  (setq org-latex-preview-process-precompiled nil)
  (org-latex-preview-clear-cache)
  (org-latex-preview 'buffer))

(defun syd-org-latex-preview-buffer ()
  (interactive)
  (org-latex-preview 'buffer))

(defun syd-org-edit-quiver-diagram ()
  (interactive)
  (when-let* ((diagram-fragment (org-element-context))
	      (_ (org-inside-LaTeX-fragment-p diagram-fragment))
	      (diagram-beg (org-element-begin diagram-fragment))
	      (diagram-end (org-element-end diagram-fragment))
	      (url (save-excursion
		     (setq syd/buf (buffer-string))
		     (and (re-search-forward (rx "% " (group (* anychar)) eol)
					     diagram-end
					     t)
			  (match-string 1)))))
    (goto-char diagram-beg)
    (set-mark diagram-end)
    (browse-url url)
    t))

(use-package org
  :custom ((org-startup-with-latex-preview t)
           (org-latex-compile "xelatex"))
  :general (:keymaps 'org-mode-map
            :states '(normal visual motion emacs insert)
            :major-modes t
            :prefix syd-localleader-key
            :non-normal-prefix syd-alt-localleader-key
            "L L" #'syd-org-latex-preview-buffer
            "L r" #'syd-org-latex-preview-recompile-preamble
            "L c" #'org-latex-preview-clear-cache)
  :config
  (add-hook 'org-ctrl-c-ctrl-c-hook #'syd-org-edit-quiver-diagram))

(defun syd-str (sep &rest strs)
  (mapconcat #'identity strs sep))

(use-package org-latex-preview
  :defer t
  :straight nil
  :custom (;; Generate previews whilst editing.
           (org-latex-preview-live t)
           ;; Default behaviour waits one second before generating the live
           ;; preview.
           (org-latex-preview-live-debounce 0.25)
           ;; Increase size of previews.
           (org-latex-preview-appearance-options
            (plist-put org-latex-preview-appearance-options :zoom 1.0))
           (org-latex-preview-process-precompile
            ;; Not suported by XeLaTeX or LuaLaTeX }:(.
            (eq org-latex-compiler "pdflatex")))
  :hook (org-mode . org-latex-preview-mode))

(use-package org-contrib)

(use-package ox-extra
  :after org-contrib
  :config
  (ox-extras-activate '(latex-header-blocks ignore-headlines)))

(provide 'syd/org/latex)
