Files
pivot-table/pivot-table.el
2025-05-12 18:01:59 -04:00

71 lines
2.2 KiB
EmacsLisp

;;; pivot-table.el --- Build org-mode pivot tables
;; Copyright (C) 2025 Jonathan Lamothe
;; Author: Jonathan Lamothe <jonathan@jlamothe.net>
;; Package-Version: 0.0
;; This file is not part of GNU Emacs.
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Affero 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
;; Affero General Public License for more details.
;; You should have received a copy of the GNU Affero General Public
;; License along with this program. If not, see
;; <https://www.gnu.org/licenses/>.
;;; Code:
(defun pt-build (source &rest params)
"Build a pivot table
TODO: more documentation"
(let* ((rows (plist-get params :rows))
(cols (plist-get params :cols))
(vals (plist-get params :vals))
(col-index (pt-get-columns source))
src-cols
(src-body (pt-get-body source))
(buckets (make-hash-table)))
(pt--index-columns rows)
(pt--index-columns cols)
(pt--index-columns vals car)
(sort src-cols #'<)
(dolist (record src-body)
(pt--process-record record source-cols buckets))))
(defun pt-get-columns (table)
"Extract the column names from a table"
(let (result)
(dolist (row table)
(when (and (listp row) (equal (car row) "!"))
(let ((n 2))
(dolist (cell (cdr row))
(unless (equal cell "")
(push (cons (format "%s" cell) n) result))
(setq n (1+ n))))))
result))
(defun pt-get-body (source)
"Discards all rows from a table before the first hline (if present)
If there is no hline, the table is instead returned unaltered."
(catch :return
(let ((remain source))
(while remain
(when (eq (car remain) 'hline)
(throw :return (cdr remain)))
(pop remain))
source)))
;; Local Variables:
;; read-symbol-shorthands: (("pt-" . "pivot-table-"))
;; End:
;;; pivot-table.el ends here