* alloc.c (which_symbols): Declare EXTERNALLY_VISIBLE,
[bpt/emacs.git] / lisp / calculator.el
CommitLineData
e8af40ee 1;;; calculator.el --- a [not so] simple calculator for Emacs
d240a249 2
73b0cd50 3;; Copyright (C) 1998, 2000-2011 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
3b44dbc5 46(eval-when-compile (require 'cl))
d240a249 47
cbb2dddb 48;;;=====================================================================
d240a249
GM
49;;; Customization:
50
51(defgroup calculator nil
25c269ef 52 "Simple Emacs calculator."
d240a249 53 :prefix "calculator"
7def2f92 54 :version "21.1"
d240a249 55 :group 'tools
eba5b4dd 56 :group 'applications)
d240a249
GM
57
58(defcustom calculator-electric-mode nil
9201cc28 59 "Run `calculator' electrically, in the echo area.
25c269ef
DL
60Electric mode saves some place but changes the way you interact with the
61calculator."
d240a249
GM
62 :type 'boolean
63 :group 'calculator)
64
86f1e1ec 65(defcustom calculator-use-menu t
9201cc28 66 "Make `calculator' create a menu.
86f1e1ec
GM
67Note that this requires easymenu. Must be set before loading."
68 :type 'boolean
69 :group 'calculator)
70
d240a249 71(defcustom calculator-bind-escape nil
9201cc28 72 "If non-nil, set escape to exit the calculator."
d240a249
GM
73 :type 'boolean
74 :group 'calculator)
75
76(defcustom calculator-unary-style 'postfix
9201cc28 77 "Value is either 'prefix or 'postfix.
d240a249
GM
78This determines the default behavior of unary operators."
79 :type '(choice (const prefix) (const postfix))
80 :group 'calculator)
81
25c269ef 82(defcustom calculator-prompt "Calc=%s> "
9201cc28 83 "The prompt used by the Emacs calculator.
bd9bb96e
JB
84It should contain a \"%s\" somewhere that will indicate the i/o radixes;
85this will be a two-character string as described in the documentation
86for `calculator-mode'."
d240a249
GM
87 :type 'string
88 :group 'calculator)
89
25c269ef 90(defcustom calculator-number-digits 3
9201cc28 91 "The calculator's number of digits used for standard display.
25c269ef
DL
92Used by the `calculator-standard-display' function - it will use the
93format string \"%.NC\" where this number is N and C is a character given
94at runtime."
2826ac81 95 :type 'integer
d240a249
GM
96 :group 'calculator)
97
761d3eb3 98(defcustom calculator-radix-grouping-mode t
9201cc28 99 "Use digit grouping in radix output mode.
761d3eb3
RS
100If this is set, chunks of `calculator-radix-grouping-digits' characters
101will be separated by `calculator-radix-grouping-separator' when in radix
f5307782
JB
102output mode is active (determined by `calculator-output-radix')."
103 :type 'boolean
104 :group 'calculator)
761d3eb3
RS
105
106(defcustom calculator-radix-grouping-digits 4
9201cc28 107 "The number of digits used for grouping display in radix modes.
f5307782
JB
108See `calculator-radix-grouping-mode'."
109 :type 'integer
110 :group 'calculator)
761d3eb3
RS
111
112(defcustom calculator-radix-grouping-separator "'"
9201cc28 113 "The separator used in radix grouping display.
f5307782
JB
114See `calculator-radix-grouping-mode'."
115 :type 'string
116 :group 'calculator)
761d3eb3 117
25c269ef 118(defcustom calculator-remove-zeros t
9201cc28 119 "Non-nil value means delete all redundant zero decimal digits.
25c269ef
DL
120If this value is not t, and not nil, redundant zeros are removed except
121for one and if it is nil, nothing is removed.
122Used by the `calculator-remove-zeros' function."
123 :type '(choice (const t) (const leave-decimal) (const nil))
d240a249
GM
124 :group 'calculator)
125
25c269ef 126(defcustom calculator-displayer '(std ?n)
9201cc28 127 "A displayer specification for numerical values.
25c269ef
DL
128This is the displayer used to show all numbers in an expression. Result
129values will be displayed according to the first element of
130`calculator-displayers'.
131
132The displayer is a symbol, a string or an expression. A symbol should
133be the name of a one-argument function, a string is used with a single
134argument and an expression will be evaluated with the variable `num'
135bound to whatever should be displayed. If it is a function symbol, it
136should be able to handle special symbol arguments, currently 'left and
137'right which will be sent by special keys to modify display parameters
138associated with the displayer function (for example to change the number
139of digits displayed).
140
141An exception to the above is the case of the list (std C) where C is a
142character, in this case the `calculator-standard-displayer' function
f5307782
JB
143will be used with this character for a format string."
144 :group 'calculator)
25c269ef
DL
145
146(defcustom calculator-displayers
2188f2d4 147 '(((std ?n) "Standard display, decimal point or scientific")
25c269ef
DL
148 (calculator-eng-display "Eng display")
149 ((std ?f) "Standard display, decimal point")
2188f2d4 150 ((std ?e) "Standard display, scientific")
25c269ef 151 ("%S" "Emacs printer"))
9201cc28 152 "A list of displayers.
25c269ef 153Each element is a list of a displayer and a description string. The
2188f2d4 154first element is the one which is currently used, this is for the display
25c269ef
DL
155of result values not values in expressions. A displayer specification
156is the same as the values that can be stored in `calculator-displayer'.
157
158`calculator-rotate-displayer' rotates this list."
159 :type 'sexp
d240a249
GM
160 :group 'calculator)
161
25c269ef 162(defcustom calculator-paste-decimals t
9201cc28 163 "If non-nil, convert pasted integers so they have a decimal point.
25c269ef
DL
164This makes it possible to paste big integers since they will be read as
165floats, otherwise the Emacs reader will fail on them."
d240a249
GM
166 :type 'boolean
167 :group 'calculator)
168
4351784f 169(defcustom calculator-copy-displayer nil
9201cc28 170 "If non-nil, this is any value that can be used for
4351784f
GM
171`calculator-displayer', to format a string before copying it with
172`calculator-copy'. If nil, then `calculator-displayer's normal value is
f5307782
JB
173used."
174 :type 'boolean
175 :group 'calculator)
4351784f 176
d240a249 177(defcustom calculator-2s-complement nil
9201cc28 178 "If non-nil, show negative numbers in 2s complement in radix modes.
d240a249
GM
179Otherwise show as a negative number."
180 :type 'boolean
181 :group 'calculator)
182
183(defcustom calculator-mode-hook nil
9201cc28 184 "List of hook functions for `calculator-mode' to run.
761d3eb3
RS
185Note: if `calculator-electric-mode' is on, then this hook will get
186activated in the minibuffer - in that case it should not do much more
187than local key settings and other effects that will change things
188outside the scope of calculator related code."
d240a249
GM
189 :type 'hook
190 :group 'calculator)
191
192(defcustom calculator-user-registers nil
9201cc28 193 "An association list of user-defined register bindings.
d240a249
GM
194Each element in this list is a list of a character and a number that
195will be stored in that character's register.
196
197For example, use this to define the golden ratio number:
25c269ef
DL
198 (setq calculator-user-registers '((?g . 1.61803398875)))
199before you load calculator."
d240a249 200 :type '(repeat (cons character number))
4f91a816
SM
201 :set (lambda (_ val)
202 (and (boundp 'calculator-registers)
203 (setq calculator-registers
204 (append val calculator-registers)))
205 (setq calculator-user-registers val))
d240a249
GM
206 :group 'calculator)
207
208(defcustom calculator-user-operators nil
9201cc28 209 "A list of additional operators.
d240a249
GM
210This is a list in the same format as specified in the documentation for
211`calculator-operators', that you can use to bind additional calculator
212operators. It is probably not a good idea to modify this value with
213`customize' since it is too complex...
214
215Examples:
216
7def2f92
DL
217* A very simple one, adding a postfix \"x-to-y\" conversion keys, using
218 t as a prefix key:
d240a249
GM
219
220 (setq calculator-user-operators
221 '((\"tf\" cl-to-fr (+ 32 (/ (* X 9) 5)) 1)
222 (\"tc\" fr-to-cl (/ (* (- X 32) 5) 9) 1)
223 (\"tp\" kg-to-lb (/ X 0.453592) 1)
224 (\"tk\" lb-to-kg (* X 0.453592) 1)
225 (\"tF\" mt-to-ft (/ X 0.3048) 1)
226 (\"tM\" ft-to-mt (* X 0.3048) 1)))
227
228* Using a function-like form is very simple, X for an argument (Y the
229 second in case of a binary operator), TX is a truncated version of X
230 and F does a recursive call, Here is a [very inefficient] Fibonacci
231 number calculation:
232
233 (add-to-list 'calculator-user-operators
234 '(\"F\" fib (if (<= TX 1)
25c269ef
DL
235 1
236 (+ (F (- TX 1)) (F (- TX 2)))) 0))
d240a249
GM
237
238 Note that this will be either postfix or prefix, according to
239 `calculator-unary-style'."
240 :type '(repeat (list string symbol sexp integer integer))
241 :group 'calculator)
242
cbb2dddb 243;;;=====================================================================
d240a249
GM
244;;; Code:
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
25c269ef
DL
673(eval-when-compile (require 'electric) (require 'ehelp))
674
d240a249
GM
675;;;###autoload
676(defun calculator ()
25c269ef 677 "Run the Emacs calculator.
d240a249
GM
678See the documentation for `calculator-mode' for more information."
679 (interactive)
86f1e1ec
GM
680 (if calculator-restart-other-mode
681 (setq calculator-electric-mode (not calculator-electric-mode)))
d240a249
GM
682 (if calculator-initial-operators
683 (progn (calculator-add-operators calculator-initial-operators)
684 (setq calculator-initial-operators nil)
685 ;; don't change this since it is a customization variable,
25c269ef 686 ;; its set function will add any new operators
d240a249 687 (calculator-add-operators calculator-user-operators)))
cc234da9 688 (setq calculator-buffer (get-buffer-create "*calculator*"))
d240a249
GM
689 (if calculator-electric-mode
690 (save-window-excursion
86f1e1ec 691 (progn (require 'electric) (message nil)) ; hide load message
d240a249
GM
692 (let (old-g-map old-l-map (echo-keystrokes 0)
693 (garbage-collection-messages nil)) ; no gc msg when electric
cc234da9 694 (set-window-buffer (minibuffer-window) calculator-buffer)
d240a249
GM
695 (select-window (minibuffer-window))
696 (calculator-reset)
697 (calculator-update-display)
698 (setq old-l-map (current-local-map))
699 (setq old-g-map (current-global-map))
700 (setq calculator-saved-global-map (current-global-map))
86f1e1ec 701 (use-local-map nil)
d240a249 702 (use-global-map calculator-mode-map)
761d3eb3 703 (run-hooks 'calculator-mode-hook)
d240a249
GM
704 (unwind-protect
705 (catch 'calculator-done
706 (Electric-command-loop
707 'calculator-done
708 ;; can't use 'noprompt, bug in electric.el
4f91a816 709 (lambda () 'noprompt)
d240a249 710 nil
86f1e1ec 711 (lambda (x y) (calculator-update-display))))
d240a249
GM
712 (and calculator-buffer
713 (catch 'calculator-done (calculator-quit)))
714 (use-local-map old-l-map)
715 (use-global-map old-g-map))))
86f1e1ec 716 (progn
4351784f
GM
717 (cond
718 ((not (get-buffer-window calculator-buffer))
a4e32226 719 (let ((window-min-height 2))
4351784f
GM
720 ;; maybe leave two lines for our window because of the normal
721 ;; `raised' modeline in Emacs 21
722 (select-window
723 (split-window-vertically
a45928e6 724 ;; If the modeline might interfere with the calculator buffer,
bd9bb96e 725 ;; use 3 lines instead.
4351784f 726 (if (and (fboundp 'face-attr-construct)
0098d2be
JB
727 (let* ((dh (plist-get (face-attr-construct 'default) :height))
728 (mf (face-attr-construct 'modeline))
729 (mh (plist-get mf :height)))
bd9bb96e
JB
730 ;; If the modeline is shorter than the default,
731 ;; stick with 2 lines. (It may be necessary to
0098d2be
JB
732 ;; check how much shorter.)
733 (and
734 (not
735 (or (and (integerp dh)
736 (integerp mh)
737 (< mh dh))
738 (and (numberp mh)
739 (not (integerp mh))
740 (< mh 1))))
741 (or
742 ;; If the modeline is taller than the default,
743 ;; use 3 lines.
744 (and (integerp dh)
745 (integerp mh)
746 (> mh dh))
747 (and (numberp mh)
748 (not (integerp mh))
749 (> mh 1))
750 ;; If the modeline has a box with non-negative line-width,
751 ;; use 3 lines.
752 (let* ((bx (plist-get mf :box))
753 (lh (plist-get bx :line-width)))
754 (and bx
bd9bb96e 755 (or
0098d2be
JB
756 (not lh)
757 (> lh 0))))
758 ;; If the modeline has an overline, use 3 lines.
759 (plist-get (face-attr-construct 'modeline) :overline)))))
4351784f
GM
760 -3 -2)))
761 (switch-to-buffer calculator-buffer)))
762 ((not (eq (current-buffer) calculator-buffer))
763 (select-window (get-buffer-window calculator-buffer))))
86f1e1ec
GM
764 (calculator-mode)
765 (setq buffer-read-only t)
766 (calculator-reset)
767 (message "Hit `?' For a quick help screen.")))
768 (if (and calculator-restart-other-mode calculator-electric-mode)
769 (calculator)))
d240a249 770
761d3eb3
RS
771(defun calculator-message (string &rest arguments)
772 "Same as `message', but special handle of electric mode."
773 (apply 'message string arguments)
774 (if calculator-electric-mode
775 (progn (sit-for 1) (message nil))))
776
cbb2dddb 777;;;---------------------------------------------------------------------
2188f2d4 778;;; Operators
25c269ef 779
d240a249
GM
780(defun calculator-op-arity (op)
781 "Return OP's arity, 2, +1 or -1."
782 (let ((arity (or (nth 3 op) 'x)))
783 (if (numberp arity)
784 arity
785 (if (eq calculator-unary-style 'postfix) +1 -1))))
786
787(defun calculator-op-prec (op)
788 "Return OP's precedence for reducing when inserting into the stack.
789Defaults to 1."
790 (or (nth 4 op) 1))
791
792(defun calculator-add-operators (more-ops)
793 "This function handles operator addition.
794Adds MORE-OPS to `calculator-operator', called initially to handle
795`calculator-initial-operators' and `calculator-user-operators'."
796 (let ((added-ops nil))
797 (while more-ops
798 (or (eq (car (car more-ops)) 'nobind)
799 (let ((i -1) (key (car (car more-ops))))
800 ;; make sure the key is undefined, so it's easy to define
801 ;; prefix keys
802 (while (< (setq i (1+ i)) (length key))
803 (or (keymapp
804 (lookup-key calculator-mode-map
805 (substring key 0 (1+ i))))
806 (progn
807 (define-key
808 calculator-mode-map (substring key 0 (1+ i)) nil)
809 (setq i (length key)))))
810 (define-key calculator-mode-map key 'calculator-op)))
811 (setq added-ops (cons (if (eq (car (car more-ops)) 'nobind)
812 (cdr (car more-ops))
813 (car more-ops))
814 added-ops))
815 (setq more-ops (cdr more-ops)))
816 ;; added-ops come first, but in correct order
817 (setq calculator-operators
818 (append (nreverse added-ops) calculator-operators))))
819
cbb2dddb 820;;;---------------------------------------------------------------------
25c269ef
DL
821;;; Display stuff
822
d240a249
GM
823(defun calculator-reset ()
824 "Reset calculator variables."
86f1e1ec
GM
825 (or calculator-restart-other-mode
826 (setq calculator-stack nil
827 calculator-curnum nil
828 calculator-stack-display nil
829 calculator-display-fragile nil))
830 (setq calculator-restart-other-mode nil)
d240a249
GM
831 (calculator-update-display))
832
833(defun calculator-get-prompt ()
834 "Return a string to display.
835The string is set not to exceed the screen width."
836 (let* ((calculator-prompt
837 (format calculator-prompt
838 (cond
839 ((or calculator-output-radix calculator-input-radix)
840 (if (eq calculator-output-radix
841 calculator-input-radix)
842 (concat
843 (char-to-string
844 (car (rassq calculator-output-radix
845 calculator-char-radix)))
846 "=")
847 (concat
848 (if calculator-input-radix
849 (char-to-string
850 (car (rassq calculator-input-radix
851 calculator-char-radix)))
852 "=")
853 (char-to-string
854 (car (rassq calculator-output-radix
855 calculator-char-radix))))))
856 (calculator-deg "D=")
857 (t "=="))))
858 (prompt
859 (concat calculator-prompt
860 (cdr calculator-stack-display)
861 (cond (calculator-curnum
862 ;; number being typed
863 (concat calculator-curnum "_"))
864 ((and (= 1 (length calculator-stack))
865 calculator-display-fragile)
866 ;; only the result is shown, next number will
867 ;; restart
868 nil)
869 (t
870 ;; waiting for a number or an operator
871 "?"))))
872 (trim (- (length prompt) (1- (window-width)))))
873 (if (<= trim 0)
874 prompt
875 (concat calculator-prompt
876 (substring prompt (+ trim (length calculator-prompt)))))))
877
761d3eb3
RS
878(defun calculator-string-to-number (str)
879 "Convert the given STR to a number, according to the value of
880`calculator-input-radix'."
d240a249
GM
881 (if calculator-input-radix
882 (let ((radix
883 (cdr (assq calculator-input-radix
884 '((bin . 2) (oct . 8) (hex . 16)))))
761d3eb3
RS
885 (i -1) (value 0) (new-value 0))
886 ;; assume mostly valid input (e.g., characters in range)
887 (while (< (setq i (1+ i)) (length str))
888 (setq new-value
889 (let* ((ch (upcase (aref str i)))
890 (n (cond ((< ch ?0) nil)
891 ((<= ch ?9) (- ch ?0))
892 ((< ch ?A) nil)
893 ((<= ch ?Z) (- ch (- ?A 10)))
894 (t nil))))
895 (if (and n (<= 0 n) (< n radix))
896 (+ n (* radix value))
897 (progn
898 (calculator-message
899 "Warning: Ignoring bad input character `%c'." ch)
900 (sit-for 1)
901 value))))
902 (if (if (< new-value 0) (> value 0) (< value 0))
903 (calculator-message "Warning: Overflow in input."))
904 (setq value new-value))
d240a249 905 value)
761d3eb3
RS
906 (car (read-from-string
907 (cond ((equal "." str) "0.0")
908 ((string-match "[eE][+-]?$" str) (concat str "0"))
909 ((string-match "\\.[0-9]\\|[eE]" str) str)
910 ((string-match "\\." str)
911 ;; do this because Emacs reads "23." as an integer
912 (concat str "0"))
913 ((stringp str) (concat str ".0"))
914 (t "0.0"))))))
915
916(defun calculator-curnum-value ()
917 "Get the numeric value of the displayed number string as a float."
918 (calculator-string-to-number calculator-curnum))
d240a249 919
25c269ef
DL
920(defun calculator-rotate-displayer (&optional new-disp)
921 "Switch to the next displayer on the `calculator-displayers' list.
922Can be called with an optional argument NEW-DISP to force rotation to
761d3eb3
RS
923that argument.
924If radix output mode is active, toggle digit grouping."
25c269ef 925 (interactive)
761d3eb3
RS
926 (cond
927 (calculator-output-radix
928 (setq calculator-radix-grouping-mode
929 (not calculator-radix-grouping-mode))
930 (calculator-message
931 "Digit grouping mode %s."
932 (if calculator-radix-grouping-mode "ON" "OFF")))
933 (t
934 (setq calculator-displayers
935 (if (and new-disp (memq new-disp calculator-displayers))
936 (let ((tmp nil))
937 (while (not (eq (car calculator-displayers) new-disp))
938 (setq tmp (cons (car calculator-displayers) tmp))
939 (setq calculator-displayers
940 (cdr calculator-displayers)))
941 (setq calculator-displayers
942 (nconc calculator-displayers (nreverse tmp))))
943 (nconc (cdr calculator-displayers)
944 (list (car calculator-displayers)))))
945 (calculator-message
946 "Using %s." (cadr (car calculator-displayers)))))
25c269ef
DL
947 (calculator-enter))
948
949(defun calculator-rotate-displayer-back ()
761d3eb3
RS
950 "Like `calculator-rotate-displayer', but rotates modes back.
951If radix output mode is active, toggle digit grouping."
25c269ef
DL
952 (interactive)
953 (calculator-rotate-displayer (car (last calculator-displayers))))
954
4351784f 955(defun calculator-displayer-prev ()
25c269ef
DL
956 "Send the current displayer function a 'left argument.
957This is used to modify display arguments (if the current displayer
761d3eb3
RS
958function supports this).
959If radix output mode is active, increase the grouping size."
25c269ef 960 (interactive)
761d3eb3
RS
961 (if calculator-output-radix
962 (progn (setq calculator-radix-grouping-digits
963 (1+ calculator-radix-grouping-digits))
964 (calculator-enter))
965 (and (car calculator-displayers)
966 (let ((disp (caar calculator-displayers)))
967 (cond
968 ((symbolp disp) (funcall disp 'left))
969 ((and (consp disp) (eq 'std (car disp)))
970 (calculator-standard-displayer 'left (cadr disp))))))))
25c269ef 971
4351784f 972(defun calculator-displayer-next ()
25c269ef
DL
973 "Send the current displayer function a 'right argument.
974This is used to modify display arguments (if the current displayer
761d3eb3
RS
975function supports this).
976If radix output mode is active, decrease the grouping size."
25c269ef 977 (interactive)
761d3eb3
RS
978 (if calculator-output-radix
979 (progn (setq calculator-radix-grouping-digits
980 (max 2 (1- calculator-radix-grouping-digits)))
981 (calculator-enter))
982 (and (car calculator-displayers)
983 (let ((disp (caar calculator-displayers)))
984 (cond
985 ((symbolp disp) (funcall disp 'right))
986 ((and (consp disp) (eq 'std (car disp)))
987 (calculator-standard-displayer 'right (cadr disp))))))))
25c269ef
DL
988
989(defun calculator-remove-zeros (numstr)
a1ff7705
JB
990 "Get a number string NUMSTR and remove unnecessary zeros.
991The behavior of this function is controlled by
25c269ef
DL
992`calculator-remove-zeros'."
993 (cond ((and (eq calculator-remove-zeros t)
994 (string-match "\\.0+\\([eE][+-]?[0-9]*\\)?$" numstr))
995 ;; remove all redundant zeros leaving an integer
996 (if (match-beginning 1)
997 (concat (substring numstr 0 (match-beginning 0))
998 (match-string 1 numstr))
999 (substring numstr 0 (match-beginning 0))))
1000 ((and calculator-remove-zeros
1001 (string-match
1002 "\\..\\([0-9]*[1-9]\\)?\\(0+\\)\\([eE][+-]?[0-9]*\\)?$"
1003 numstr))
1004 ;; remove zeros, except for first after the "."
1005 (if (match-beginning 3)
1006 (concat (substring numstr 0 (match-beginning 2))
1007 (match-string 3 numstr))
1008 (substring numstr 0 (match-beginning 2))))
1009 (t numstr)))
1010
1011(defun calculator-standard-displayer (num char)
1012 "Standard display function, used to display NUM.
1013Its behavior is determined by `calculator-number-digits' and the given
1014CHAR argument (both will be used to compose a format string). If the
1015char is \"n\" then this function will choose one between %f or %e, this
1016is a work around %g jumping to exponential notation too fast.
1017
1018The special 'left and 'right symbols will make it change the current
1019number of digits displayed (`calculator-number-digits').
1020
1021It will also remove redundant zeros from the result."
1022 (if (symbolp num)
1023 (cond ((eq num 'left)
1024 (and (> calculator-number-digits 0)
1025 (setq calculator-number-digits
1026 (1- calculator-number-digits))
1027 (calculator-enter)))
1028 ((eq num 'right)
1029 (setq calculator-number-digits
1030 (1+ calculator-number-digits))
1031 (calculator-enter)))
4351784f
GM
1032 (let ((str (if (zerop num)
1033 "0"
1034 (format
1035 (concat "%."
1036 (number-to-string calculator-number-digits)
1037 (if (eq char ?n)
1038 (let ((n (abs num)))
1039 (if (or (< n 0.001) (> n 1e8)) "e" "f"))
1040 (string char)))
1041 num))))
25c269ef
DL
1042 (calculator-remove-zeros str))))
1043
1044(defun calculator-eng-display (num)
1045 "Display NUM in engineering notation.
1046The number of decimal digits used is controlled by
1047`calculator-number-digits', so to change it at runtime you have to use
1048the 'left or 'right when one of the standard modes is used."
1049 (if (symbolp num)
1050 (cond ((eq num 'left)
1051 (setq calculator-eng-extra
1052 (if calculator-eng-extra
1053 (1+ calculator-eng-extra)
1054 1))
1055 (let ((calculator-eng-tmp-show t)) (calculator-enter)))
1056 ((eq num 'right)
1057 (setq calculator-eng-extra
1058 (if calculator-eng-extra
1059 (1- calculator-eng-extra)
1060 -1))
1061 (let ((calculator-eng-tmp-show t)) (calculator-enter))))
1062 (let ((exp 0))
1063 (and (not (= 0 num))
1064 (progn
1065 (while (< (abs num) 1.0)
1066 (setq num (* num 1000.0)) (setq exp (- exp 3)))
1067 (while (> (abs num) 999.0)
1068 (setq num (/ num 1000.0)) (setq exp (+ exp 3)))
1069 (and calculator-eng-tmp-show
1070 (not (= 0 calculator-eng-extra))
1071 (let ((i calculator-eng-extra))
1072 (while (> i 0)
1073 (setq num (* num 1000.0)) (setq exp (- exp 3))
1074 (setq i (1- i)))
1075 (while (< i 0)
1076 (setq num (/ num 1000.0)) (setq exp (+ exp 3))
1077 (setq i (1+ i)))))))
1078 (or calculator-eng-tmp-show (setq calculator-eng-extra nil))
6ac080e1
GM
1079 (let ((str (format (concat "%." (number-to-string
1080 calculator-number-digits)
1081 "f")
25c269ef
DL
1082 num)))
1083 (concat (let ((calculator-remove-zeros
1084 ;; make sure we don't leave integers
1085 (and calculator-remove-zeros 'x)))
1086 (calculator-remove-zeros str))
1087 "e" (number-to-string exp))))))
1088
761d3eb3 1089(defun calculator-number-to-string (num)
d240a249
GM
1090 "Convert NUM to a displayable string."
1091 (cond
1092 ((and (numberp num) calculator-output-radix)
1093 ;; print with radix - for binary I convert the octal number
1094 (let ((str (format (if (eq calculator-output-radix 'hex) "%x" "%o")
1095 (calculator-truncate
1096 (if calculator-2s-complement num (abs num))))))
1097 (if (eq calculator-output-radix 'bin)
1098 (let ((i -1) (s ""))
1099 (while (< (setq i (1+ i)) (length str))
1100 (setq s
1101 (concat s
1102 (cdr (assq (aref str i)
1103 '((?0 . "000") (?1 . "001")
1104 (?2 . "010") (?3 . "011")
1105 (?4 . "100") (?5 . "101")
1106 (?6 . "110") (?7 . "111")))))))
1107 (string-match "^0*\\(.+\\)" s)
1108 (setq str (match-string 1 s))))
761d3eb3
RS
1109 (if calculator-radix-grouping-mode
1110 (let ((d (/ (length str) calculator-radix-grouping-digits))
1111 (r (% (length str) calculator-radix-grouping-digits)))
1112 (while (>= (setq d (1- d)) (if (zerop r) 1 0))
1113 (let ((i (+ r (* d calculator-radix-grouping-digits))))
1114 (setq str (concat (substring str 0 i)
1115 calculator-radix-grouping-separator
1116 (substring str i)))))))
d240a249
GM
1117 (upcase
1118 (if (and (not calculator-2s-complement) (< num 0))
1119 (concat "-" str)
1120 str))))
4351784f
GM
1121 ((and (numberp num) calculator-displayer)
1122 (cond
1123 ((stringp calculator-displayer)
1124 (format calculator-displayer num))
1125 ((symbolp calculator-displayer)
1126 (funcall calculator-displayer num))
1127 ((and (consp calculator-displayer)
1128 (eq 'std (car calculator-displayer)))
1129 (calculator-standard-displayer num (cadr calculator-displayer)))
1130 ((listp calculator-displayer)
1131 (eval calculator-displayer))
1132 (t (prin1-to-string num t))))
25c269ef 1133 ;; operators are printed here
d240a249
GM
1134 (t (prin1-to-string (nth 1 num) t))))
1135
1136(defun calculator-update-display (&optional force)
1137 "Update the display.
1138If optional argument FORCE is non-nil, don't use the cached string."
1139 (set-buffer calculator-buffer)
1140 ;; update calculator-stack-display
1141 (if (or force
1142 (not (eq (car calculator-stack-display) calculator-stack)))
1143 (setq calculator-stack-display
1144 (cons calculator-stack
1145 (if calculator-stack
1146 (concat
4351784f
GM
1147 (let ((calculator-displayer
1148 (if (and calculator-displayers
1149 (= 1 (length calculator-stack)))
1150 ;; customizable display for a single value
1151 (caar calculator-displayers)
1152 calculator-displayer)))
761d3eb3 1153 (mapconcat 'calculator-number-to-string
4351784f
GM
1154 (reverse calculator-stack)
1155 " "))
d240a249
GM
1156 " "
1157 (and calculator-display-fragile
1158 calculator-saved-list
1159 (= (car calculator-stack)
1160 (nth calculator-saved-ptr
1161 calculator-saved-list))
1162 (if (= 0 calculator-saved-ptr)
1163 (format "[%s]" (length calculator-saved-list))
1164 (format "[%s/%s]"
1165 (- (length calculator-saved-list)
1166 calculator-saved-ptr)
1167 (length calculator-saved-list)))))
1168 ""))))
1169 (let ((inhibit-read-only t))
1170 (erase-buffer)
1171 (insert (calculator-get-prompt)))
1172 (set-buffer-modified-p nil)
1173 (if calculator-display-fragile
1174 (goto-char (1+ (length calculator-prompt)))
1175 (goto-char (1- (point)))))
1176
cbb2dddb 1177;;;---------------------------------------------------------------------
25c269ef
DL
1178;;; Stack computations
1179
d240a249
GM
1180(defun calculator-reduce-stack (prec)
1181 "Reduce the stack using top operator.
1182PREC is a precedence - reduce everything with higher precedence."
1183 (while
1184 (cond
1185 ((and (cdr (cdr calculator-stack)) ; have three values
1186 (consp (nth 0 calculator-stack)) ; two operators & num
1187 (numberp (nth 1 calculator-stack))
1188 (consp (nth 2 calculator-stack))
1189 (eq '\) (nth 1 (nth 0 calculator-stack)))
1190 (eq '\( (nth 1 (nth 2 calculator-stack))))
1191 ;; reduce "... ( x )" --> "... x"
1192 (setq calculator-stack
1193 (cons (nth 1 calculator-stack)
1194 (nthcdr 3 calculator-stack)))
1195 ;; another iteration
1196 t)
1197 ((and (cdr (cdr calculator-stack)) ; have three values
1198 (numberp (nth 0 calculator-stack)) ; two nums & operator
1199 (consp (nth 1 calculator-stack))
1200 (numberp (nth 2 calculator-stack))
1201 (= 2 (calculator-op-arity ; binary operator
1202 (nth 1 calculator-stack)))
1203 (<= prec ; with higher prec.
1204 (calculator-op-prec (nth 1 calculator-stack))))
1205 ;; reduce "... x op y" --> "... r", r is the result
1206 (setq calculator-stack
1207 (cons (calculator-funcall
1208 (nth 2 (nth 1 calculator-stack))
1209 (nth 2 calculator-stack)
1210 (nth 0 calculator-stack))
1211 (nthcdr 3 calculator-stack)))
1212 ;; another iteration
1213 t)
1214 ((and (>= (length calculator-stack) 2) ; have two values
1215 (numberp (nth 0 calculator-stack)) ; number & operator
1216 (consp (nth 1 calculator-stack))
1217 (= -1 (calculator-op-arity ; prefix-unary op
1218 (nth 1 calculator-stack)))
1219 (<= prec ; with higher prec.
1220 (calculator-op-prec (nth 1 calculator-stack))))
1221 ;; reduce "... op x" --> "... r" for prefix op
1222 (setq calculator-stack
1223 (cons (calculator-funcall
1224 (nth 2 (nth 1 calculator-stack))
1225 (nth 0 calculator-stack))
1226 (nthcdr 2 calculator-stack)))
1227 ;; another iteration
1228 t)
1229 ((and (cdr calculator-stack) ; have two values
1230 (consp (nth 0 calculator-stack)) ; operator & number
1231 (numberp (nth 1 calculator-stack))
1232 (= +1 (calculator-op-arity ; postfix-unary op
1233 (nth 0 calculator-stack)))
1234 (<= prec ; with higher prec.
1235 (calculator-op-prec (nth 0 calculator-stack))))
1236 ;; reduce "... x op" --> "... r" for postfix op
1237 (setq calculator-stack
1238 (cons (calculator-funcall
1239 (nth 2 (nth 0 calculator-stack))
1240 (nth 1 calculator-stack))
1241 (nthcdr 2 calculator-stack)))
1242 ;; another iteration
1243 t)
1244 ((and calculator-stack ; have one value
1245 (consp (nth 0 calculator-stack)) ; an operator
1246 (= 0 (calculator-op-arity ; 0-ary op
1247 (nth 0 calculator-stack))))
1248 ;; reduce "... op" --> "... r" for 0-ary op
1249 (setq calculator-stack
1250 (cons (calculator-funcall
1251 (nth 2 (nth 0 calculator-stack)))
1252 (nthcdr 1 calculator-stack)))
1253 ;; another iteration
1254 t)
1255 ((and (cdr calculator-stack) ; have two values
1256 (numberp (nth 0 calculator-stack)) ; both numbers
1257 (numberp (nth 1 calculator-stack)))
1258 ;; get rid of redundant numbers:
1259 ;; reduce "... y x" --> "... x"
1260 ;; needed for 0-ary ops that puts more values
1261 (setcdr calculator-stack (cdr (cdr calculator-stack))))
1262 (t ;; no more iterations
1263 nil))))
1264
25c269ef
DL
1265(defun calculator-funcall (f &optional X Y)
1266 "If F is a symbol, evaluate (F X Y).
1267Otherwise, it should be a list, evaluate it with X, Y bound to the
1268arguments."
1269 ;; remember binary ops for calculator-repR/L
1270 (if Y (setq calculator-last-opXY (list f X Y)))
1271 (condition-case nil
1272 ;; there used to be code here that returns 0 if the result was
1273 ;; smaller than calculator-epsilon (1e-15). I don't think this is
1274 ;; necessary now.
1275 (if (symbolp f)
1276 (cond ((and X Y) (funcall f X Y))
1277 (X (funcall f X))
1278 (t (funcall f)))
1279 ;; f is an expression
1280 (let* ((__f__ f) ; so we can get this value below...
1281 (TX (calculator-truncate X))
1282 (TY (and Y (calculator-truncate Y)))
1283 (DX (if calculator-deg (/ (* X pi) 180) X))
1284 (L calculator-saved-list)
1285 (Fbound (fboundp 'F))
1286 (Fsave (and Fbound (symbol-function 'F)))
1287 (Dbound (fboundp 'D))
1288 (Dsave (and Dbound (symbol-function 'D))))
1289 ;; a shortened version of flet
1290 (fset 'F (function
1291 (lambda (&optional x y)
1292 (calculator-funcall __f__ x y))))
1293 (fset 'D (function
1294 (lambda (x)
9e0d4f9e 1295 (if calculator-deg (/ (* x 180) float-pi) x))))
25c269ef
DL
1296 (unwind-protect (eval f)
1297 (if Fbound (fset 'F Fsave) (fmakunbound 'F))
1298 (if Dbound (fset 'D Dsave) (fmakunbound 'D)))))
1299 (error 0)))
1300
cbb2dddb 1301;;;---------------------------------------------------------------------
25c269ef
DL
1302;;; Input interaction
1303
86f1e1ec
GM
1304(defun calculator-last-input (&optional keys)
1305 "Last char (or event or event sequence) that was read.
1306Optional string argument KEYS will force using it as the keys entered."
1307 (let ((inp (or keys (this-command-keys))))
d240a249
GM
1308 (if (or (stringp inp) (not (arrayp inp)))
1309 inp
1310 ;; this translates kp-x to x and [tries to] create a string to
1311 ;; lookup operators
1312 (let* ((i -1) (converted-str (make-string (length inp) ? )) k)
1313 ;; converts an array to a string the ops lookup with keypad
1314 ;; input
1315 (while (< (setq i (1+ i)) (length inp))
1316 (setq k (aref inp i))
1317 ;; if Emacs will someday have a event-key, then this would
1318 ;; probably be modified anyway
d88757d6
RS
1319 (and (if (fboundp 'key-press-event-p) (key-press-event-p k))
1320 (if (fboundp 'event-key)
1321 (and (event-key k) (setq k (event-key k)))))
d240a249
GM
1322 ;; assume all symbols are translatable with an ascii-character
1323 (and (symbolp k)
1324 (setq k (or (get k 'ascii-character) ? )))
1325 (aset converted-str i k))
1326 converted-str))))
1327
1328(defun calculator-clear-fragile (&optional op)
1329 "Clear the fragile flag if it was set, then maybe reset all.
1330OP is the operator (if any) that caused this call."
1331 (if (and calculator-display-fragile
1332 (or (not op)
1333 (= -1 (calculator-op-arity op))
1334 (= 0 (calculator-op-arity op))))
1335 ;; reset if last calc finished, and now get a num or prefix or 0-ary
25c269ef 1336 ;; op
d240a249
GM
1337 (calculator-reset))
1338 (setq calculator-display-fragile nil))
1339
1340(defun calculator-digit ()
1341 "Enter a single digit."
1342 (interactive)
1343 (let ((inp (aref (calculator-last-input) 0)))
1344 (if (and (or calculator-display-fragile
1345 (not (numberp (car calculator-stack))))
1346 (cond
1347 ((not calculator-input-radix) (<= inp ?9))
1348 ((eq calculator-input-radix 'bin) (<= inp ?1))
1349 ((eq calculator-input-radix 'oct) (<= inp ?7))
1350 (t t)))
1351 ;; enter digit if starting a new computation or have an op on the
25c269ef 1352 ;; stack
d240a249
GM
1353 (progn
1354 (calculator-clear-fragile)
1355 (let ((digit (upcase (char-to-string inp))))
1356 (if (equal calculator-curnum "0")
1357 (setq calculator-curnum nil))
1358 (setq calculator-curnum
1359 (concat (or calculator-curnum "") digit)))
1360 (calculator-update-display)))))
1361
1362(defun calculator-decimal ()
1363 "Enter a decimal period."
1364 (interactive)
1365 (if (and (not calculator-input-radix)
1366 (or calculator-display-fragile
1367 (not (numberp (car calculator-stack))))
1368 (not (and calculator-curnum
1369 (string-match "[.eE]" calculator-curnum))))
1370 ;; enter the period on the same condition as a digit, only if no
25c269ef 1371 ;; period or exponent entered yet
d240a249
GM
1372 (progn
1373 (calculator-clear-fragile)
1374 (setq calculator-curnum (concat (or calculator-curnum "0") "."))
1375 (calculator-update-display))))
1376
1377(defun calculator-exp ()
1378 "Enter an `E' exponent character, or a digit in hex input mode."
1379 (interactive)
1380 (if calculator-input-radix
1381 (calculator-digit)
1382 (if (and (or calculator-display-fragile
1383 (not (numberp (car calculator-stack))))
1384 (not (and calculator-curnum
1385 (string-match "[eE]" calculator-curnum))))
25c269ef 1386 ;; same condition as above, also no E so far
d240a249
GM
1387 (progn
1388 (calculator-clear-fragile)
1389 (setq calculator-curnum (concat (or calculator-curnum "1") "e"))
1390 (calculator-update-display)))))
1391
86f1e1ec
GM
1392(defun calculator-op (&optional keys)
1393 "Enter an operator on the stack, doing all necessary reductions.
1394Optional string argument KEYS will force using it as the keys entered."
d240a249 1395 (interactive)
25c269ef
DL
1396 (catch 'op-error
1397 (let* ((last-inp (calculator-last-input keys))
1398 (op (assoc last-inp calculator-operators)))
1399 (calculator-clear-fragile op)
1400 (if (and calculator-curnum (/= (calculator-op-arity op) 0))
1401 (setq calculator-stack
1402 (cons (calculator-curnum-value) calculator-stack)))
1403 (setq calculator-curnum nil)
1404 (if (and (= 2 (calculator-op-arity op))
1405 (not (and calculator-stack
1406 (numberp (nth 0 calculator-stack)))))
1407 ;; we have a binary operator but no number - search for a prefix
1408 ;; version
1409 (let ((rest-ops calculator-operators))
1410 (while (not (equal last-inp (car (car rest-ops))))
1411 (setq rest-ops (cdr rest-ops)))
1412 (setq op (assoc last-inp (cdr rest-ops)))
1413 (if (not (and op (= -1 (calculator-op-arity op))))
1414 ;;(error "Binary operator without a first operand")
1415 (progn
761d3eb3
RS
1416 (calculator-message
1417 "Binary operator without a first operand")
25c269ef
DL
1418 (throw 'op-error nil)))))
1419 (calculator-reduce-stack
1420 (cond ((eq (nth 1 op) '\() 10)
1421 ((eq (nth 1 op) '\)) 0)
1422 (t (calculator-op-prec op))))
1423 (if (or (and (= -1 (calculator-op-arity op))
1424 (numberp (car calculator-stack)))
1425 (and (/= (calculator-op-arity op) -1)
1426 (/= (calculator-op-arity op) 0)
1427 (not (numberp (car calculator-stack)))))
1428 ;;(error "Unterminated expression")
1429 (progn
761d3eb3 1430 (calculator-message "Unterminated expression")
25c269ef
DL
1431 (throw 'op-error nil)))
1432 (setq calculator-stack (cons op calculator-stack))
1433 (calculator-reduce-stack (calculator-op-prec op))
1434 (and (= (length calculator-stack) 1)
1435 (numberp (nth 0 calculator-stack))
1436 ;; the display is fragile if it contains only one number
1437 (setq calculator-display-fragile t)
1438 ;; add number to the saved-list
1439 calculator-add-saved
1440 (if (= 0 calculator-saved-ptr)
1441 (setq calculator-saved-list
1442 (cons (car calculator-stack) calculator-saved-list))
1443 (let ((p (nthcdr (1- calculator-saved-ptr)
1444 calculator-saved-list)))
1445 (setcdr p (cons (car calculator-stack) (cdr p))))))
1446 (calculator-update-display))))
d240a249
GM
1447
1448(defun calculator-op-or-exp ()
1449 "Either enter an operator or a digit.
25c269ef 1450Used with +/- for entering them as digits in numbers like 1e-3 (there is
a1ff7705 1451no need for negative numbers since these are handled by unary operators)."
d240a249
GM
1452 (interactive)
1453 (if (and (not calculator-display-fragile)
1454 calculator-curnum
1455 (string-match "[eE]$" calculator-curnum))
1456 (calculator-digit)
1457 (calculator-op)))
1458
cbb2dddb 1459;;;---------------------------------------------------------------------
25c269ef
DL
1460;;; Input/output modes (not display)
1461
d240a249
GM
1462(defun calculator-dec/deg-mode ()
1463 "Set decimal mode for display & input, if decimal, toggle deg mode."
1464 (interactive)
1465 (if calculator-curnum
1466 (setq calculator-stack
1467 (cons (calculator-curnum-value) calculator-stack)))
1468 (setq calculator-curnum nil)
1469 (if (or calculator-input-radix calculator-output-radix)
1470 (progn (setq calculator-input-radix nil)
1471 (setq calculator-output-radix nil))
1472 ;; already decimal - toggle degrees mode
1473 (setq calculator-deg (not calculator-deg)))
1474 (calculator-update-display t))
1475
86f1e1ec
GM
1476(defun calculator-radix-mode (&optional keys)
1477 "Set input and display radix modes.
1478Optional string argument KEYS will force using it as the keys entered."
d240a249 1479 (interactive)
86f1e1ec
GM
1480 (calculator-radix-input-mode keys)
1481 (calculator-radix-output-mode keys))
d240a249 1482
86f1e1ec
GM
1483(defun calculator-radix-input-mode (&optional keys)
1484 "Set input radix modes.
1485Optional string argument KEYS will force using it as the keys entered."
d240a249
GM
1486 (interactive)
1487 (if calculator-curnum
1488 (setq calculator-stack
1489 (cons (calculator-curnum-value) calculator-stack)))
1490 (setq calculator-curnum nil)
1491 (setq calculator-input-radix
86f1e1ec 1492 (let ((inp (calculator-last-input keys)))
d240a249
GM
1493 (cdr (assq (upcase (aref inp (1- (length inp))))
1494 calculator-char-radix))))
1495 (calculator-update-display))
1496
86f1e1ec
GM
1497(defun calculator-radix-output-mode (&optional keys)
1498 "Set display radix modes.
1499Optional string argument KEYS will force using it as the keys entered."
d240a249
GM
1500 (interactive)
1501 (if calculator-curnum
1502 (setq calculator-stack
1503 (cons (calculator-curnum-value) calculator-stack)))
1504 (setq calculator-curnum nil)
1505 (setq calculator-output-radix
86f1e1ec 1506 (let ((inp (calculator-last-input keys)))
d240a249
GM
1507 (cdr (assq (upcase (aref inp (1- (length inp))))
1508 calculator-char-radix))))
1509 (calculator-update-display t))
1510
cbb2dddb 1511;;;---------------------------------------------------------------------
25c269ef
DL
1512;;; Saved values list
1513
d240a249
GM
1514(defun calculator-save-on-list ()
1515 "Evaluate current expression, put result on the saved values list."
1516 (interactive)
1517 (let ((calculator-add-saved t)) ; marks the result to be added
1518 (calculator-enter)))
1519
1520(defun calculator-clear-saved ()
1521 "Clear the list of saved values in `calculator-saved-list'."
1522 (interactive)
1523 (setq calculator-saved-list nil)
25c269ef 1524 (setq calculator-saved-ptr 0)
d240a249
GM
1525 (calculator-update-display t))
1526
1527(defun calculator-saved-move (n)
1528 "Go N elements up the list of saved values."
1529 (interactive)
1530 (and calculator-saved-list
1531 (or (null calculator-stack) calculator-display-fragile)
1532 (progn
1533 (setq calculator-saved-ptr
1534 (max (min (+ n calculator-saved-ptr)
1535 (length calculator-saved-list))
1536 0))
1537 (if (nth calculator-saved-ptr calculator-saved-list)
1538 (setq calculator-stack
1539 (list (nth calculator-saved-ptr calculator-saved-list))
1540 calculator-display-fragile t)
86f1e1ec
GM
1541 (calculator-reset))
1542 (calculator-update-display))))
d240a249
GM
1543
1544(defun calculator-saved-up ()
1545 "Go up the list of saved values."
1546 (interactive)
1547 (calculator-saved-move +1))
1548
1549(defun calculator-saved-down ()
1550 "Go down the list of saved values."
1551 (interactive)
1552 (calculator-saved-move -1))
1553
cbb2dddb 1554;;;---------------------------------------------------------------------
25c269ef
DL
1555;;; Misc functions
1556
d240a249
GM
1557(defun calculator-open-paren ()
1558 "Equivalents of `(' use this."
1559 (interactive)
86f1e1ec 1560 (calculator-op "("))
d240a249
GM
1561
1562(defun calculator-close-paren ()
1563 "Equivalents of `)' use this."
1564 (interactive)
86f1e1ec 1565 (calculator-op ")"))
d240a249
GM
1566
1567(defun calculator-enter ()
86f1e1ec 1568 "Evaluate current expression."
d240a249 1569 (interactive)
86f1e1ec 1570 (calculator-op "="))
d240a249
GM
1571
1572(defun calculator-backspace ()
1573 "Backward delete a single digit or a stack element."
1574 (interactive)
1575 (if calculator-curnum
1576 (setq calculator-curnum
1577 (if (> (length calculator-curnum) 1)
1578 (substring calculator-curnum
1579 0 (1- (length calculator-curnum)))
1580 nil))
1581 (setq calculator-stack (cdr calculator-stack)))
1582 (calculator-update-display))
1583
1584(defun calculator-clear ()
1585 "Clear current number."
1586 (interactive)
1587 (setq calculator-curnum nil)
1588 (cond
1589 ;; if the current number is from the saved-list - remove it
1590 ((and calculator-display-fragile
1591 calculator-saved-list
1592 (= (car calculator-stack)
1593 (nth calculator-saved-ptr calculator-saved-list)))
1594 (if (= 0 calculator-saved-ptr)
1595 (setq calculator-saved-list (cdr calculator-saved-list))
1596 (let ((p (nthcdr (1- calculator-saved-ptr)
1597 calculator-saved-list)))
1598 (setcdr p (cdr (cdr p)))
1599 (setq calculator-saved-ptr (1- calculator-saved-ptr))))
1600 (if calculator-saved-list
1601 (setq calculator-stack
1602 (list (nth calculator-saved-ptr calculator-saved-list)))
1603 (calculator-reset)))
1604 ;; reset if fragile or double clear
1605 ((or calculator-display-fragile (eq last-command this-command))
1606 (calculator-reset)))
1607 (calculator-update-display))
1608
1609(defun calculator-copy ()
1610 "Copy current number to the `kill-ring'."
1611 (interactive)
4351784f
GM
1612 (let ((calculator-displayer
1613 (or calculator-copy-displayer calculator-displayer))
1614 (calculator-displayers
1615 (if calculator-copy-displayer nil calculator-displayers)))
1616 (calculator-enter)
1214bb6e 1617 ;; remove trailing spaces and an index
4351784f
GM
1618 (let ((s (cdr calculator-stack-display)))
1619 (and s
1620 (if (string-match "^\\([^ ]+\\) *\\(\\[[0-9/]+\\]\\)? *$" s)
1621 (setq s (match-string 1 s)))
1622 (kill-new s)))))
d240a249
GM
1623
1624(defun calculator-set-register (reg)
1625 "Set a register value for REG."
1626 (interactive "cRegister to store into: ")
1627 (let* ((as (assq reg calculator-registers))
1628 (val (progn (calculator-enter) (car calculator-stack))))
1629 (if as
1630 (setcdr as val)
1631 (setq calculator-registers
1632 (cons (cons reg val) calculator-registers)))
761d3eb3 1633 (calculator-message "[%c] := %S" reg val)))
d240a249
GM
1634
1635(defun calculator-put-value (val)
1636 "Paste VAL as if entered.
1637Used by `calculator-paste' and `get-register'."
1638 (if (and (numberp val)
1639 ;; (not calculator-curnum)
1640 (or calculator-display-fragile
1641 (not (numberp (car calculator-stack)))))
1642 (progn
1643 (calculator-clear-fragile)
4351784f 1644 (setq calculator-curnum (let ((calculator-displayer "%S"))
761d3eb3 1645 (calculator-number-to-string val)))
d240a249
GM
1646 (calculator-update-display))))
1647
1648(defun calculator-paste ()
1649 "Paste a value from the `kill-ring'."
1650 (interactive)
1651 (calculator-put-value
761d3eb3
RS
1652 (let ((str (replace-regexp-in-string
1653 "^ *\\(.+[^ ]\\) *$" "\\1" (current-kill 0))))
1654 (and (not calculator-input-radix)
1655 calculator-paste-decimals
cbb2dddb
GM
1656 (string-match "\\([0-9]+\\)\\(\\.[0-9]+\\)?\\(e[0-9]+\\)?"
1657 str)
1658 (or (match-string 1 str)
1659 (match-string 2 str)
1660 (match-string 3 str))
761d3eb3 1661 (setq str (concat (or (match-string 1 str) "0")
cbb2dddb 1662 (or (match-string 2 str) ".0")
761d3eb3
RS
1663 (or (match-string 3 str) ""))))
1664 (condition-case nil (calculator-string-to-number str)
25c269ef 1665 (error nil)))))
d240a249
GM
1666
1667(defun calculator-get-register (reg)
1668 "Get a value from a register REG."
1669 (interactive "cRegister to get value from: ")
1670 (calculator-put-value (cdr (assq reg calculator-registers))))
1671
1672(defun calculator-help ()
1673 ;; this is used as the quick reference screen you get with `h'
1674 "Quick reference:
1675* numbers/operators/parens/./e - enter expressions
1676 + - * / \\(div) %(rem) _(-X,postfix) ;(1/X,postfix) ^(exp) L(og)
1677 Q(sqrt) !(fact) S(in) C(os) T(an) |(or) #(xor) &(and) ~(not)
1678* >/< repeats last binary operation with its 2nd (1st) arg as postfix op
25c269ef
DL
1679* I inverses next trig function * '/\"/{} - display/display args
1680* D - switch to all-decimal, or toggle deg/rad mode
d240a249
GM
1681* B/O/H/X - binary/octal/hex mode for i/o (X is a shortcut for H)
1682* i/o - prefix for d/b/o/x - set only input/output modes
1683* enter/= - evaluate current expr. * s/g - set/get a register
1684* space - evaluate & save on list * l/v - list total/average
1685* up/down/C-p/C-n - browse saved * C-delete - clear all saved
86f1e1ec 1686* C-insert - copy whole expr. * C-return - evaluate, copy, exit
d240a249
GM
1687* insert - paste a number * backspace- delete backwards
1688* delete - clear argument or list value or whole expression (twice)
1689* escape/q - exit."
1690 (interactive)
1691 (if (eq last-command 'calculator-help)
1692 (let ((mode-name "Calculator")
1693 (major-mode 'calculator-mode)
1694 (g-map (current-global-map))
1695 (win (selected-window)))
1696 (require 'ehelp)
1697 (if calculator-electric-mode
1698 (use-global-map calculator-saved-global-map))
cbb2dddb
GM
1699 (if (or (not calculator-electric-mode)
1700 ;; XEmacs has a problem with electric-describe-mode
f8246027 1701 (featurep 'xemacs))
cbb2dddb
GM
1702 (describe-mode)
1703 (electric-describe-mode))
d240a249
GM
1704 (if calculator-electric-mode
1705 (use-global-map g-map))
1706 (select-window win) ; these are for XEmacs (also below)
1707 (message nil))
1708 (let ((one (one-window-p t))
1709 (win (selected-window))
1710 (help-buf (get-buffer-create "*Help*")))
1711 (save-window-excursion
1712 (with-output-to-temp-buffer "*Help*"
1713 (princ (documentation 'calculator-help)))
1714 (if one
1715 (shrink-window-if-larger-than-buffer
1716 (get-buffer-window help-buf)))
1717 (message
1718 "`%s' again for more help, any other key continues normally."
1719 (calculator-last-input))
1720 (select-window win)
1721 (sit-for 360))
1722 (select-window win))))
1723
1724(defun calculator-quit ()
1725 "Quit calculator."
1726 (interactive)
1727 (set-buffer calculator-buffer)
1728 (let ((inhibit-read-only t)) (erase-buffer))
1729 (if (not calculator-electric-mode)
1730 (progn
1731 (condition-case nil
1732 (while (get-buffer-window calculator-buffer)
1733 (delete-window (get-buffer-window calculator-buffer)))
1734 (error nil))
1735 (kill-buffer calculator-buffer)))
1736 (setq calculator-buffer nil)
1737 (message "Calculator done.")
1738 (if calculator-electric-mode (throw 'calculator-done nil)))
1739
1740(defun calculator-save-and-quit ()
1741 "Quit the calculator, saving the result on the `kill-ring'."
1742 (interactive)
1743 (calculator-enter)
1744 (calculator-copy)
1745 (calculator-quit))
1746
d240a249 1747(defun calculator-repR (x)
a1ff7705 1748 "Repeat the last binary operation with its second argument and X.
d240a249
GM
1749To use this, apply a binary operator (evaluate it), then call this."
1750 (if calculator-last-opXY
1751 ;; avoid rebinding calculator-last-opXY
1752 (let ((calculator-last-opXY calculator-last-opXY))
1753 (calculator-funcall
1754 (car calculator-last-opXY) x (nth 2 calculator-last-opXY)))
1755 x))
1756
1757(defun calculator-repL (x)
a1ff7705 1758 "Repeat the last binary operation with its first argument and X.
d240a249
GM
1759To use this, apply a binary operator (evaluate it), then call this."
1760 (if calculator-last-opXY
1761 ;; avoid rebinding calculator-last-opXY
1762 (let ((calculator-last-opXY calculator-last-opXY))
1763 (calculator-funcall
1764 (car calculator-last-opXY) (nth 1 calculator-last-opXY) x))
1765 x))
1766
f50347a9
JB
1767(defun calculator-integer-p (x)
1768 "Non-nil if X is equal to an integer."
1769 (condition-case nil
1770 (= x (ftruncate x))
1771 (error nil)))
1772
1773(defun calculator-expt (x y)
1774 "Compute X^Y, dealing with errors appropriately."
1775 (condition-case
1776 nil
1777 (expt x y)
1778 (domain-error 0.0e+NaN)
1779 (range-error
b4739e5d
JB
1780 (cond
1781 ((and (< x 1.0) (> x -1.0))
1782 ;; For small x, the range error comes from large y.
1783 0.0)
1784 ((and (> x 0.0) (< y 0.0))
cba1a4bd 1785 ;; For large positive x and negative y, the range error
b4739e5d
JB
1786 ;; comes from large negative y.
1787 0.0)
1788 ((and (> x 0.0) (> y 0.0))
cba1a4bd 1789 ;; For large positive x and positive y, the range error
b4739e5d
JB
1790 ;; comes from large y.
1791 1.0e+INF)
1792 ;; For the rest, x must be large and negative.
1793 ;; The range errors come from large integer y.
1794 ((< y 0.0)
1795 0.0)
cba1a4bd 1796 ((eq (logand (truncate y) 1) 1) ; expansion of cl `oddp'
b4739e5d
JB
1797 ;; If y is odd
1798 -1.0e+INF)
1799 (t
a1ff7705 1800 ;;
b4739e5d 1801 1.0e+INF)))
f50347a9
JB
1802 (error 0.0e+NaN)))
1803
d240a249
GM
1804(defun calculator-fact (x)
1805 "Simple factorial of X."
f50347a9
JB
1806 (if (and (>= x 0)
1807 (calculator-integer-p x))
1808 (if (= (calculator-expt (/ x 3.0) x) 1.0e+INF)
1809 1.0e+INF
1810 (let ((r (if (<= x 10) 1 1.0)))
1811 (while (> x 0)
1812 (setq r (* r (truncate x)))
1813 (setq x (1- x)))
1814 (+ 0.0 r)))
1815 (if (= x 1.0e+INF)
1816 x
1817 0.0e+NaN)))
d240a249
GM
1818
1819(defun calculator-truncate (n)
1820 "Truncate N, return 0 in case of overflow."
1821 (condition-case nil (truncate n) (error 0)))
1822
1823
1824(provide 'calculator)
1825
1826;;; calculator.el ends here