;;; devdocs-latex-preview.el --- LaTeX preview for devdocs  -*- lexical-binding: t; -*-

;; Copyright (C) 2024  Karthik Chikmagalur

;; Author: Karthik Chikmagalur <karthikchikmagalur@gmail.com>
;; Keywords: tex

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; 

;;; Code:

(require 'org-latex-preview)
(require 'devdocs)

(setf (alist-get 'devdocs-mode org-latex-preview-interfaces)
      `(:preamble ,#'devdocs-latex-preview--make-preamble
        :section  ,#'devdocs-latex-preview--section-bounds
        :context  ,#'devdocs-latex-preview-context
        :type     ,#'devdocs-latex-preview-type
        :property ,#'devdocs-latex-preview-property))

(defun devdocs-latex-preview--section-bounds ()
  (list (point-min) (point-max)))

(defun devdocs-latex-preview--make-preamble ()
  (with-temp-buffer (org-latex-preview--get-preamble)))

(defun devdocs-latex-preview-type (elem)
  (plist-get elem :type))

(defun devdocs-latex-preview-property (prop elem)
  (plist-get elem prop))

(defun devdocs-latex-preview-context ()
  (save-excursion
    (let (type begin end value)
      (when (eq (char-before) ?\\)
        (forward-char))
      (when (eq (char-after) ?\\)
        (forward-char 2))
      (cond
       ((looking-back "\\\\\\[")
        (setq type 'latex-environment
              begin (- (point) 2))
        (when (search-forward "\\]" nil t)
          (setq end (point))))
       ((looking-back "\\\\(")
        (setq type 'latex-fragment
              begin (- (point) 2))
        (when (search-forward "\\)" nil t)
          (setq end (point)))))
      (when (and begin end)
        (list :type  type :begin begin :end   end
              :value (buffer-substring-no-properties begin end))))))

(provide 'devdocs-latex-preview)
;;; devdocs-latex-preview.el ends here