emacs-orgmode@gnu.org archives
 help / color / mirror / code / Atom feed
blob 2656f27fd1ed849eba459d9c899cda09248cdea4 8144 bytes (raw)
name: lisp/ob-calc.el 	 # note: path name is non-authoritative(*)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
 
;;; ob-calc.el --- Babel Functions for Calc

;; Copyright (C) 2010-2015 Free Software Foundation, Inc.

;; Author: Eric Schulte
;; Keywords: literate programming, reproducible research
;; Homepage: http://orgmode.org

;; This file is part of GNU Emacs.

;; GNU Emacs 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 Emacs 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 GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; Org-Babel and Org-Table support for evaluating calc code.
;; See `org-babel-calc-eval' for documentation.

;;; Code:
(require 'ob)
(require 'calc)
(unless (featurep 'xemacs)
  (require 'calc-trail)
  (require 'calc-store))

(declare-function calc-store-into    "calc-store" (&optional var))
(declare-function calc-recall        "calc-store" (&optional var))
(declare-function math-evaluate-expr "calc-ext"   (x))

(defvar org-babel-default-header-args:calc nil
  "Default arguments for evaluating an calc source block.")

(defun org-babel-expand-body:calc (body _params)
  "Expand BODY according to PARAMS, return the expanded body." body)

(defun org-babel-execute:calc (body params)
  "Execute a block of calc code with Babel."
  (org-babel-calc-eval (org-babel-expand-body:calc body params)
		       (org-babel--get-vars params)))

(defvar org--ob-calc-env-symbol nil) ; For org-babel-calc-eval
(defvar org--ob-calc-var-names nil)

(defun org-babel-calc-eval (text &optional environment env-symbol setup env-setup)
  "Evaluate TEXT as set of calc expressions (one per line) and return the top of the stack.

Optional argument ENVIRONMENT is a user-defined variables
environment which is an alist of (SYMBOL . VALUE).

Optional argument ENV-SYMBOL is a symbol of a user-defined
variables environment which is an alist of (SYMBOL . VALUE).

Setting your environment using either of ENVIRONMENT or
ENV-SYMBOL has the same effect. The difference is that this
function caches the value of ENV-SYMBOL internally between
succesive evaluations with ENV-SYMBOL arguments of equal symbol
names and reevaluates the value of ENV-SYMBOL only when the
symbol name of ENV-SYMBOL changes.

Additionally, setting ENV-SYMBOL to nil will forget any
internal environment before applying ENVIRONMENT, i.e. with
ENV-SYMBOL set to nil this function is pure.

You can also use `org-babel-calc-set-env',
`org-babel-calc-reset-env' and `org-babel-calc-store-env' to set,
reset and update the internal environment between evaluations.

Optional argument SETUP allows additional calc setup on every
evaluation.

Optional argument ENV-SETUP allows additional calc setup on every
ENV-SYMBOL change.

This function is useful if you want to evaluate complicated
formulas in a table, e.g. after evaluating

  (setq an-env '((foo . \"2 day\")
                 (bar . \"6 hr\")))

you can use this in the following table

  | Expr      | Result       |
  |-----------+--------------|
  | foo + bar | 2 day + 6 hr |
  | foo - bar | 2 day - 6 hr |
  |-----------+--------------|
  #+TBLFM: $2='(org-babel-calc-eval $1 an-env)

which would become slow to recompute with a lot of rows, but then
you can change the TBLFM line to

  #+TBLFM: $2='(org-babel-calc-eval $1 nil 'an-env)

and it would become fast again.

SETUP argument can be used like this:

  | Expr      | Result   |
  |-----------+----------|
  | foo + bar | 2.25 day |
  | foo - bar | 1.75 day |
  |-----------+----------|
  #+TBLFM: $2='(org-babel-calc-eval $1 nil 'an-env nil (lambda () (calc-units-simplify-mode t)))

In case that is not fast or complicated enough, you can combine
this with `org-babel-calc-store-env' to produce some clever stuff
like, e.g. computing environment on the fly (an-env variable is
not actually used here, it is being generated just in case you
want to use it elsewhere):

  (setq an-env nil)
  (defun compute-and-remember (name expr)
    (let* ((v (org-babel-calc-eval expr nil 'an-env nil (lambda () (calc-units-simplify-mode t))))
           (c `(,(intern name) . ,v)))
        (org-babel-calc-store-env (list c))
        (push c an-env)
        v))

and then

  | Name | Expr       | Value    |
  |------+------------+----------|
  | foo  | 2 day      | 2 day    |
  | bar  | foo + 6 hr | 2.25 day |
  |------+------------+----------|
  #+TBLFM: $3='(compute-and-remember $1 $2)

Note that you can set ENV-SYMBOL to 'nil to get ENV-SETUP
without.

The subsequent results might become somewhat surprising in case
ENVIRONMENT overrides variables set with ENV-SYMBOL."
  (org-babel-calc-init)
  (cond
    ((equal env-symbol nil) (org-babel-calc-reset-env))
    ((not (equal (symbol-name env-symbol) org--ob-calc-env-symbol))
	(org-babel-calc-set-env env-symbol)
	(unless (null env-setup)
	  (funcall env-setup))))
  (org-babel-calc-store-env environment)
  (unless (null setup)
    (funcall setup))
  (org-babel-calc-eval-string text))

(defun org-babel-calc-init ()
  "Initialize calc.

You probably don't want to call this function explicitly."
  (unless (get-buffer "*Calculator*")
    (save-window-excursion (calc) (calc-quit))))

(defun org-babel-calc-set-env (env-symbol)
  "Force update current environment with the value of ENV-SYMBOL.

See `org-babel-calc-eval' for more info."
  (org-babel-calc-reset-env)
  (org-babel-calc-store-env (eval env-symbol))
  (setq org--ob-calc-env-symbol (symbol-name env-symbol)))

(defun org-babel-calc-reset-env ()
  "Forget current environment and the value of the last
ENV-SYMBOL.

See `org-babel-calc-eval' for more info."
  (setq org--ob-calc-var-names nil
	org--ob-calc-env-symbol nil))

(defun org-babel-calc-store-env (vars)
  "Store an environment (alist of (SYMBOL . VALUE) pairs) into calc.

See `org-babel-calc-eval' for more info."
  (mapc
    (lambda (pair)
	(let ((name (symbol-name (car pair)))
	    (value (cdr pair)))
	;; Using symbol-name and then intern here may seem a little
	;; crazy, but without it calc may not recall some of variables
	;; that got non-canonical symbols, which will be very surprising
	;; for users that produce their environments with '(...) syntax.
	;; Better safe than sorry.
	  (calc-store-value (intern name) value "" 0)
	  (push name org--ob-calc-var-names)))
    vars))

(defun org-babel-calc-eval-string (text)
  (mapc #'org-babel-calc-eval-line (split-string text "[\n\r]"))
  (save-excursion
    (with-current-buffer (get-buffer "*Calculator*")
      (prog1
        (calc-eval (calc-top 1)
        (calc-pop 1))))))

(defun org-babel-calc-eval-line (line)
  (let ((line (org-babel-trim line)))
    (when (> (length line) 0)
	(cond
	 ;; simple variable name
	 ((member line org--ob-calc-var-names) (calc-recall (intern line)))
	 ;; stack operation
	 ((string= "'" (substring line 0 1))
	(funcall (lookup-key calc-mode-map (substring line 1)) nil))
	 ;; complex expression
	 (t (calc-push-list
	 (list (let ((res (calc-eval line)))
		 (cond
		   ((numberp res) res)
		   ((math-read-number res) (math-read-number res))
		   ((listp res) (error "Calc error \"%s\" on input \"%s\""
					 (cadr res) line))
		   (t (replace-regexp-in-string "'" ""
			(calc-eval
			  (math-evaluate-expr
				;; resolve user variables, calc built in
				;; variables are handled automatically
				;; upstream by calc
				(mapcar #'org-babel-calc-maybe-resolve-var
				;; parse line into calc objects
				(car (math-read-exprs line))))))))))))))))

(defun org-babel-calc-maybe-resolve-var (el)
  (if (consp el)
	(if (and (equal 'var (car el))
		 (member (symbol-name (cadr el)) org--ob-calc-var-names))
	  (progn
	    (calc-recall (cadr el))
	    (prog1
	      (calc-top 1)
	      (calc-pop 1)))
	  (mapcar #'org-babel-calc-maybe-resolve-var el))
    el))

(provide 'ob-calc)

;;; ob-calc.el ends here

debug log:

solving 2656f27 ...
found 2656f27 in https://yhetil.org/orgmode/1446581747-1960-10-git-send-email-oxij@oxij.org/
found e8b43e7 in https://yhetil.org/orgmode/1446581747-1960-9-git-send-email-oxij@oxij.org/
found a8c50da in https://git.savannah.gnu.org/cgit/emacs/org-mode.git
preparing index
index prepared:
100644 a8c50da93291ec026364ee8fc6f2ef28d3280938	lisp/ob-calc.el

applying [1/2] https://yhetil.org/orgmode/1446581747-1960-9-git-send-email-oxij@oxij.org/
diff --git a/lisp/ob-calc.el b/lisp/ob-calc.el
index a8c50da..e8b43e7 100644


applying [2/2] https://yhetil.org/orgmode/1446581747-1960-10-git-send-email-oxij@oxij.org/
diff --git a/lisp/ob-calc.el b/lisp/ob-calc.el
index e8b43e7..2656f27 100644

Checking patch lisp/ob-calc.el...
Applied patch lisp/ob-calc.el cleanly.
Checking patch lisp/ob-calc.el...
Applied patch lisp/ob-calc.el cleanly.

index at:
100644 2656f27fd1ed849eba459d9c899cda09248cdea4	lisp/ob-calc.el

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs/org-mode.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).