1 ;;; ob-calc.el --- Babel Functions for Calc -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2010-2018 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;; Org-Babel support for evaluating calc code
34 (declare-function calc-store-into
"calc-store" (&optional var
))
35 (declare-function calc-recall
"calc-store" (&optional var
))
36 (declare-function math-evaluate-expr
"calc-ext" (x))
37 (declare-function org-trim
"org" (s &optional keep-lead
))
39 (defvar org-babel-default-header-args
:calc nil
40 "Default arguments for evaluating a calc source block.")
42 (defun org-babel-expand-body:calc
(body _params
)
43 "Expand BODY according to PARAMS, return the expanded body." body
)
45 (defvar org--var-syms
) ; Dynamically scoped from org-babel-execute:calc
47 (defun org-babel-execute:calc
(body params
)
48 "Execute a block of calc code with Babel."
49 (unless (get-buffer "*Calculator*")
50 (save-window-excursion (calc) (calc-quit)))
51 (let* ((vars (org-babel--get-vars params
))
52 (org--var-syms (mapcar #'car vars
))
53 (var-names (mapcar #'symbol-name org--var-syms
)))
56 (calc-push-list (list (cdr pair
)))
57 (calc-store-into (car pair
)))
61 (when (> (length line
) 0)
63 ;; simple variable name
64 ((member line var-names
) (calc-recall (intern line
)))
66 ((string= "'" (substring line
0 1))
67 (funcall (lookup-key calc-mode-map
(substring line
1)) nil
))
71 (list (let ((res (calc-eval line
)))
74 ((math-read-number res
) (math-read-number res
))
75 ((listp res
) (error "Calc error \"%s\" on input \"%s\""
77 (t (replace-regexp-in-string
81 ;; resolve user variables, calc built in
82 ;; variables are handled automatically
84 (mapcar #'org-babel-calc-maybe-resolve-var
85 ;; parse line into calc objects
86 (car (math-read-exprs line
)))))))))
89 (split-string (org-babel-expand-body:calc body params
) "[\n\r]"))))
91 (with-current-buffer (get-buffer "*Calculator*")
93 (calc-eval (calc-top 1))
96 (defun org-babel-calc-maybe-resolve-var (el)
98 (if (and (eq 'var
(car el
)) (member (cadr el
) org--var-syms
))
100 (calc-recall (cadr el
))
103 (mapcar #'org-babel-calc-maybe-resolve-var el
))
110 ;;; ob-calc.el ends here