;;; jao-buffers.el --- utilities to deal with buffers and windows  -*- lexical-binding: t; -*-

;; Copyright (C) 2026  Jose Antonio Ortega Ruiz

;; Author: Jose Antonio Ortega Ruiz <mail@jao.io>
;; Keywords: files

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

;;;; attached buffers
(defun jao-display-buffer-below-selected (buffer alist)
  (delete-other-windows-vertically)
  (display-buffer-below-selected buffer alist))

(defun jao-display-below-eldoc (buffer alist)
  (let ((w (selected-window)))
    (pop-to-buffer "*eldoc*" nil t)
    (jao-display-buffer-below-selected buffer alist)
    (select-window w t)))

(defun jao-attached-buffer-entry (name-rx height)
  `(,name-rx (display-buffer-reuse-window
              jao-display-buffer-below-selected)
             (window-height . ,(or height 25))))

;;;###autoload
(defmacro jao-with-attached-buffer (name-rx height &rest body)
  (declare (indent defun))
  `(let ((display-buffer-alist '(,(jao-attached-buffer-entry name-rx height))))
     ,@body))

;;;###autoload
(defun jao-define-attached-buffer (name-rx &optional height)
  (add-to-list 'display-buffer-alist
               (jao-attached-buffer-entry name-rx height)))

;;;###autoload
(defun jao-buffer-same-mode (&optional mode pre-fn switch-fn)
  (interactive)
  (let* ((mode (or mode major-mode))
         (modes (if (symbolp mode) (list mode) mode))
         (pred `(lambda (b)
                  (let ((b (get-buffer (if (consp b) (car b) b))))
                    (member (buffer-local-value 'major-mode b)
                            ',modes))))
         (buff (read-buffer "Buffer: " nil t pred)))
    (when pre-fn (funcall pre-fn))
    (if switch-fn (funcall switch-fn buff) (switch-to-buffer buff))))

;;;###autoload
(defun jao-buffer-same-mode-cmd (&optional pop)
  (interactive "P")
  (jao-buffer-same-mode nil nil (and pop #'pop-to-buffer)))

(provide 'jao-buffers)
;;; jao-buffers.el ends here
