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