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