Spelling and typo fixes.
[bpt/emacs.git] / lisp / calculator.el
CommitLineData
40f7e0e8 1;;; calculator.el --- a [not so] simple calculator for Emacs -*- lexical-binding: t -*-
d240a249 2
ab422c4d 3;; Copyright (C) 1998, 2000-2013 Free Software Foundation, Inc.
d240a249 4
4ece8d61 5;; Author: Eli Barzilay <eli@barzilay.org>
d240a249 6;; Keywords: tools, convenience
d240a249
GM
7
8;; This file is part of GNU Emacs.
9
eb3fa2cf
GM
10;; GNU Emacs is free software: you can redistribute it and/or modify
11;; it under the terms of the GNU General Public License as published by
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
d240a249 14
eb3fa2cf
GM
15;; GNU Emacs is distributed in the hope that it will be useful,
16;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18;; GNU General Public License for more details.
d240a249
GM
19
20;; You should have received a copy of the GNU General Public License
eb3fa2cf 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
d240a249 22
cbb2dddb 23;;;=====================================================================
d240a249
GM
24;;; Commentary:
25;;
25c269ef 26;; A calculator for Emacs.
5ca425fc 27;; Why should you reach for your mouse to get xcalc (calc.exe, gcalc or
25c269ef 28;; whatever), when you have Emacs running already?
d240a249
GM
29;;
30;; If this is not part of your Emacs distribution, then simply bind
31;; `calculator' to a key and make it an autoloaded function, e.g.:
32;; (autoload 'calculator "calculator"
25c269ef 33;; "Run the Emacs calculator." t)
d240a249
GM
34;; (global-set-key [(control return)] 'calculator)
35;;
25c269ef
DL
36;; Written by Eli Barzilay: Maze is Life! eli@barzilay.org
37;; http://www.barzilay.org/
d240a249
GM
38;;
39;; For latest version, check
25c269ef 40;; http://www.barzilay.org/misc/calculator.el
4351784f
GM
41;;
42
43;;; History:
44;; I hate history.
d240a249 45
cbb2dddb 46;;;=====================================================================
d240a249
GM
47;;; Customization:
48
49(defgroup calculator nil
25c269ef 50 "Simple Emacs calculator."
d240a249 51 :prefix "calculator"
7def2f92 52 :version "21.1"
d240a249 53 :group 'tools
eba5b4dd 54 :group 'applications)
d240a249
GM
55
56(defcustom calculator-electric-mode nil
9201cc28 57 "Run `calculator' electrically, in the echo area.
25c269ef
DL
58Electric mode saves some place but changes the way you interact with the
59calculator."
d240a249
GM
60 :type 'boolean
61 :group 'calculator)
62
86f1e1ec 63(defcustom calculator-use-menu t
9201cc28 64 "Make `calculator' create a menu.
86f1e1ec
GM
65Note that this requires easymenu. Must be set before loading."
66 :type 'boolean
67 :group 'calculator)
68
d240a249 69(defcustom calculator-bind-escape nil
9201cc28 70 "If non-nil, set escape to exit the calculator."
d240a249
GM
71 :type 'boolean
72 :group 'calculator)
73
74(defcustom calculator-unary-style 'postfix
9201cc28 75 "Value is either 'prefix or 'postfix.
d240a249
GM
76This determines the default behavior of unary operators."
77 :type '(choice (const prefix) (const postfix))
78 :group 'calculator)
79
25c269ef 80(defcustom calculator-prompt "Calc=%s> "
9201cc28 81 "The prompt used by the Emacs calculator.
c80e3b4a 82It should contain a \"%s\" somewhere that will indicate the i/o radices;
bd9bb96e
JB
83this will be a two-character string as described in the documentation
84for `calculator-mode'."
d240a249
GM
85 :type 'string
86 :group 'calculator)
87
25c269ef 88(defcustom calculator-number-digits 3
9201cc28 89 "The calculator's number of digits used for standard display.
25c269ef
DL
90Used by the `calculator-standard-display' function - it will use the
91format string \"%.NC\" where this number is N and C is a character given
92at runtime."
2826ac81 93 :type 'integer
d240a249
GM
94 :group 'calculator)
95
761d3eb3 96(defcustom calculator-radix-grouping-mode t
9201cc28 97 "Use digit grouping in radix output mode.
761d3eb3
RS
98If this is set, chunks of `calculator-radix-grouping-digits' characters
99will be separated by `calculator-radix-grouping-separator' when in radix
f5307782
JB
100output mode is active (determined by `calculator-output-radix')."
101 :type 'boolean
102 :group 'calculator)
761d3eb3
RS
103
104(defcustom calculator-radix-grouping-digits 4
9201cc28 105 "The number of digits used for grouping display in radix modes.
f5307782
JB
106See `calculator-radix-grouping-mode'."
107 :type 'integer
108 :group 'calculator)
761d3eb3
RS
109
110(defcustom calculator-radix-grouping-separator "'"
9201cc28 111 "The separator used in radix grouping display.
f5307782
JB
112See `calculator-radix-grouping-mode'."
113 :type 'string
114 :group 'calculator)
761d3eb3 115
25c269ef 116(defcustom calculator-remove-zeros t
9201cc28 117 "Non-nil value means delete all redundant zero decimal digits.
25c269ef
DL
118If this value is not t, and not nil, redundant zeros are removed except
119for one and if it is nil, nothing is removed.
120Used by the `calculator-remove-zeros' function."
121 :type '(choice (const t) (const leave-decimal) (const nil))
d240a249
GM
122 :group 'calculator)
123
25c269ef 124(defcustom calculator-displayer '(std ?n)
9201cc28 125 "A displayer specification for numerical values.
25c269ef
DL
126This is the displayer used to show all numbers in an expression. Result
127values will be displayed according to the first element of
128`calculator-displayers'.
129
130The displayer is a symbol, a string or an expression. A symbol should
131be the name of a one-argument function, a string is used with a single
132argument and an expression will be evaluated with the variable `num'
133bound to whatever should be displayed. If it is a function symbol, it
40f7e0e8
SM
134should be able to handle special symbol arguments, currently `left' and
135`right' which will be sent by special keys to modify display parameters
25c269ef
DL
136associated with the displayer function (for example to change the number
137of digits displayed).
138
139An exception to the above is the case of the list (std C) where C is a
140character, in this case the `calculator-standard-displayer' function
f5307782
JB
141will be used with this character for a format string."
142 :group 'calculator)
25c269ef
DL
143
144(defcustom calculator-displayers
2188f2d4 145 '(((std ?n) "Standard display, decimal point or scientific")
25c269ef
DL
146 (calculator-eng-display "Eng display")
147 ((std ?f) "Standard display, decimal point")
2188f2d4 148 ((std ?e) "Standard display, scientific")
25c269ef 149 ("%S" "Emacs printer"))
9201cc28 150 "A list of displayers.
25c269ef 151Each element is a list of a displayer and a description string. The
2188f2d4 152first element is the one which is currently used, this is for the display
25c269ef
DL
153of result values not values in expressions. A displayer specification
154is the same as the values that can be stored in `calculator-displayer'.
155
156`calculator-rotate-displayer' rotates this list."
157 :type 'sexp
d240a249
GM
158 :group 'calculator)
159
25c269ef 160(defcustom calculator-paste-decimals t
9201cc28 161 "If non-nil, convert pasted integers so they have a decimal point.
25c269ef
DL
162This makes it possible to paste big integers since they will be read as
163floats, otherwise the Emacs reader will fail on them."
d240a249
GM
164 :type 'boolean
165 :group 'calculator)
166
4351784f 167(defcustom calculator-copy-displayer nil
9201cc28 168 "If non-nil, this is any value that can be used for
4351784f
GM
169`calculator-displayer', to format a string before copying it with
170`calculator-copy'. If nil, then `calculator-displayer's normal value is
f5307782
JB
171used."
172 :type 'boolean
173 :group 'calculator)
4351784f 174
d240a249 175(defcustom calculator-2s-complement nil
9201cc28 176 "If non-nil, show negative numbers in 2s complement in radix modes.
d240a249
GM
177Otherwise show as a negative number."
178 :type 'boolean
179 :group 'calculator)
180
181(defcustom calculator-mode-hook nil
9201cc28 182 "List of hook functions for `calculator-mode' to run.
761d3eb3
RS
183Note: if `calculator-electric-mode' is on, then this hook will get
184activated in the minibuffer - in that case it should not do much more
185than local key settings and other effects that will change things
186outside the scope of calculator related code."
d240a249
GM
187 :type 'hook
188 :group 'calculator)
189
190(defcustom calculator-user-registers nil
9201cc28 191 "An association list of user-defined register bindings.
d240a249
GM
192Each element in this list is a list of a character and a number that
193will be stored in that character's register.
194
195For example, use this to define the golden ratio number:
25c269ef
DL
196 (setq calculator-user-registers '((?g . 1.61803398875)))
197before you load calculator."
d240a249 198 :type '(repeat (cons character number))
4f91a816
SM
199 :set (lambda (_ val)
200 (and (boundp 'calculator-registers)
201 (setq calculator-registers
202 (append val calculator-registers)))
203 (setq calculator-user-registers val))
d240a249
GM
204 :group 'calculator)
205
206(defcustom calculator-user-operators nil
9201cc28 207 "A list of additional operators.
d240a249
GM
208This is a list in the same format as specified in the documentation for
209`calculator-operators', that you can use to bind additional calculator
210operators. It is probably not a good idea to modify this value with
211`customize' since it is too complex...
212
213Examples:
214
7def2f92
DL
215* A very simple one, adding a postfix \"x-to-y\" conversion keys, using
216 t as a prefix key:
d240a249
GM
217
218 (setq calculator-user-operators
219 '((\"tf\" cl-to-fr (+ 32 (/ (* X 9) 5)) 1)
220 (\"tc\" fr-to-cl (/ (* (- X 32) 5) 9) 1)
221 (\"tp\" kg-to-lb (/ X 0.453592) 1)
222 (\"tk\" lb-to-kg (* X 0.453592) 1)
223 (\"tF\" mt-to-ft (/ X 0.3048) 1)
224 (\"tM\" ft-to-mt (* X 0.3048) 1)))
225
226* Using a function-like form is very simple, X for an argument (Y the
227 second in case of a binary operator), TX is a truncated version of X
228 and F does a recursive call, Here is a [very inefficient] Fibonacci
229 number calculation:
230
231 (add-to-list 'calculator-user-operators
232 '(\"F\" fib (if (<= TX 1)
25c269ef
DL
233 1
234 (+ (F (- TX 1)) (F (- TX 2)))) 0))
d240a249
GM
235
236 Note that this will be either postfix or prefix, according to
237 `calculator-unary-style'."
238 :type '(repeat (list string symbol sexp integer integer))
239 :group 'calculator)
240
cbb2dddb 241;;;=====================================================================
d240a249
GM
242;;; Code:
243
40f7e0e8
SM
244(eval-when-compile (require 'cl-lib))
245
cbb2dddb 246;;;---------------------------------------------------------------------
25c269ef
DL
247;;; Variables
248
d240a249 249(defvar calculator-initial-operators
86f1e1ec
GM
250 '(;; "+"/"-" have keybindings of themselves, not calculator-ops
251 ("=" = identity 1 -1)
25c269ef
DL
252 (nobind "+" + + 2 4)
253 (nobind "-" - - 2 4)
254 (nobind "+" + + -1 9)
255 (nobind "-" - - -1 9)
86f1e1ec
GM
256 ("(" \( identity -1 -1)
257 (")" \) identity +1 10)
d240a249
GM
258 ;; normal keys
259 ("|" or (logior TX TY) 2 2)
260 ("#" xor (logxor TX TY) 2 2)
261 ("&" and (logand TX TY) 2 3)
262 ("*" * * 2 5)
263 ("/" / / 2 5)
264 ("\\" div (/ TX TY) 2 5)
265 ("%" rem (% TX TY) 2 5)
266 ("L" log log 2 6)
267 ("S" sin (sin DX) x 6)
268 ("C" cos (cos DX) x 6)
269 ("T" tan (tan DX) x 6)
270 ("IS" asin (D (asin X)) x 6)
271 ("IC" acos (D (acos X)) x 6)
272 ("IT" atan (D (atan X)) x 6)
273 ("Q" sqrt sqrt x 7)
f50347a9 274 ("^" ^ calculator-expt 2 7)
d240a249
GM
275 ("!" ! calculator-fact x 7)
276 (";" 1/ (/ 1 X) 1 7)
277 ("_" - - 1 8)
278 ("~" ~ (lognot TX) x 8)
279 (">" repR calculator-repR 1 8)
280 ("<" repL calculator-repL 1 8)
281 ("v" avg (/ (apply '+ L) (length L)) 0 8)
282 ("l" tot (apply '+ L) 0 8)
283 )
284 "A list of initial operators.
d240a249
GM
285This is a list in the same format as `calculator-operators'. Whenever
286`calculator' starts, it looks at the value of this variable, and if it
287is not empty, its contents is prepended to `calculator-operators' and
288the appropriate key bindings are made.
289
290This variable is then reset to nil. Don't use this if you want to add
291user-defined operators, use `calculator-user-operators' instead.")
292
293(defvar calculator-operators nil
294 "The calculator operators, each a list with:
295
2961. The key that is bound to for this operation (usually a string);
297
2982. The displayed symbol for this function;
299
3003. The function symbol, or a form that uses the variables `X' and `Y',
301 (if it is a binary operator), `TX' and `TY' (truncated integer
302 versions), `DX' (converted to radians if degrees mode is on), `D'
303 (function for converting radians to degrees if deg mode is on), `L'
304 (list of saved values), `F' (function for recursive iteration calls)
305 and evaluates to the function value - these variables are capital;
306
25c269ef
DL
3074. The function's arity, optional, one of: 2 => binary, -1 => prefix
308 unary, +1 => postfix unary, 0 => a 0-arg operator func, non-number =>
309 postfix/prefix as determined by `calculator-unary-style' (the
310 default);
d240a249 311
25c269ef
DL
3125. The function's precedence - should be in the range of 1 (lowest) to
313 9 (highest) (optional, defaults to 1);
d240a249
GM
314
315It it possible have a unary prefix version of a binary operator if it
316comes later in this list. If the list begins with the symbol 'nobind,
317then no key binding will take place - this is only useful for predefined
318keys.
319
320Use `calculator-user-operators' to add operators to this list, see its
321documentation for an example.")
322
323(defvar calculator-stack nil
324 "Stack contents - operations and operands.")
325
326(defvar calculator-curnum nil
327 "Current number being entered (as a string).")
328
329(defvar calculator-stack-display nil
330 "Cons of the stack and its string representation.")
331
332(defvar calculator-char-radix
333 '((?D . nil) (?B . bin) (?O . oct) (?H . hex) (?X . hex))
334 "A table to convert input characters to corresponding radix symbols.")
335
336(defvar calculator-output-radix nil
337 "The mode for display, one of: nil (decimal), 'bin, 'oct or 'hex.")
338
339(defvar calculator-input-radix nil
340 "The mode for input, one of: nil (decimal), 'bin, 'oct or 'hex.")
341
342(defvar calculator-deg nil
343 "Non-nil if trig functions operate on degrees instead of radians.")
344
345(defvar calculator-saved-list nil
346 "A list of saved values collected.")
347
348(defvar calculator-saved-ptr 0
349 "The pointer to the current saved number.")
350
351(defvar calculator-add-saved nil
352 "Bound to t when a value should be added to the saved-list.")
353
354(defvar calculator-display-fragile nil
355 "When non-nil, we see something that the next digit should replace.")
356
357(defvar calculator-buffer nil
358 "The current calculator buffer.")
359
25c269ef
DL
360(defvar calculator-eng-extra nil
361 "Internal value used by `calculator-eng-display'.")
362
363(defvar calculator-eng-tmp-show nil
364 "Internal value used by `calculator-eng-display'.")
365
d240a249
GM
366(defvar calculator-last-opXY nil
367 "The last binary operation and its arguments.
368Used for repeating operations in calculator-repR/L.")
369
370(defvar calculator-registers ; use user-bindings first
9e0d4f9e
SM
371 (append calculator-user-registers
372 (list (cons ?e float-e) (cons ?p float-pi)))
d240a249
GM
373 "The association list of calculator register values.")
374
375(defvar calculator-saved-global-map nil
376 "Saved global key map.")
377
86f1e1ec 378(defvar calculator-restart-other-mode nil
25c269ef
DL
379 "Used to hack restarting with the electric mode changed.")
380
cbb2dddb 381;;;---------------------------------------------------------------------
25c269ef 382;;; Key bindings
86f1e1ec 383
4d789d84 384(defvar calculator-mode-map
86f1e1ec 385 (let ((map (make-sparse-keymap)))
d240a249
GM
386 (suppress-keymap map t)
387 (define-key map "i" nil)
388 (define-key map "o" nil)
86f1e1ec 389 (let ((p
25c269ef
DL
390 '((calculator-open-paren "[")
391 (calculator-close-paren "]")
392 (calculator-op-or-exp "+" "-" [kp-add] [kp-subtract])
393 (calculator-digit "0" "1" "2" "3" "4" "5" "6" "7" "8"
394 "9" "a" "b" "c" "d" "f"
395 [kp-0] [kp-1] [kp-2] [kp-3] [kp-4]
396 [kp-5] [kp-6] [kp-7] [kp-8] [kp-9])
397 (calculator-op [kp-divide] [kp-multiply])
398 (calculator-decimal "." [kp-decimal])
399 (calculator-exp "e")
86f1e1ec
GM
400 (calculator-dec/deg-mode "D")
401 (calculator-set-register "s")
402 (calculator-get-register "g")
403 (calculator-radix-mode "H" "X" "O" "B")
404 (calculator-radix-input-mode "id" "ih" "ix" "io" "ib"
405 "iD" "iH" "iX" "iO" "iB")
406 (calculator-radix-output-mode "od" "oh" "ox" "oo" "ob"
407 "oD" "oH" "oX" "oO" "oB")
25c269ef
DL
408 (calculator-rotate-displayer "'")
409 (calculator-rotate-displayer-back "\"")
761d3eb3 410 (calculator-displayer-prev "{")
4351784f 411 (calculator-displayer-next "}")
86f1e1ec
GM
412 (calculator-saved-up [up] [?\C-p])
413 (calculator-saved-down [down] [?\C-n])
414 (calculator-quit "q" [?\C-g])
25c269ef
DL
415 (calculator-enter [enter] [linefeed] [kp-enter]
416 [return] [?\r] [?\n])
86f1e1ec
GM
417 (calculator-save-on-list " " [space])
418 (calculator-clear-saved [?\C-c] [(control delete)])
419 (calculator-save-and-quit [(control return)]
420 [(control kp-enter)])
cbb2dddb 421 (calculator-paste [insert] [(shift insert)]
761d3eb3 422 [paste] [mouse-2] [?\C-y])
86f1e1ec
GM
423 (calculator-clear [delete] [?\C-?] [?\C-d])
424 (calculator-help [?h] [??] [f1] [help])
761d3eb3 425 (calculator-copy [(control insert)] [copy])
86f1e1ec
GM
426 (calculator-backspace [backspace])
427 )))
d240a249 428 (while p
86f1e1ec
GM
429 ;; reverse the keys so first defs come last - makes the more
430 ;; sensible bindings visible in the menu
431 (let ((func (car (car p))) (keys (reverse (cdr (car p)))))
432 (while keys
433 (define-key map (car keys) func)
434 (setq keys (cdr keys))))
d240a249
GM
435 (setq p (cdr p))))
436 (if calculator-bind-escape
437 (progn (define-key map [?\e] 'calculator-quit)
438 (define-key map [escape] 'calculator-quit))
439 (define-key map [?\e ?\e ?\e] 'calculator-quit))
440 ;; make C-h work in text-mode
441 (or window-system (define-key map [?\C-h] 'calculator-backspace))
86f1e1ec
GM
442 ;; set up a menu
443 (if (and calculator-use-menu (not (boundp 'calculator-menu)))
444 (let ((radix-selectors
445 (mapcar (lambda (x)
446 `([,(nth 0 x)
447 (calculator-radix-mode ,(nth 2 x))
448 :style radio
449 :keys ,(nth 2 x)
450 :selected
451 (and
452 (eq calculator-input-radix ',(nth 1 x))
453 (eq calculator-output-radix ',(nth 1 x)))]
454 [,(concat (nth 0 x) " Input")
455 (calculator-radix-input-mode ,(nth 2 x))
456 :keys ,(concat "i" (downcase (nth 2 x)))
457 :style radio
458 :selected
459 (eq calculator-input-radix ',(nth 1 x))]
460 [,(concat (nth 0 x) " Output")
461 (calculator-radix-output-mode ,(nth 2 x))
462 :keys ,(concat "o" (downcase (nth 2 x)))
463 :style radio
464 :selected
465 (eq calculator-output-radix ',(nth 1 x))]))
466 '(("Decimal" nil "D")
467 ("Binary" bin "B")
468 ("Octal" oct "O")
469 ("Hexadecimal" hex "H"))))
4d789d84
SM
470 (op (lambda (name key)
471 `[,name (calculator-op ,key) :keys ,key])))
86f1e1ec 472 (easy-menu-define
4d789d84
SM
473 calculator-menu map "Calculator menu."
474 `("Calculator"
475 ["Help"
476 (let ((last-command 'calculator-help)) (calculator-help))
477 :keys "?"]
478 "---"
479 ["Copy" calculator-copy]
480 ["Paste" calculator-paste]
86f1e1ec 481 "---"
4d789d84
SM
482 ["Electric mode"
483 (progn (calculator-quit)
484 (setq calculator-restart-other-mode t)
4f91a816 485 (run-with-timer 0.1 nil (lambda () (message nil)))
4d789d84
SM
486 ;; the message from the menu will be visible,
487 ;; couldn't make it go away...
488 (calculator))
489 :active (not calculator-electric-mode)]
490 ["Normal mode"
491 (progn (setq calculator-restart-other-mode t)
492 (calculator-quit))
493 :active calculator-electric-mode]
86f1e1ec 494 "---"
4d789d84
SM
495 ("Functions"
496 ,(funcall op "Repeat-right" ">")
497 ,(funcall op "Repeat-left" "<")
498 "------General------"
499 ,(funcall op "Reciprocal" ";")
500 ,(funcall op "Log" "L")
501 ,(funcall op "Square-root" "Q")
502 ,(funcall op "Factorial" "!")
503 "------Trigonometric------"
504 ,(funcall op "Sinus" "S")
505 ,(funcall op "Cosine" "C")
506 ,(funcall op "Tangent" "T")
507 ,(funcall op "Inv-Sinus" "IS")
508 ,(funcall op "Inv-Cosine" "IC")
509 ,(funcall op "Inv-Tangent" "IT")
510 "------Bitwise------"
511 ,(funcall op "Or" "|")
512 ,(funcall op "Xor" "#")
513 ,(funcall op "And" "&")
514 ,(funcall op "Not" "~"))
515 ("Saved List"
516 ["Eval+Save" calculator-save-on-list]
517 ["Prev number" calculator-saved-up]
518 ["Next number" calculator-saved-down]
519 ["Delete current" calculator-clear
520 :active (and calculator-display-fragile
521 calculator-saved-list
522 (= (car calculator-stack)
523 (nth calculator-saved-ptr
524 calculator-saved-list)))]
525 ["Delete all" calculator-clear-saved]
86f1e1ec 526 "---"
4d789d84
SM
527 ,(funcall op "List-total" "l")
528 ,(funcall op "List-average" "v"))
529 ("Registers"
530 ["Get register" calculator-get-register]
531 ["Set register" calculator-set-register])
532 ("Modes"
533 ["Radians"
534 (progn
535 (and (or calculator-input-radix calculator-output-radix)
536 (calculator-radix-mode "D"))
537 (and calculator-deg (calculator-dec/deg-mode)))
538 :keys "D"
539 :style radio
540 :selected (not (or calculator-input-radix
541 calculator-output-radix
542 calculator-deg))]
543 ["Degrees"
544 (progn
545 (and (or calculator-input-radix calculator-output-radix)
546 (calculator-radix-mode "D"))
547 (or calculator-deg (calculator-dec/deg-mode)))
548 :keys "D"
549 :style radio
550 :selected (and calculator-deg
551 (not (or calculator-input-radix
552 calculator-output-radix)))]
553 "---"
554 ,@(mapcar 'car radix-selectors)
555 ("Separate I/O"
556 ,@(mapcar (lambda (x) (nth 1 x)) radix-selectors)
557 "---"
558 ,@(mapcar (lambda (x) (nth 2 x)) radix-selectors)))
559 ("Decimal Display"
560 ,@(mapcar (lambda (d)
561 (vector (cadr d)
562 ;; Note: inserts actual object here
563 `(calculator-rotate-displayer ',d)))
564 calculator-displayers)
565 "---"
566 ["Change Prev Display" calculator-displayer-prev]
567 ["Change Next Display" calculator-displayer-next])
25c269ef 568 "---"
4d789d84
SM
569 ["Copy+Quit" calculator-save-and-quit]
570 ["Quit" calculator-quit]))))
571 map)
572 "The calculator key map.")
d240a249 573
cbb2dddb 574;;;---------------------------------------------------------------------
25c269ef
DL
575;;; Startup and mode stuff
576
4d789d84 577(define-derived-mode calculator-mode fundamental-mode "Calculator"
25c269ef
DL
578 ;; this help is also used as the major help screen
579 "A [not so] simple calculator for Emacs.
d240a249
GM
580
581This calculator is used in the same way as other popular calculators
582like xcalc or calc.exe - but using an Emacs interface.
583
584Expressions are entered using normal infix notation, parens are used as
585normal. Unary functions are usually postfix, but some depends on the
586value of `calculator-unary-style' (if the style for an operator below is
587specified, then it is fixed, otherwise it depends on this variable).
588`+' and `-' can be used as either binary operators or prefix unary
589operators. Numbers can be entered with exponential notation using `e',
590except when using a non-decimal radix mode for input (in this case `e'
f50347a9
JB
591will be the hexadecimal digit). If the result of a calculation is too
592large (out of range for Emacs), the value of \"inf\" is returned.
d240a249
GM
593
594Here are the editing keys:
595* `RET' `=' evaluate the current expression
596* `C-insert' copy the whole current expression to the `kill-ring'
86f1e1ec 597* `C-return' evaluate, save result the `kill-ring' and exit
d240a249
GM
598* `insert' paste a number if the one was copied (normally)
599* `delete' `C-d' clear last argument or whole expression (hit twice)
600* `backspace' delete a digit or a previous expression element
601* `h' `?' pop-up a quick reference help
602* `ESC' `q' exit (`ESC' can be used if `calculator-bind-escape' is
603 non-nil, otherwise use three consecutive `ESC's)
604
605These operators are pre-defined:
606* `+' `-' `*' `/' the common binary operators
607* `\\' `%' integer division and reminder
608* `_' `;' postfix unary negation and reciprocal
609* `^' `L' binary operators for x^y and log(x) in base y
610* `Q' `!' unary square root and factorial
611* `S' `C' `T' unary trigonometric operators - sin, cos and tan
612* `|' `#' `&' `~' bitwise operators - or, xor, and, not
613
614The trigonometric functions can be inverted if prefixed with an `I', see
615below for the way to use degrees instead of the default radians.
616
617Two special postfix unary operators are `>' and `<': whenever a binary
618operator is performed, it is remembered along with its arguments; then
619`>' (`<') will apply the same operator with the same right (left)
620argument.
621
622hex/oct/bin modes can be set for input and for display separately.
623Another toggle-able mode is for using degrees instead of radians for
624trigonometric functions.
625The keys to switch modes are (`X' is shortcut for `H'):
626* `D' switch to all-decimal mode, or toggle degrees/radians
627* `B' `O' `H' `X' binary/octal/hexadecimal modes for input & display
628* `i' `o' followed by one of `D' `B' `O' `H' `X' (case
629 insensitive) sets only the input or display radix mode
630The prompt indicates the current modes:
631* \"D=\": degrees mode;
632* \"?=\": (? is B/O/H) this is the radix for both input and output;
633* \"=?\": (? is B/O/H) the display radix (when input is decimal);
634* \"??\": (? is D/B/O/H) 1st char for input radix, 2nd for display.
635
761d3eb3
RS
636Also, the quote key can be used to switch display modes for decimal
637numbers (double-quote rotates back), and the two brace characters
638\(\"{\" and \"}\" change display parameters that these displayers use (if
639they handle such). If output is using any radix mode, then these keys
640toggle digit grouping mode and the chunk size.
25c269ef 641
d240a249
GM
642Values can be saved for future reference in either a list of saved
643values, or in registers.
644
645The list of saved values is useful for statistics operations on some
646collected data. It is possible to navigate in this list, and if the
647value shown is the current one on the list, an indication is displayed
648as \"[N]\" if this is the last number and there are N numbers, or
649\"[M/N]\" if the M-th value is shown.
650* `SPC' evaluate the current value as usual, but also adds
651 the result to the list of saved values
652* `l' `v' computes total / average of saved values
653* `up' `C-p' browse to the previous value in the list
654* `down' `C-n' browse to the next value in the list
655* `delete' `C-d' remove current value from the list (if it is on it)
656* `C-delete' `C-c' delete the whole list
657
658Registers are variable-like place-holders for values:
659* `s' followed by a character attach the current value to that character
660* `g' followed by a character fetches the attached value
661
662There are many variables that can be used to customize the calculator.
663Some interesting customization variables are:
664* `calculator-electric-mode' use only the echo-area electrically.
665* `calculator-unary-style' set most unary ops to pre/postfix style.
666* `calculator-user-registers' to define user-preset registers.
667* `calculator-user-operators' to add user-defined operators.
668See the documentation for these variables, and \"calculator.el\" for
669more information.
670
4d789d84 671\\{calculator-mode-map}")
d240a249 672
f440830d
GM
673(declare-function Electric-command-loop "electric"
674 (return-tag &optional prompt inhibit-quitting
675 loop-function loop-state))
25c269ef 676
d240a249
GM
677;;;###autoload
678(defun calculator ()
25c269ef 679 "Run the Emacs calculator.
d240a249
GM
680See the documentation for `calculator-mode' for more information."
681 (interactive)
86f1e1ec
GM
682 (if calculator-restart-other-mode
683 (setq calculator-electric-mode (not calculator-electric-mode)))
d240a249
GM
684 (if calculator-initial-operators
685 (progn (calculator-add-operators calculator-initial-operators)
686 (setq calculator-initial-operators nil)
687 ;; don't change this since it is a customization variable,
25c269ef 688 ;; its set function will add any new operators
d240a249 689 (calculator-add-operators calculator-user-operators)))
cc234da9 690 (setq calculator-buffer (get-buffer-create "*calculator*"))
d240a249
GM
691 (if calculator-electric-mode
692 (save-window-excursion
86f1e1ec 693 (progn (require 'electric) (message nil)) ; hide load message
d240a249
GM
694 (let (old-g-map old-l-map (echo-keystrokes 0)
695 (garbage-collection-messages nil)) ; no gc msg when electric
cc234da9 696 (set-window-buffer (minibuffer-window) calculator-buffer)
d240a249
GM
697 (select-window (minibuffer-window))
698 (calculator-reset)
699 (calculator-update-display)
700 (setq old-l-map (current-local-map))
701 (setq old-g-map (current-global-map))
702 (setq calculator-saved-global-map (current-global-map))
86f1e1ec 703 (use-local-map nil)
d240a249 704 (use-global-map calculator-mode-map)
761d3eb3 705 (run-hooks 'calculator-mode-hook)
d240a249
GM
706 (unwind-protect
707 (catch 'calculator-done
708 (Electric-command-loop
709 'calculator-done
710 ;; can't use 'noprompt, bug in electric.el
4f91a816 711 (lambda () 'noprompt)
d240a249 712 nil
45fdb482 713 (lambda (_x _y) (calculator-update-display))))
d240a249
GM
714 (and calculator-buffer
715 (catch 'calculator-done (calculator-quit)))
716 (use-local-map old-l-map)
717 (use-global-map old-g-map))))
86f1e1ec 718 (progn
4351784f
GM
719 (cond
720 ((not (get-buffer-window calculator-buffer))
a4e32226 721 (let ((window-min-height 2))
37269466
CY
722 ;; maybe leave two lines for our window because of the
723 ;; normal `raised' mode line
4351784f 724 (select-window
2d197ffb 725 (split-window-below
37269466
CY
726 ;; If the mode line might interfere with the calculator
727 ;; buffer, use 3 lines instead.
4351784f 728 (if (and (fboundp 'face-attr-construct)
0098d2be 729 (let* ((dh (plist-get (face-attr-construct 'default) :height))
37269466 730 (mf (face-attr-construct 'mode-line))
0098d2be 731 (mh (plist-get mf :height)))
37269466 732 ;; If the mode line is shorter than the default,
bd9bb96e 733 ;; stick with 2 lines. (It may be necessary to
0098d2be
JB
734 ;; check how much shorter.)
735 (and
736 (not
737 (or (and (integerp dh)
738 (integerp mh)
739 (< mh dh))
740 (and (numberp mh)
741 (not (integerp mh))
742 (< mh 1))))
743 (or
37269466 744 ;; If the mode line is taller than the default,
0098d2be
JB
745 ;; use 3 lines.
746 (and (integerp dh)
747 (integerp mh)
748 (> mh dh))
749 (and (numberp mh)
750 (not (integerp mh))
751 (> mh 1))
37269466 752 ;; If the mode line has a box with non-negative line-width,
0098d2be
JB
753 ;; use 3 lines.
754 (let* ((bx (plist-get mf :box))
755 (lh (plist-get bx :line-width)))
756 (and bx
bd9bb96e 757 (or
0098d2be
JB
758 (not lh)
759 (> lh 0))))
37269466
CY
760 ;; If the mode line has an overline, use 3 lines.
761 (plist-get (face-attr-construct 'mode-line) :overline)))))
4351784f
GM
762 -3 -2)))
763 (switch-to-buffer calculator-buffer)))
764 ((not (eq (current-buffer) calculator-buffer))
765 (select-window (get-buffer-window calculator-buffer))))
86f1e1ec
GM
766 (calculator-mode)
767 (setq buffer-read-only t)
768 (calculator-reset)
769 (message "Hit `?' For a quick help screen.")))
770 (if (and calculator-restart-other-mode calculator-electric-mode)
771 (calculator)))
d240a249 772
761d3eb3
RS
773(defun calculator-message (string &rest arguments)
774 "Same as `message', but special handle of electric mode."
775 (apply 'message string arguments)
776 (if calculator-electric-mode
777 (progn (sit-for 1) (message nil))))
778
cbb2dddb 779;;;---------------------------------------------------------------------
2188f2d4 780;;; Operators
25c269ef 781
d240a249
GM
782(defun calculator-op-arity (op)
783 "Return OP's arity, 2, +1 or -1."
784 (let ((arity (or (nth 3 op) 'x)))
785 (if (numberp arity)
786 arity
787 (if (eq calculator-unary-style 'postfix) +1 -1))))
788
789(defun calculator-op-prec (op)
790 "Return OP's precedence for reducing when inserting into the stack.
791Defaults to 1."
792 (or (nth 4 op) 1))
793
794(defun calculator-add-operators (more-ops)
795 "This function handles operator addition.
796Adds MORE-OPS to `calculator-operator', called initially to handle
797`calculator-initial-operators' and `calculator-user-operators'."
798 (let ((added-ops nil))
799 (while more-ops
800 (or (eq (car (car more-ops)) 'nobind)
801 (let ((i -1) (key (car (car more-ops))))
802 ;; make sure the key is undefined, so it's easy to define
803 ;; prefix keys
804 (while (< (setq i (1+ i)) (length key))
805 (or (keymapp
806 (lookup-key calculator-mode-map
807 (substring key 0 (1+ i))))
808 (progn
809 (define-key
810 calculator-mode-map (substring key 0 (1+ i)) nil)
811 (setq i (length key)))))
812 (define-key calculator-mode-map key 'calculator-op)))
813 (setq added-ops (cons (if (eq (car (car more-ops)) 'nobind)
814 (cdr (car more-ops))
815 (car more-ops))
816 added-ops))
817 (setq more-ops (cdr more-ops)))
818 ;; added-ops come first, but in correct order
819 (setq calculator-operators
820 (append (nreverse added-ops) calculator-operators))))
821
cbb2dddb 822;;;---------------------------------------------------------------------
25c269ef
DL
823;;; Display stuff
824
d240a249
GM
825(defun calculator-reset ()
826 "Reset calculator variables."
86f1e1ec
GM
827 (or calculator-restart-other-mode
828 (setq calculator-stack nil
829 calculator-curnum nil
830 calculator-stack-display nil
831 calculator-display-fragile nil))
832 (setq calculator-restart-other-mode nil)
d240a249
GM
833 (calculator-update-display))
834
835(defun calculator-get-prompt ()
836 "Return a string to display.
837The string is set not to exceed the screen width."
838 (let* ((calculator-prompt
839 (format calculator-prompt
840 (cond
841 ((or calculator-output-radix calculator-input-radix)
842 (if (eq calculator-output-radix
843 calculator-input-radix)
844 (concat
845 (char-to-string
846 (car (rassq calculator-output-radix
847 calculator-char-radix)))
848 "=")
849 (concat
850 (if calculator-input-radix
851 (char-to-string
852 (car (rassq calculator-input-radix
853 calculator-char-radix)))
854 "=")
855 (char-to-string
856 (car (rassq calculator-output-radix
857 calculator-char-radix))))))
858 (calculator-deg "D=")
859 (t "=="))))
860 (prompt
861 (concat calculator-prompt
862 (cdr calculator-stack-display)
863 (cond (calculator-curnum
864 ;; number being typed
865 (concat calculator-curnum "_"))
866 ((and (= 1 (length calculator-stack))
867 calculator-display-fragile)
868 ;; only the result is shown, next number will
869 ;; restart
870 nil)
871 (t
872 ;; waiting for a number or an operator
873 "?"))))
874 (trim (- (length prompt) (1- (window-width)))))
875 (if (<= trim 0)
876 prompt
877 (concat calculator-prompt
878 (substring prompt (+ trim (length calculator-prompt)))))))
879
761d3eb3
RS
880(defun calculator-string-to-number (str)
881 "Convert the given STR to a number, according to the value of
882`calculator-input-radix'."
d240a249
GM
883 (if calculator-input-radix
884 (let ((radix
885 (cdr (assq calculator-input-radix
886 '((bin . 2) (oct . 8) (hex . 16)))))
761d3eb3
RS
887 (i -1) (value 0) (new-value 0))
888 ;; assume mostly valid input (e.g., characters in range)
889 (while (< (setq i (1+ i)) (length str))
890 (setq new-value
891 (let* ((ch (upcase (aref str i)))
892 (n (cond ((< ch ?0) nil)
893 ((<= ch ?9) (- ch ?0))
894 ((< ch ?A) nil)
895 ((<= ch ?Z) (- ch (- ?A 10)))
896 (t nil))))
897 (if (and n (<= 0 n) (< n radix))
898 (+ n (* radix value))
899 (progn
900 (calculator-message
901 "Warning: Ignoring bad input character `%c'." ch)
902 (sit-for 1)
903 value))))
904 (if (if (< new-value 0) (> value 0) (< value 0))
905 (calculator-message "Warning: Overflow in input."))
906 (setq value new-value))
d240a249 907 value)
761d3eb3
RS
908 (car (read-from-string
909 (cond ((equal "." str) "0.0")
45fdb482
JB
910 ((string-match-p "[eE][+-]?$" str) (concat str "0"))
911 ((string-match-p "\\.[0-9]\\|[eE]" str) str)
912 ((string-match-p "\\." str)
761d3eb3
RS
913 ;; do this because Emacs reads "23." as an integer
914 (concat str "0"))
915 ((stringp str) (concat str ".0"))
916 (t "0.0"))))))
917
918(defun calculator-curnum-value ()
919 "Get the numeric value of the displayed number string as a float."
920 (calculator-string-to-number calculator-curnum))
d240a249 921
25c269ef
DL
922(defun calculator-rotate-displayer (&optional new-disp)
923 "Switch to the next displayer on the `calculator-displayers' list.
924Can be called with an optional argument NEW-DISP to force rotation to
761d3eb3
RS
925that argument.
926If radix output mode is active, toggle digit grouping."
25c269ef 927 (interactive)
761d3eb3
RS
928 (cond
929 (calculator-output-radix
930 (setq calculator-radix-grouping-mode
931 (not calculator-radix-grouping-mode))
932 (calculator-message
933 "Digit grouping mode %s."
934 (if calculator-radix-grouping-mode "ON" "OFF")))
935 (t
936 (setq calculator-displayers
937 (if (and new-disp (memq new-disp calculator-displayers))
938 (let ((tmp nil))
939 (while (not (eq (car calculator-displayers) new-disp))
940 (setq tmp (cons (car calculator-displayers) tmp))
941 (setq calculator-displayers
942 (cdr calculator-displayers)))
943 (setq calculator-displayers
944 (nconc calculator-displayers (nreverse tmp))))
945 (nconc (cdr calculator-displayers)
946 (list (car calculator-displayers)))))
947 (calculator-message
948 "Using %s." (cadr (car calculator-displayers)))))
25c269ef
DL
949 (calculator-enter))
950
951(defun calculator-rotate-displayer-back ()
761d3eb3
RS
952 "Like `calculator-rotate-displayer', but rotates modes back.
953If radix output mode is active, toggle digit grouping."
25c269ef
DL
954 (interactive)
955 (calculator-rotate-displayer (car (last calculator-displayers))))
956
4351784f 957(defun calculator-displayer-prev ()
25c269ef
DL
958 "Send the current displayer function a 'left argument.
959This is used to modify display arguments (if the current displayer
761d3eb3
RS
960function supports this).
961If radix output mode is active, increase the grouping size."
25c269ef 962 (interactive)
761d3eb3
RS
963 (if calculator-output-radix
964 (progn (setq calculator-radix-grouping-digits
965 (1+ calculator-radix-grouping-digits))
966 (calculator-enter))
967 (and (car calculator-displayers)
968 (let ((disp (caar calculator-displayers)))
969 (cond
970 ((symbolp disp) (funcall disp 'left))
971 ((and (consp disp) (eq 'std (car disp)))
972 (calculator-standard-displayer 'left (cadr disp))))))))
25c269ef 973
4351784f 974(defun calculator-displayer-next ()
25c269ef
DL
975 "Send the current displayer function a 'right argument.
976This is used to modify display arguments (if the current displayer
761d3eb3
RS
977function supports this).
978If radix output mode is active, decrease the grouping size."
25c269ef 979 (interactive)
761d3eb3
RS
980 (if calculator-output-radix
981 (progn (setq calculator-radix-grouping-digits
982 (max 2 (1- calculator-radix-grouping-digits)))
983 (calculator-enter))
984 (and (car calculator-displayers)
985 (let ((disp (caar calculator-displayers)))
986 (cond
987 ((symbolp disp) (funcall disp 'right))
988 ((and (consp disp) (eq 'std (car disp)))
989 (calculator-standard-displayer 'right (cadr disp))))))))
25c269ef
DL
990
991(defun calculator-remove-zeros (numstr)
a1ff7705
JB
992 "Get a number string NUMSTR and remove unnecessary zeros.
993The behavior of this function is controlled by
25c269ef
DL
994`calculator-remove-zeros'."
995 (cond ((and (eq calculator-remove-zeros t)
996 (string-match "\\.0+\\([eE][+-]?[0-9]*\\)?$" numstr))
997 ;; remove all redundant zeros leaving an integer
998 (if (match-beginning 1)
999 (concat (substring numstr 0 (match-beginning 0))
1000 (match-string 1 numstr))
1001 (substring numstr 0 (match-beginning 0))))
1002 ((and calculator-remove-zeros
1003 (string-match
1004 "\\..\\([0-9]*[1-9]\\)?\\(0+\\)\\([eE][+-]?[0-9]*\\)?$"
1005 numstr))
1006 ;; remove zeros, except for first after the "."
1007 (if (match-beginning 3)
1008 (concat (substring numstr 0 (match-beginning 2))
1009 (match-string 3 numstr))
1010 (substring numstr 0 (match-beginning 2))))
1011 (t numstr)))
1012
1013(defun calculator-standard-displayer (num char)
1014 "Standard display function, used to display NUM.
1015Its behavior is determined by `calculator-number-digits' and the given
1016CHAR argument (both will be used to compose a format string). If the
1017char is \"n\" then this function will choose one between %f or %e, this
1018is a work around %g jumping to exponential notation too fast.
1019
1020The special 'left and 'right symbols will make it change the current
1021number of digits displayed (`calculator-number-digits').
1022
1023It will also remove redundant zeros from the result."
1024 (if (symbolp num)
1025 (cond ((eq num 'left)
1026 (and (> calculator-number-digits 0)
1027 (setq calculator-number-digits
1028 (1- calculator-number-digits))
1029 (calculator-enter)))
1030 ((eq num 'right)
1031 (setq calculator-number-digits
1032 (1+ calculator-number-digits))
1033 (calculator-enter)))
4351784f
GM
1034 (let ((str (if (zerop num)
1035 "0"
1036 (format
1037 (concat "%."
1038 (number-to-string calculator-number-digits)
1039 (if (eq char ?n)
1040 (let ((n (abs num)))
1041 (if (or (< n 0.001) (> n 1e8)) "e" "f"))
1042 (string char)))
1043 num))))
25c269ef
DL
1044 (calculator-remove-zeros str))))
1045
1046(defun calculator-eng-display (num)
1047 "Display NUM in engineering notation.
1048The number of decimal digits used is controlled by
1049`calculator-number-digits', so to change it at runtime you have to use
1050the 'left or 'right when one of the standard modes is used."
1051 (if (symbolp num)
1052 (cond ((eq num 'left)
1053 (setq calculator-eng-extra
1054 (if calculator-eng-extra
1055 (1+ calculator-eng-extra)
1056 1))
1057 (let ((calculator-eng-tmp-show t)) (calculator-enter)))
1058 ((eq num 'right)
1059 (setq calculator-eng-extra
1060 (if calculator-eng-extra
1061 (1- calculator-eng-extra)
1062 -1))
1063 (let ((calculator-eng-tmp-show t)) (calculator-enter))))
1064 (let ((exp 0))
1065 (and (not (= 0 num))
1066 (progn
1067 (while (< (abs num) 1.0)
1068 (setq num (* num 1000.0)) (setq exp (- exp 3)))
1069 (while (> (abs num) 999.0)
1070 (setq num (/ num 1000.0)) (setq exp (+ exp 3)))
1071 (and calculator-eng-tmp-show
1072 (not (= 0 calculator-eng-extra))
1073 (let ((i calculator-eng-extra))
1074 (while (> i 0)
1075 (setq num (* num 1000.0)) (setq exp (- exp 3))
1076 (setq i (1- i)))
1077 (while (< i 0)
1078 (setq num (/ num 1000.0)) (setq exp (+ exp 3))
1079 (setq i (1+ i)))))))
1080 (or calculator-eng-tmp-show (setq calculator-eng-extra nil))
6ac080e1
GM
1081 (let ((str (format (concat "%." (number-to-string
1082 calculator-number-digits)
1083 "f")
25c269ef
DL
1084 num)))
1085 (concat (let ((calculator-remove-zeros
1086 ;; make sure we don't leave integers
1087 (and calculator-remove-zeros 'x)))
1088 (calculator-remove-zeros str))
1089 "e" (number-to-string exp))))))
1090
761d3eb3 1091(defun calculator-number-to-string (num)
d240a249
GM
1092 "Convert NUM to a displayable string."
1093 (cond
1094 ((and (numberp num) calculator-output-radix)
1095 ;; print with radix - for binary I convert the octal number
1096 (let ((str (format (if (eq calculator-output-radix 'hex) "%x" "%o")
1097 (calculator-truncate
1098 (if calculator-2s-complement num (abs num))))))
1099 (if (eq calculator-output-radix 'bin)
1100 (let ((i -1) (s ""))
1101 (while (< (setq i (1+ i)) (length str))
1102 (setq s
1103 (concat s
1104 (cdr (assq (aref str i)
1105 '((?0 . "000") (?1 . "001")
1106 (?2 . "010") (?3 . "011")
1107 (?4 . "100") (?5 . "101")
1108 (?6 . "110") (?7 . "111")))))))
1109 (string-match "^0*\\(.+\\)" s)
1110 (setq str (match-string 1 s))))
761d3eb3
RS
1111 (if calculator-radix-grouping-mode
1112 (let ((d (/ (length str) calculator-radix-grouping-digits))
1113 (r (% (length str) calculator-radix-grouping-digits)))
1114 (while (>= (setq d (1- d)) (if (zerop r) 1 0))
1115 (let ((i (+ r (* d calculator-radix-grouping-digits))))
1116 (setq str (concat (substring str 0 i)
1117 calculator-radix-grouping-separator
1118 (substring str i)))))))
d240a249
GM
1119 (upcase
1120 (if (and (not calculator-2s-complement) (< num 0))
1121 (concat "-" str)
1122 str))))
4351784f
GM
1123 ((and (numberp num) calculator-displayer)
1124 (cond
1125 ((stringp calculator-displayer)
1126 (format calculator-displayer num))
1127 ((symbolp calculator-displayer)
1128 (funcall calculator-displayer num))
40f7e0e8 1129 ((eq 'std (car-safe calculator-displayer))
4351784f
GM
1130 (calculator-standard-displayer num (cadr calculator-displayer)))
1131 ((listp calculator-displayer)
40f7e0e8 1132 (eval calculator-displayer `((num. ,num))))
4351784f 1133 (t (prin1-to-string num t))))
25c269ef 1134 ;; operators are printed here
d240a249
GM
1135 (t (prin1-to-string (nth 1 num) t))))
1136
1137(defun calculator-update-display (&optional force)
1138 "Update the display.
1139If optional argument FORCE is non-nil, don't use the cached string."
1140 (set-buffer calculator-buffer)
1141 ;; update calculator-stack-display
1142 (if (or force
1143 (not (eq (car calculator-stack-display) calculator-stack)))
1144 (setq calculator-stack-display
1145 (cons calculator-stack
1146 (if calculator-stack
1147 (concat
4351784f
GM
1148 (let ((calculator-displayer
1149 (if (and calculator-displayers
1150 (= 1 (length calculator-stack)))
1151 ;; customizable display for a single value
1152 (caar calculator-displayers)
1153 calculator-displayer)))
761d3eb3 1154 (mapconcat 'calculator-number-to-string
4351784f
GM
1155 (reverse calculator-stack)
1156 " "))
d240a249
GM
1157 " "
1158 (and calculator-display-fragile
1159 calculator-saved-list
1160 (= (car calculator-stack)
1161 (nth calculator-saved-ptr
1162 calculator-saved-list))
1163 (if (= 0 calculator-saved-ptr)
1164 (format "[%s]" (length calculator-saved-list))
1165 (format "[%s/%s]"
1166 (- (length calculator-saved-list)
1167 calculator-saved-ptr)
1168 (length calculator-saved-list)))))
1169 ""))))
1170 (let ((inhibit-read-only t))
1171 (erase-buffer)
1172 (insert (calculator-get-prompt)))
1173 (set-buffer-modified-p nil)
1174 (if calculator-display-fragile
1175 (goto-char (1+ (length calculator-prompt)))
1176 (goto-char (1- (point)))))
1177
cbb2dddb 1178;;;---------------------------------------------------------------------
25c269ef
DL
1179;;; Stack computations
1180
d240a249
GM
1181(defun calculator-reduce-stack (prec)
1182 "Reduce the stack using top operator.
1183PREC is a precedence - reduce everything with higher precedence."
1184 (while
1185 (cond
1186 ((and (cdr (cdr calculator-stack)) ; have three values
1187 (consp (nth 0 calculator-stack)) ; two operators & num
1188 (numberp (nth 1 calculator-stack))
1189 (consp (nth 2 calculator-stack))
1190 (eq '\) (nth 1 (nth 0 calculator-stack)))
1191 (eq '\( (nth 1 (nth 2 calculator-stack))))
1192 ;; reduce "... ( x )" --> "... x"
1193 (setq calculator-stack
1194 (cons (nth 1 calculator-stack)
1195 (nthcdr 3 calculator-stack)))
1196 ;; another iteration
1197 t)
1198 ((and (cdr (cdr calculator-stack)) ; have three values
1199 (numberp (nth 0 calculator-stack)) ; two nums & operator
1200 (consp (nth 1 calculator-stack))
1201 (numberp (nth 2 calculator-stack))
1202 (= 2 (calculator-op-arity ; binary operator
1203 (nth 1 calculator-stack)))
1204 (<= prec ; with higher prec.
1205 (calculator-op-prec (nth 1 calculator-stack))))
1206 ;; reduce "... x op y" --> "... r", r is the result
1207 (setq calculator-stack
1208 (cons (calculator-funcall
1209 (nth 2 (nth 1 calculator-stack))
1210 (nth 2 calculator-stack)
1211 (nth 0 calculator-stack))
1212 (nthcdr 3 calculator-stack)))
1213 ;; another iteration
1214 t)
1215 ((and (>= (length calculator-stack) 2) ; have two values
1216 (numberp (nth 0 calculator-stack)) ; number & operator
1217 (consp (nth 1 calculator-stack))
1218 (= -1 (calculator-op-arity ; prefix-unary op
1219 (nth 1 calculator-stack)))
1220 (<= prec ; with higher prec.
1221 (calculator-op-prec (nth 1 calculator-stack))))
1222 ;; reduce "... op x" --> "... r" for prefix op
1223 (setq calculator-stack
1224 (cons (calculator-funcall
1225 (nth 2 (nth 1 calculator-stack))
1226 (nth 0 calculator-stack))
1227 (nthcdr 2 calculator-stack)))
1228 ;; another iteration
1229 t)
1230 ((and (cdr calculator-stack) ; have two values
1231 (consp (nth 0 calculator-stack)) ; operator & number
1232 (numberp (nth 1 calculator-stack))
1233 (= +1 (calculator-op-arity ; postfix-unary op
1234 (nth 0 calculator-stack)))
1235 (<= prec ; with higher prec.
1236 (calculator-op-prec (nth 0 calculator-stack))))
1237 ;; reduce "... x op" --> "... r" for postfix op
1238 (setq calculator-stack
1239 (cons (calculator-funcall
1240 (nth 2 (nth 0 calculator-stack))
1241 (nth 1 calculator-stack))
1242 (nthcdr 2 calculator-stack)))
1243 ;; another iteration
1244 t)
1245 ((and calculator-stack ; have one value
1246 (consp (nth 0 calculator-stack)) ; an operator
1247 (= 0 (calculator-op-arity ; 0-ary op
1248 (nth 0 calculator-stack))))
1249 ;; reduce "... op" --> "... r" for 0-ary op
1250 (setq calculator-stack
1251 (cons (calculator-funcall
1252 (nth 2 (nth 0 calculator-stack)))
1253 (nthcdr 1 calculator-stack)))
1254 ;; another iteration
1255 t)
1256 ((and (cdr calculator-stack) ; have two values
1257 (numberp (nth 0 calculator-stack)) ; both numbers
1258 (numberp (nth 1 calculator-stack)))
1259 ;; get rid of redundant numbers:
1260 ;; reduce "... y x" --> "... x"
1261 ;; needed for 0-ary ops that puts more values
1262 (setcdr calculator-stack (cdr (cdr calculator-stack))))
1263 (t ;; no more iterations
1264 nil))))
1265
25c269ef
DL
1266(defun calculator-funcall (f &optional X Y)
1267 "If F is a symbol, evaluate (F X Y).
1268Otherwise, it should be a list, evaluate it with X, Y bound to the
1269arguments."
1270 ;; remember binary ops for calculator-repR/L
1271 (if Y (setq calculator-last-opXY (list f X Y)))
1272 (condition-case nil
1273 ;; there used to be code here that returns 0 if the result was
1274 ;; smaller than calculator-epsilon (1e-15). I don't think this is
1275 ;; necessary now.
1276 (if (symbolp f)
40f7e0e8
SM
1277 (cond ((and X Y) (funcall f X Y))
1278 (X (funcall f X))
1279 (t (funcall f)))
25c269ef 1280 ;; f is an expression
40f7e0e8 1281 (let* ((TX (calculator-truncate X))
25c269ef
DL
1282 (TY (and Y (calculator-truncate Y)))
1283 (DX (if calculator-deg (/ (* X pi) 180) X))
40f7e0e8
SM
1284 (L calculator-saved-list))
1285 (cl-letf (((symbol-function 'F)
1286 (lambda (&optional x y) (calculator-funcall f x y)))
1287 ((symbol-function 'D)
1288 (lambda (x) (if calculator-deg (/ (* x 180) float-pi) x))))
1289 (eval f `((X . ,X)
84032db7 1290 (Y . ,Y)
40f7e0e8
SM
1291 (TX . ,TX)
1292 (TY . ,TY)
1293 (DX . ,DX)
1294 (L . ,L))))))
25c269ef
DL
1295 (error 0)))
1296
cbb2dddb 1297;;;---------------------------------------------------------------------
25c269ef
DL
1298;;; Input interaction
1299
86f1e1ec
GM
1300(defun calculator-last-input (&optional keys)
1301 "Last char (or event or event sequence) that was read.
1302Optional string argument KEYS will force using it as the keys entered."
1303 (let ((inp (or keys (this-command-keys))))
d240a249
GM
1304 (if (or (stringp inp) (not (arrayp inp)))
1305 inp
1306 ;; this translates kp-x to x and [tries to] create a string to
1307 ;; lookup operators
1308 (let* ((i -1) (converted-str (make-string (length inp) ? )) k)
1309 ;; converts an array to a string the ops lookup with keypad
1310 ;; input
1311 (while (< (setq i (1+ i)) (length inp))
1312 (setq k (aref inp i))
1313 ;; if Emacs will someday have a event-key, then this would
1314 ;; probably be modified anyway
d88757d6
RS
1315 (and (if (fboundp 'key-press-event-p) (key-press-event-p k))
1316 (if (fboundp 'event-key)
1317 (and (event-key k) (setq k (event-key k)))))
d240a249
GM
1318 ;; assume all symbols are translatable with an ascii-character
1319 (and (symbolp k)
1320 (setq k (or (get k 'ascii-character) ? )))
1321 (aset converted-str i k))
1322 converted-str))))
1323
1324(defun calculator-clear-fragile (&optional op)
1325 "Clear the fragile flag if it was set, then maybe reset all.
1326OP is the operator (if any) that caused this call."
1327 (if (and calculator-display-fragile
1328 (or (not op)
1329 (= -1 (calculator-op-arity op))
1330 (= 0 (calculator-op-arity op))))
1331 ;; reset if last calc finished, and now get a num or prefix or 0-ary
25c269ef 1332 ;; op
d240a249
GM
1333 (calculator-reset))
1334 (setq calculator-display-fragile nil))
1335
1336(defun calculator-digit ()
1337 "Enter a single digit."
1338 (interactive)
1339 (let ((inp (aref (calculator-last-input) 0)))
1340 (if (and (or calculator-display-fragile
1341 (not (numberp (car calculator-stack))))
1342 (cond
1343 ((not calculator-input-radix) (<= inp ?9))
1344 ((eq calculator-input-radix 'bin) (<= inp ?1))
1345 ((eq calculator-input-radix 'oct) (<= inp ?7))
1346 (t t)))
1347 ;; enter digit if starting a new computation or have an op on the
25c269ef 1348 ;; stack
d240a249
GM
1349 (progn
1350 (calculator-clear-fragile)
1351 (let ((digit (upcase (char-to-string inp))))
1352 (if (equal calculator-curnum "0")
1353 (setq calculator-curnum nil))
1354 (setq calculator-curnum
1355 (concat (or calculator-curnum "") digit)))
1356 (calculator-update-display)))))
1357
1358(defun calculator-decimal ()
1359 "Enter a decimal period."
1360 (interactive)
1361 (if (and (not calculator-input-radix)
1362 (or calculator-display-fragile
1363 (not (numberp (car calculator-stack))))
1364 (not (and calculator-curnum
45fdb482 1365 (string-match-p "[.eE]" calculator-curnum))))
d240a249 1366 ;; enter the period on the same condition as a digit, only if no
25c269ef 1367 ;; period or exponent entered yet
d240a249
GM
1368 (progn
1369 (calculator-clear-fragile)
1370 (setq calculator-curnum (concat (or calculator-curnum "0") "."))
1371 (calculator-update-display))))
1372
1373(defun calculator-exp ()
1374 "Enter an `E' exponent character, or a digit in hex input mode."
1375 (interactive)
1376 (if calculator-input-radix
1377 (calculator-digit)
1378 (if (and (or calculator-display-fragile
1379 (not (numberp (car calculator-stack))))
1380 (not (and calculator-curnum
45fdb482 1381 (string-match-p "[eE]" calculator-curnum))))
25c269ef 1382 ;; same condition as above, also no E so far
d240a249
GM
1383 (progn
1384 (calculator-clear-fragile)
1385 (setq calculator-curnum (concat (or calculator-curnum "1") "e"))
1386 (calculator-update-display)))))
1387
86f1e1ec
GM
1388(defun calculator-op (&optional keys)
1389 "Enter an operator on the stack, doing all necessary reductions.
1390Optional string argument KEYS will force using it as the keys entered."
d240a249 1391 (interactive)
25c269ef
DL
1392 (catch 'op-error
1393 (let* ((last-inp (calculator-last-input keys))
1394 (op (assoc last-inp calculator-operators)))
1395 (calculator-clear-fragile op)
1396 (if (and calculator-curnum (/= (calculator-op-arity op) 0))
1397 (setq calculator-stack
1398 (cons (calculator-curnum-value) calculator-stack)))
1399 (setq calculator-curnum nil)
1400 (if (and (= 2 (calculator-op-arity op))
1401 (not (and calculator-stack
1402 (numberp (nth 0 calculator-stack)))))
1403 ;; we have a binary operator but no number - search for a prefix
1404 ;; version
1405 (let ((rest-ops calculator-operators))
1406 (while (not (equal last-inp (car (car rest-ops))))
1407 (setq rest-ops (cdr rest-ops)))
1408 (setq op (assoc last-inp (cdr rest-ops)))
1409 (if (not (and op (= -1 (calculator-op-arity op))))
1410 ;;(error "Binary operator without a first operand")
1411 (progn
761d3eb3
RS
1412 (calculator-message
1413 "Binary operator without a first operand")
25c269ef
DL
1414 (throw 'op-error nil)))))
1415 (calculator-reduce-stack
1416 (cond ((eq (nth 1 op) '\() 10)
1417 ((eq (nth 1 op) '\)) 0)
1418 (t (calculator-op-prec op))))
1419 (if (or (and (= -1 (calculator-op-arity op))
1420 (numberp (car calculator-stack)))
1421 (and (/= (calculator-op-arity op) -1)
1422 (/= (calculator-op-arity op) 0)
1423 (not (numberp (car calculator-stack)))))
1424 ;;(error "Unterminated expression")
1425 (progn
761d3eb3 1426 (calculator-message "Unterminated expression")
25c269ef
DL
1427 (throw 'op-error nil)))
1428 (setq calculator-stack (cons op calculator-stack))
1429 (calculator-reduce-stack (calculator-op-prec op))
1430 (and (= (length calculator-stack) 1)
1431 (numberp (nth 0 calculator-stack))
1432 ;; the display is fragile if it contains only one number
1433 (setq calculator-display-fragile t)
1434 ;; add number to the saved-list
1435 calculator-add-saved
1436 (if (= 0 calculator-saved-ptr)
1437 (setq calculator-saved-list
1438 (cons (car calculator-stack) calculator-saved-list))
1439 (let ((p (nthcdr (1- calculator-saved-ptr)
1440 calculator-saved-list)))
1441 (setcdr p (cons (car calculator-stack) (cdr p))))))
1442 (calculator-update-display))))
d240a249
GM
1443
1444(defun calculator-op-or-exp ()
1445 "Either enter an operator or a digit.
25c269ef 1446Used with +/- for entering them as digits in numbers like 1e-3 (there is
a1ff7705 1447no need for negative numbers since these are handled by unary operators)."
d240a249
GM
1448 (interactive)
1449 (if (and (not calculator-display-fragile)
1450 calculator-curnum
45fdb482 1451 (string-match-p "[eE]$" calculator-curnum))
d240a249
GM
1452 (calculator-digit)
1453 (calculator-op)))
1454
cbb2dddb 1455;;;---------------------------------------------------------------------
25c269ef
DL
1456;;; Input/output modes (not display)
1457
d240a249
GM
1458(defun calculator-dec/deg-mode ()
1459 "Set decimal mode for display & input, if decimal, toggle deg mode."
1460 (interactive)
1461 (if calculator-curnum
1462 (setq calculator-stack
1463 (cons (calculator-curnum-value) calculator-stack)))
1464 (setq calculator-curnum nil)
1465 (if (or calculator-input-radix calculator-output-radix)
1466 (progn (setq calculator-input-radix nil)
1467 (setq calculator-output-radix nil))
1468 ;; already decimal - toggle degrees mode
1469 (setq calculator-deg (not calculator-deg)))
1470 (calculator-update-display t))
1471
86f1e1ec
GM
1472(defun calculator-radix-mode (&optional keys)
1473 "Set input and display radix modes.
1474Optional string argument KEYS will force using it as the keys entered."
d240a249 1475 (interactive)
86f1e1ec
GM
1476 (calculator-radix-input-mode keys)
1477 (calculator-radix-output-mode keys))
d240a249 1478
86f1e1ec
GM
1479(defun calculator-radix-input-mode (&optional keys)
1480 "Set input radix modes.
1481Optional string argument KEYS will force using it as the keys entered."
d240a249
GM
1482 (interactive)
1483 (if calculator-curnum
1484 (setq calculator-stack
1485 (cons (calculator-curnum-value) calculator-stack)))
1486 (setq calculator-curnum nil)
1487 (setq calculator-input-radix
86f1e1ec 1488 (let ((inp (calculator-last-input keys)))
d240a249
GM
1489 (cdr (assq (upcase (aref inp (1- (length inp))))
1490 calculator-char-radix))))
1491 (calculator-update-display))
1492
86f1e1ec
GM
1493(defun calculator-radix-output-mode (&optional keys)
1494 "Set display radix modes.
1495Optional string argument KEYS will force using it as the keys entered."
d240a249
GM
1496 (interactive)
1497 (if calculator-curnum
1498 (setq calculator-stack
1499 (cons (calculator-curnum-value) calculator-stack)))
1500 (setq calculator-curnum nil)
1501 (setq calculator-output-radix
86f1e1ec 1502 (let ((inp (calculator-last-input keys)))
d240a249
GM
1503 (cdr (assq (upcase (aref inp (1- (length inp))))
1504 calculator-char-radix))))
1505 (calculator-update-display t))
1506
cbb2dddb 1507;;;---------------------------------------------------------------------
25c269ef
DL
1508;;; Saved values list
1509
d240a249
GM
1510(defun calculator-save-on-list ()
1511 "Evaluate current expression, put result on the saved values list."
1512 (interactive)
1513 (let ((calculator-add-saved t)) ; marks the result to be added
1514 (calculator-enter)))
1515
1516(defun calculator-clear-saved ()
1517 "Clear the list of saved values in `calculator-saved-list'."
1518 (interactive)
1519 (setq calculator-saved-list nil)
25c269ef 1520 (setq calculator-saved-ptr 0)
d240a249
GM
1521 (calculator-update-display t))
1522
1523(defun calculator-saved-move (n)
1524 "Go N elements up the list of saved values."
1525 (interactive)
1526 (and calculator-saved-list
1527 (or (null calculator-stack) calculator-display-fragile)
1528 (progn
1529 (setq calculator-saved-ptr
1530 (max (min (+ n calculator-saved-ptr)
1531 (length calculator-saved-list))
1532 0))
1533 (if (nth calculator-saved-ptr calculator-saved-list)
1534 (setq calculator-stack
1535 (list (nth calculator-saved-ptr calculator-saved-list))
1536 calculator-display-fragile t)
86f1e1ec
GM
1537 (calculator-reset))
1538 (calculator-update-display))))
d240a249
GM
1539
1540(defun calculator-saved-up ()
1541 "Go up the list of saved values."
1542 (interactive)
1543 (calculator-saved-move +1))
1544
1545(defun calculator-saved-down ()
1546 "Go down the list of saved values."
1547 (interactive)
1548 (calculator-saved-move -1))
1549
cbb2dddb 1550;;;---------------------------------------------------------------------
25c269ef
DL
1551;;; Misc functions
1552
d240a249
GM
1553(defun calculator-open-paren ()
1554 "Equivalents of `(' use this."
1555 (interactive)
86f1e1ec 1556 (calculator-op "("))
d240a249
GM
1557
1558(defun calculator-close-paren ()
1559 "Equivalents of `)' use this."
1560 (interactive)
86f1e1ec 1561 (calculator-op ")"))
d240a249
GM
1562
1563(defun calculator-enter ()
86f1e1ec 1564 "Evaluate current expression."
d240a249 1565 (interactive)
86f1e1ec 1566 (calculator-op "="))
d240a249
GM
1567
1568(defun calculator-backspace ()
1569 "Backward delete a single digit or a stack element."
1570 (interactive)
1571 (if calculator-curnum
1572 (setq calculator-curnum
1573 (if (> (length calculator-curnum) 1)
1574 (substring calculator-curnum
1575 0 (1- (length calculator-curnum)))
1576 nil))
1577 (setq calculator-stack (cdr calculator-stack)))
1578 (calculator-update-display))
1579
1580(defun calculator-clear ()
1581 "Clear current number."
1582 (interactive)
1583 (setq calculator-curnum nil)
1584 (cond
1585 ;; if the current number is from the saved-list - remove it
1586 ((and calculator-display-fragile
1587 calculator-saved-list
1588 (= (car calculator-stack)
1589 (nth calculator-saved-ptr calculator-saved-list)))
1590 (if (= 0 calculator-saved-ptr)
1591 (setq calculator-saved-list (cdr calculator-saved-list))
1592 (let ((p (nthcdr (1- calculator-saved-ptr)
1593 calculator-saved-list)))
1594 (setcdr p (cdr (cdr p)))
1595 (setq calculator-saved-ptr (1- calculator-saved-ptr))))
1596 (if calculator-saved-list
1597 (setq calculator-stack
1598 (list (nth calculator-saved-ptr calculator-saved-list)))
1599 (calculator-reset)))
1600 ;; reset if fragile or double clear
1601 ((or calculator-display-fragile (eq last-command this-command))
1602 (calculator-reset)))
1603 (calculator-update-display))
1604
1605(defun calculator-copy ()
1606 "Copy current number to the `kill-ring'."
1607 (interactive)
4351784f
GM
1608 (let ((calculator-displayer
1609 (or calculator-copy-displayer calculator-displayer))
1610 (calculator-displayers
1611 (if calculator-copy-displayer nil calculator-displayers)))
1612 (calculator-enter)
1214bb6e 1613 ;; remove trailing spaces and an index
4351784f
GM
1614 (let ((s (cdr calculator-stack-display)))
1615 (and s
1616 (if (string-match "^\\([^ ]+\\) *\\(\\[[0-9/]+\\]\\)? *$" s)
1617 (setq s (match-string 1 s)))
1618 (kill-new s)))))
d240a249
GM
1619
1620(defun calculator-set-register (reg)
1621 "Set a register value for REG."
1622 (interactive "cRegister to store into: ")
1623 (let* ((as (assq reg calculator-registers))
1624 (val (progn (calculator-enter) (car calculator-stack))))
1625 (if as
1626 (setcdr as val)
1627 (setq calculator-registers
1628 (cons (cons reg val) calculator-registers)))
761d3eb3 1629 (calculator-message "[%c] := %S" reg val)))
d240a249
GM
1630
1631(defun calculator-put-value (val)
1632 "Paste VAL as if entered.
1633Used by `calculator-paste' and `get-register'."
1634 (if (and (numberp val)
1635 ;; (not calculator-curnum)
1636 (or calculator-display-fragile
1637 (not (numberp (car calculator-stack)))))
1638 (progn
1639 (calculator-clear-fragile)
4351784f 1640 (setq calculator-curnum (let ((calculator-displayer "%S"))
761d3eb3 1641 (calculator-number-to-string val)))
d240a249
GM
1642 (calculator-update-display))))
1643
1644(defun calculator-paste ()
1645 "Paste a value from the `kill-ring'."
1646 (interactive)
1647 (calculator-put-value
761d3eb3
RS
1648 (let ((str (replace-regexp-in-string
1649 "^ *\\(.+[^ ]\\) *$" "\\1" (current-kill 0))))
1650 (and (not calculator-input-radix)
1651 calculator-paste-decimals
cbb2dddb
GM
1652 (string-match "\\([0-9]+\\)\\(\\.[0-9]+\\)?\\(e[0-9]+\\)?"
1653 str)
1654 (or (match-string 1 str)
1655 (match-string 2 str)
1656 (match-string 3 str))
761d3eb3 1657 (setq str (concat (or (match-string 1 str) "0")
cbb2dddb 1658 (or (match-string 2 str) ".0")
761d3eb3 1659 (or (match-string 3 str) ""))))
45fdb482 1660 (ignore-errors (calculator-string-to-number str)))))
d240a249
GM
1661
1662(defun calculator-get-register (reg)
1663 "Get a value from a register REG."
1664 (interactive "cRegister to get value from: ")
1665 (calculator-put-value (cdr (assq reg calculator-registers))))
1666
f440830d
GM
1667(declare-function electric-describe-mode "ehelp" ())
1668
d240a249
GM
1669(defun calculator-help ()
1670 ;; this is used as the quick reference screen you get with `h'
1671 "Quick reference:
1672* numbers/operators/parens/./e - enter expressions
1673 + - * / \\(div) %(rem) _(-X,postfix) ;(1/X,postfix) ^(exp) L(og)
1674 Q(sqrt) !(fact) S(in) C(os) T(an) |(or) #(xor) &(and) ~(not)
1675* >/< repeats last binary operation with its 2nd (1st) arg as postfix op
25c269ef
DL
1676* I inverses next trig function * '/\"/{} - display/display args
1677* D - switch to all-decimal, or toggle deg/rad mode
d240a249
GM
1678* B/O/H/X - binary/octal/hex mode for i/o (X is a shortcut for H)
1679* i/o - prefix for d/b/o/x - set only input/output modes
1680* enter/= - evaluate current expr. * s/g - set/get a register
1681* space - evaluate & save on list * l/v - list total/average
1682* up/down/C-p/C-n - browse saved * C-delete - clear all saved
86f1e1ec 1683* C-insert - copy whole expr. * C-return - evaluate, copy, exit
d240a249
GM
1684* insert - paste a number * backspace- delete backwards
1685* delete - clear argument or list value or whole expression (twice)
1686* escape/q - exit."
1687 (interactive)
1688 (if (eq last-command 'calculator-help)
1689 (let ((mode-name "Calculator")
1690 (major-mode 'calculator-mode)
1691 (g-map (current-global-map))
1692 (win (selected-window)))
1693 (require 'ehelp)
1694 (if calculator-electric-mode
1695 (use-global-map calculator-saved-global-map))
cbb2dddb
GM
1696 (if (or (not calculator-electric-mode)
1697 ;; XEmacs has a problem with electric-describe-mode
f8246027 1698 (featurep 'xemacs))
f440830d 1699 (describe-mode)
cbb2dddb 1700 (electric-describe-mode))
d240a249
GM
1701 (if calculator-electric-mode
1702 (use-global-map g-map))
1703 (select-window win) ; these are for XEmacs (also below)
1704 (message nil))
1705 (let ((one (one-window-p t))
1706 (win (selected-window))
1707 (help-buf (get-buffer-create "*Help*")))
1708 (save-window-excursion
1709 (with-output-to-temp-buffer "*Help*"
1710 (princ (documentation 'calculator-help)))
1711 (if one
1712 (shrink-window-if-larger-than-buffer
1713 (get-buffer-window help-buf)))
1714 (message
1715 "`%s' again for more help, any other key continues normally."
1716 (calculator-last-input))
1717 (select-window win)
1718 (sit-for 360))
1719 (select-window win))))
1720
1721(defun calculator-quit ()
1722 "Quit calculator."
1723 (interactive)
1724 (set-buffer calculator-buffer)
1725 (let ((inhibit-read-only t)) (erase-buffer))
45fdb482
JB
1726 (unless calculator-electric-mode
1727 (ignore-errors
1728 (while (get-buffer-window calculator-buffer)
1729 (delete-window (get-buffer-window calculator-buffer))))
1730 (kill-buffer calculator-buffer))
d240a249
GM
1731 (setq calculator-buffer nil)
1732 (message "Calculator done.")
1733 (if calculator-electric-mode (throw 'calculator-done nil)))
1734
1735(defun calculator-save-and-quit ()
1736 "Quit the calculator, saving the result on the `kill-ring'."
1737 (interactive)
1738 (calculator-enter)
1739 (calculator-copy)
1740 (calculator-quit))
1741
d240a249 1742(defun calculator-repR (x)
a1ff7705 1743 "Repeat the last binary operation with its second argument and X.
d240a249
GM
1744To use this, apply a binary operator (evaluate it), then call this."
1745 (if calculator-last-opXY
1746 ;; avoid rebinding calculator-last-opXY
1747 (let ((calculator-last-opXY calculator-last-opXY))
1748 (calculator-funcall
1749 (car calculator-last-opXY) x (nth 2 calculator-last-opXY)))
1750 x))
1751
1752(defun calculator-repL (x)
a1ff7705 1753 "Repeat the last binary operation with its first argument and X.
d240a249
GM
1754To use this, apply a binary operator (evaluate it), then call this."
1755 (if calculator-last-opXY
1756 ;; avoid rebinding calculator-last-opXY
1757 (let ((calculator-last-opXY calculator-last-opXY))
1758 (calculator-funcall
1759 (car calculator-last-opXY) (nth 1 calculator-last-opXY) x))
1760 x))
1761
f50347a9
JB
1762(defun calculator-integer-p (x)
1763 "Non-nil if X is equal to an integer."
45fdb482 1764 (ignore-errors (= x (ftruncate x))))
f50347a9
JB
1765
1766(defun calculator-expt (x y)
1767 "Compute X^Y, dealing with errors appropriately."
45fdb482 1768 (condition-case nil
f50347a9
JB
1769 (expt x y)
1770 (domain-error 0.0e+NaN)
1771 (range-error
b4739e5d
JB
1772 (cond
1773 ((and (< x 1.0) (> x -1.0))
1774 ;; For small x, the range error comes from large y.
1775 0.0)
1776 ((and (> x 0.0) (< y 0.0))
cba1a4bd 1777 ;; For large positive x and negative y, the range error
b4739e5d
JB
1778 ;; comes from large negative y.
1779 0.0)
1780 ((and (> x 0.0) (> y 0.0))
cba1a4bd 1781 ;; For large positive x and positive y, the range error
b4739e5d
JB
1782 ;; comes from large y.
1783 1.0e+INF)
1784 ;; For the rest, x must be large and negative.
1785 ;; The range errors come from large integer y.
1786 ((< y 0.0)
1787 0.0)
cba1a4bd 1788 ((eq (logand (truncate y) 1) 1) ; expansion of cl `oddp'
b4739e5d
JB
1789 ;; If y is odd
1790 -1.0e+INF)
1791 (t
a1ff7705 1792 ;;
b4739e5d 1793 1.0e+INF)))
f50347a9
JB
1794 (error 0.0e+NaN)))
1795
d240a249
GM
1796(defun calculator-fact (x)
1797 "Simple factorial of X."
f50347a9
JB
1798 (if (and (>= x 0)
1799 (calculator-integer-p x))
1800 (if (= (calculator-expt (/ x 3.0) x) 1.0e+INF)
1801 1.0e+INF
1802 (let ((r (if (<= x 10) 1 1.0)))
1803 (while (> x 0)
1804 (setq r (* r (truncate x)))
1805 (setq x (1- x)))
1806 (+ 0.0 r)))
1807 (if (= x 1.0e+INF)
1808 x
1809 0.0e+NaN)))
d240a249
GM
1810
1811(defun calculator-truncate (n)
1812 "Truncate N, return 0 in case of overflow."
1813 (condition-case nil (truncate n) (error 0)))
1814
1815
1816(provide 'calculator)
1817
1818;;; calculator.el ends here