;;; astro-ts-mode.el --- Major mode for editing Astro templates  -*- lexical-binding: t; -*-

;; Copyright (C) 2023-2024  Ruby Iris Juric

;; Author: Ruby Iris Juric <ruby@srxl.me>
;; Homepage: https://github.com/Sorixelle/astro-ts-mode
;; Package-Version: 3.0.2
;; Package-Revision: v3.0.2-0-g1d24c9d399de
;; Package-Requires: ((emacs "30"))
;; Keywords: languages

;; 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:

;; This package provides a major mode with syntax highlighting for Astro
;; templates. It leverages Emacs' built-in tree-sitter support, as well as
;; virchau13's tree-sitter grammar for Astro.
;;
;; More info:
;; README: https://github.com/Sorixelle/astro-ts-mode
;; tree-sitter-astro: https://github.com/virchau13/tree-sitter-astro
;; Astro: https://astro.build/

;;; Code:

(require 'treesit)
(require 'typescript-ts-mode)
(require 'css-mode)

(defgroup astro ()
  "Major mode for editing Astro templates."
  :group 'languages)

(defcustom astro-ts-mode-indent-offset 2
  "Number of spaces for each indentation step in `astro-ts-mode'."
  :type 'integer
  :group 'astro
  :package-version '(astro-ts-mode . "1.0.0"))

(defvar astro-ts-mode--indent-rules
  `((astro
     ((parent-is "document") column-0 0)
     ((node-is "frontmatter") column-0 0)
     ((node-is "/>") parent-bol 0)
     ((node-is ">") parent-bol 0)
     ((node-is "end_tag") parent-bol 0)
     ((parent-is "comment") prev-adaptive-prefix 0)
     ((parent-is "element") parent-bol astro-ts-mode-indent-offset)
     ((parent-is "script_element") parent-bol astro-ts-mode-indent-offset)
     ((parent-is "style_element") parent-bol astro-ts-mode-indent-offset)
     ((parent-is "start_tag") parent-bol astro-ts-mode-indent-offset)
     ((parent-is "self_closing_tag") parent-bol astro-ts-mode-indent-offset))
    (css . ,(append '(((parent-is "stylesheet") parent-bol 0))
                    (alist-get 'css css--treesit-indent-rules)))
    (tsx . ,(append '(((parent-is "program") parent-bol 0))
                    (alist-get 'tsx (typescript-ts-mode--indent-rules 'tsx)))))
  "Tree-sitter indentation rules for `astro-ts-mode'.")

(defun astro-ts-mode--prefix-font-lock-features (prefix settings)
  "Prefix with PREFIX the font lock features in SETTINGS."
  (mapcar (lambda (setting)
            (list (nth 0 setting)
                  (nth 1 setting)
                  (intern (format "%s-%s" prefix (nth 2 setting)))
                  (nth 3 setting)))
          settings))

(defvar astro-ts-mode--font-lock-settings
  (append
   (astro-ts-mode--prefix-font-lock-features
    "tsx"
    (typescript-ts-mode--font-lock-settings 'tsx))
   (astro-ts-mode--prefix-font-lock-features "css" css--treesit-settings)
   (treesit-font-lock-rules
    :language 'astro
    :feature 'astro-comment
    '((comment) @font-lock-comment-face
      (frontmatter ("---") @font-lock-comment-face))

    :language 'astro
    :feature 'astro-keyword
    '("doctype" @font-lock-keyword-face)

    :language 'astro
    :feature 'astro-definition
    '((tag_name) @font-lock-function-name-face)

    :language 'astro
    :feature 'astro-string
    '((quoted_attribute_value) @font-lock-string-face
      (attribute_name) @font-lock-constant-face)

    :language 'astro
    :feature 'astro-bracket
    '((["<" ">" "</" "/>" "{" "}"]) @font-lock-bracket-face)))
  "Tree-sitter font-lock settings for `astro-ts-mode'.")

(defvar astro-ts-mode--range-settings
  (treesit-range-rules
   :embed 'tsx
   :host 'astro
   :local t
   '((frontmatter (frontmatter_js_block) @cap)
     (attribute_interpolation (attribute_js_expr) @cap)
     (html_interpolation (permissible_text) @cap)
     (script_element (raw_text) @cap))

   :embed 'css
   :host 'astro
   :local t
   '((style_element (raw_text) @cap))))

(defun astro-ts-mode--treesit-language-at-point (point)
  "Return the language at POINT."
  (let* ((node (treesit-node-at point 'astro))
         (type (treesit-node-type node)))
    (cond
     ((string-equal type "raw_text")
      (let ((parent-type (treesit-node-type (treesit-node-parent node))))
        (cond
         ((string-equal parent-type "script_element") 'tsx)
         ((string-equal parent-type "style_element") 'css))))
     ((string-equal type "frontmatter_js_block") 'tsx)
     ((string-equal type "attribute_js_expr") 'tsx)
     ((string-equal type "permissible_text") 'tsx)
     (t 'astro))))

;;;###autoload
(define-derived-mode astro-ts-mode html-mode "Astro"
  "Major mode for editing Astro templates, powered by tree-sitter."
  :group 'astro

  (unless (treesit-ready-p 'astro)
    (error "Tree-sitter grammar for Astro isn't available"))

  (unless (treesit-ready-p 'css)
    (error "Tree-sitter grammar for CSS isn't available"))

  (unless (treesit-ready-p 'tsx)
    (error "Tree-sitter grammar for Typescript/TSX isn't available"))

  (treesit-parser-create 'astro)

  ;; Comments and text content
  (setq-local treesit-text-type-regexp
              (regexp-opt '("comment" "text")))

  ;; Indentation rules
  (setq-local treesit-simple-indent-rules astro-ts-mode--indent-rules
              css-indent-offset astro-ts-mode-indent-offset)

  ;; Font locking
  (setq-local treesit-font-lock-settings astro-ts-mode--font-lock-settings
              treesit-font-lock-feature-list
              '((astro-comment astro-keyword astro-definition css-selector
                               css-comment css-query css-keyword tsx-comment
                               tsx-declaration tsx-jsx)
                (astro-string css-property css-constant css-string tsx-keyword
                              tsx-string tsx-escape-sequence)
                (css-error css-variable css-function css-operator tsx-constant
                           tsx-expression tsx-identifier tsx-number tsx-pattern
                           tsx-property)
                (astro-bracket css-bracket tsx-function tsx-bracket
                               tsx-delimiter)))

  ;; Embedded languages
  (setq-local treesit-range-settings astro-ts-mode--range-settings
              treesit-language-at-point-function
              #'astro-ts-mode--treesit-language-at-point)

  (treesit-major-mode-setup))

;;;###autoload
(if (treesit-ready-p 'astro)
    (add-to-list 'auto-mode-alist '("\\.astro\\'" . astro-ts-mode)))

(provide 'astro-ts-mode)
;;; astro-ts-mode.el ends here
