;;; -*- lexical-binding: t; -*-
;;; guix-emacs.el --- Emacs packages installed with Guix

;; Copyright © 2014, 2015, 2016, 2017 Alex Kost <alezost@gmail.com>
;; Copyright © 2017 Kyle Meyer <kyle@kyleam.com>
;; Copyright © 2019, 2023 Maxim Cournoyer <maxim.cournoyer@gmail.com>

;; This file is part of GNU Guix.

;; GNU Guix 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.

;; GNU Guix 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 <http://www.gnu.org/licenses/>.

;;; Commentary:

;; This file provides auxiliary code to autoload Emacs packages installed with
;; Guix.  To produce verbose messages useful while debugging, set the
;; GUIX-EMACS-VERBOSE variable to true.

;;; Code:
(require 'seq)
(declare-function package-load-descriptor "package" (pkg-dir))

(defvar guix-emacs-autoloads-regexp
  (rx (* any) "-autoloads.el" (zero-or-one "c") string-end)
  "Regexp to match files containing autoload definitions.

Historically, this used to be the package name followed by \"-autoloads.el\".
As of Emacs 29, the term \"loaddefs\" is preferred over \"autoloads\",
but they function much in the same manner.")

(defun guix-emacs-find-autoloads (directory)
  "Return a list of files containing autoload definitions in DIRECTORY.
The files in the list do not have extensions (.el, .elc)."
  ;; `directory-files' doesn't honor group in regexp.
  (delete-dups (mapcar #'file-name-sans-extension
                       (directory-files directory 'full-name
                                        guix-emacs-autoloads-regexp))))

(defcustom guix-emacs-verbose nil
  "Set to true to provide verbose messages, such as when loading packages."
  :type 'boolean
  :group 'guix-emacs)

(defun guix-emacs--load-file-no-error (file)
  "Load FILE, ignoring any errors"
  (load file 'noerror (not guix-emacs-verbose)))

(defun guix-emacs--non-core-load-path ()
  ;; Filter out core Elisp directories, which are already handled by Emacs.
  (seq-filter (lambda (dir)
                (string-match-p "/share/emacs/site-lisp" dir))
              load-path))

(defun guix-emacs--subdirs-files ()
  "Return the Guix subdirs.el files found on the (non-core) load path."
  (seq-filter #'file-exists-p
              (mapcar (lambda (dir)
                        (expand-file-name "subdirs.el" dir))
                      (guix-emacs--non-core-load-path))))

;;;###autoload
(defun guix-emacs-autoload-packages (&optional no-reload)
  "Load autoload definitions for packages in `load-path'.

Autoload definitions are contained within files matching
`guix-emacs-autoload-regexp'; load each file matching that regexp.
When NO-RELOAD is nil (the default), also evaluate any subdirs.el files
found in `load-path' to discover newly installed packages."
  (interactive "P")
  ;; Reload the subdirs.el files such as the one generated by the Guix profile
  ;; hook, so that newly installed Emacs packages located under
  ;; sub-directories are put on the load-path without having to restart Emacs.
  (unless no-reload
    (mapc #'guix-emacs--load-file-no-error (guix-emacs--subdirs-files))
    (setq load-path (delete-dups load-path)))

  (let ((autoloads (mapcan #'guix-emacs-find-autoloads
                           (guix-emacs--non-core-load-path))))
    (mapc #'guix-emacs--load-file-no-error autoloads)))

;;;###autoload
(defun guix-emacs-load-package-descriptors ()
  "Load descriptors for packages found in EMACSLOADPATH via subdirs.el."
  (dolist (subdirs-file (guix-emacs--subdirs-files))
    (with-temp-buffer
      (insert-file-contents subdirs-file)
      (goto-char (point-min))
      (let ((subdirs (read (current-buffer))))
        (and (equal (car-safe subdirs) 'normal-top-level-add-to-load-path)
             (equal (car-safe (cadr subdirs)) 'list)
             (dolist (subdir (cdadr subdirs))
               (let ((pkg-dir (expand-file-name
                               subdir (file-name-directory subdirs-file))))
                 (when (file-directory-p pkg-dir)
                   (package-load-descriptor pkg-dir)))))))))

;; If emacs built with tree-sitter, read the value of the environment variable
;; to make tree-sitter grammars available in emacs out-of-the-box.
(with-eval-after-load 'treesit
  (when-let ((grammar-path (getenv "TREE_SITTER_GRAMMAR_PATH")))
    (mapcar (lambda (x) (add-to-list 'treesit-extra-load-path x))
            (split-string grammar-path ":"))))

(provide 'guix-emacs)

;;; guix-emacs.el ends here
