1;;; calculator.el --- a [not so] simple calculator for Emacs
2
3;; Copyright (C) 1998, 2000, 2001, 2002, 2003, 2004,
4;;   2005, 2006, 2007 Free Software Foundation, Inc.
5
6;; Author: Eli Barzilay <eli@barzilay.org>
7;; Keywords: tools, convenience
8;; Time-stamp: <2006-02-06 13:36:00 ttn>
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
24;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
25;; MA 02110-1301, USA.
26
27;;;=====================================================================
28;;; Commentary:
29;;
30;; A calculator for Emacs.
31;; Why should you reach for your mouse to get xcalc (calc.exe, gcalc or
32;; whatever), when you have Emacs running already?
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"
37;;     "Run the Emacs calculator." t)
38;;   (global-set-key [(control return)] 'calculator)
39;;
40;; Written by Eli Barzilay: Maze is Life!  eli@barzilay.org
41;;                                         http://www.barzilay.org/
42;;
43;; For latest version, check
44;;     http://www.barzilay.org/misc/calculator.el
45;;
46
47;;; History:
48;; I hate history.
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
55;;;=====================================================================
56;;; Customization:
57
58(defgroup calculator nil
59  "Simple Emacs calculator."
60  :prefix "calculator"
61  :version "21.1"
62  :group 'tools
63  :group 'convenience)
64
65(defcustom calculator-electric-mode nil
66  "*Run `calculator' electrically, in the echo area.
67Electric mode saves some place but changes the way you interact with the
68calculator."
69  :type  'boolean
70  :group 'calculator)
71
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
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
89(defcustom calculator-prompt "Calc=%s> "
90  "*The prompt used by the Emacs calculator.
91It should contain a \"%s\" somewhere that will indicate the i/o radixes;
92this will be a two-character string as described in the documentation
93for `calculator-mode'."
94  :type  'string
95  :group 'calculator)
96
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."
102  :type  'integer
103  :group 'calculator)
104
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
109output mode is active (determined by `calculator-output-radix')."
110  :type  'boolean
111  :group 'calculator)
112
113(defcustom calculator-radix-grouping-digits 4
114  "*The number of digits used for grouping display in radix modes.
115See `calculator-radix-grouping-mode'."
116  :type  'integer
117  :group 'calculator)
118
119(defcustom calculator-radix-grouping-separator "'"
120  "*The separator used in radix grouping display.
121See `calculator-radix-grouping-mode'."
122  :type  'string
123  :group 'calculator)
124
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))
131  :group 'calculator)
132
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
150will be used with this character for a format string."
151  :group 'calculator)
152
153(defcustom calculator-displayers
154  '(((std ?n) "Standard display, decimal point or scientific")
155    (calculator-eng-display "Eng display")
156    ((std ?f) "Standard display, decimal point")
157    ((std ?e) "Standard display, scientific")
158    ("%S"     "Emacs printer"))
159  "*A list of displayers.
160Each element is a list of a displayer and a description string.  The
161first element is the one which is currently used, this is for the display
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
167  :group 'calculator)
168
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."
173  :type  'boolean
174  :group 'calculator)
175
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
180used."
181  :type  'boolean
182  :group 'calculator)
183
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
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."
196  :type  'hook
197  :group 'calculator)
198
199(defcustom calculator-user-registers nil
200  "*An association list of user-defined register bindings.
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:
205  (setq calculator-user-registers '((?g .  1.61803398875)))
206before you load calculator."
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.
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
224* A very simple one, adding a postfix \"x-to-y\" conversion keys, using
225  t as a prefix key:
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)
242                         1
243                         (+ (F (- TX 1)) (F (- TX 2)))) 0))
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
250;;;=====================================================================
251;;; Code:
252
253;;;---------------------------------------------------------------------
254;;; Variables
255
256(defvar calculator-initial-operators
257  '(;; "+"/"-" have keybindings of themselves, not calculator-ops
258    ("=" =     identity        1 -1)
259    (nobind "+" +  +           2  4)
260    (nobind "-" -  -           2  4)
261    (nobind "+" +  +          -1  9)
262    (nobind "-" -  -          -1  9)
263    ("(" \(    identity       -1 -1)
264    (")" \)    identity       +1 10)
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.
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
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);
318
3195. The function's precedence - should be in the range of 1 (lowest) to
320   9 (highest) (optional, defaults to 1);
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
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
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
384(defvar calculator-restart-other-mode nil
385  "Used to hack restarting with the electric mode changed.")
386
387;;;---------------------------------------------------------------------
388;;; Key bindings
389
390(defvar calculator-mode-map nil
391  "The calculator key map.")
392
393(or calculator-mode-map
394  (let ((map (make-sparse-keymap)))
395    (suppress-keymap map t)
396    (define-key map "i" nil)
397    (define-key map "o" nil)
398    (let ((p
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")
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")
417             (calculator-rotate-displayer      "'")
418             (calculator-rotate-displayer-back "\"")
419             (calculator-displayer-prev        "{")
420             (calculator-displayer-next        "}")
421             (calculator-saved-up      [up] [?\C-p])
422             (calculator-saved-down    [down] [?\C-n])
423             (calculator-quit          "q" [?\C-g])
424             (calculator-enter         [enter] [linefeed] [kp-enter]
425                                       [return] [?\r] [?\n])
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)])
430             (calculator-paste         [insert] [(shift insert)]
431                                       [paste] [mouse-2] [?\C-y])
432             (calculator-clear         [delete] [?\C-?] [?\C-d])
433             (calculator-help          [?h] [??] [f1] [help])
434             (calculator-copy          [(control insert)] [copy])
435             (calculator-backspace     [backspace])
436             )))
437      (while p
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))))
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))
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            ("Separate I/O"
565             ,@(mapcar (lambda (x) (nth 1 x)) radix-selectors)
566             "---"
567             ,@(mapcar (lambda (x) (nth 2 x)) radix-selectors)))
568           ("Decimal Display"
569            ,@(mapcar (lambda (d)
570                        (vector (cadr d)
571                                ;; Note: inserts actual object here
572                                `(calculator-rotate-displayer ',d)))
573                      calculator-displayers)
574            "---"
575            ["Change Prev Display" calculator-displayer-prev]
576            ["Change Next Display" calculator-displayer-next])
577           "---"
578           ["Copy+Quit" calculator-save-and-quit]
579           ["Quit"      calculator-quit]))))
580    (setq calculator-mode-map map)))
581
582;;;---------------------------------------------------------------------
583;;; Startup and mode stuff
584
585(defun calculator-mode ()
586  ;; this help is also used as the major help screen
587  "A [not so] simple calculator for Emacs.
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'
604* `C-return'     evaluate, save result the `kill-ring' and exit
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
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.
648
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)
684  (run-mode-hooks 'calculator-mode-hook))
685
686(eval-when-compile (require 'electric) (require 'ehelp))
687
688;;;###autoload
689(defun calculator ()
690  "Run the Emacs calculator.
691See the documentation for `calculator-mode' for more information."
692  (interactive)
693  (if calculator-restart-other-mode
694    (setq calculator-electric-mode (not calculator-electric-mode)))
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,
699           ;; its set function will add any new operators
700           (calculator-add-operators calculator-user-operators)))
701  (setq calculator-buffer (get-buffer-create "*calculator*"))
702  (if calculator-electric-mode
703    (save-window-excursion
704      (progn (require 'electric) (message nil)) ; hide load message
705      (let (old-g-map old-l-map (echo-keystrokes 0)
706            (garbage-collection-messages nil)) ; no gc msg when electric
707        (set-window-buffer (minibuffer-window) calculator-buffer)
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))
714        (use-local-map nil)
715        (use-global-map calculator-mode-map)
716        (run-hooks 'calculator-mode-hook)
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
724               (lambda (x y) (calculator-update-display))))
725          (and calculator-buffer
726               (catch 'calculator-done (calculator-quit)))
727          (use-local-map old-l-map)
728          (use-global-map old-g-map))))
729    (progn
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
738             ;; If the modeline might interfere with the calculator buffer,
739             ;; use 3 lines instead.
740             (if (and (fboundp 'face-attr-construct)
741                      (let* ((dh (plist-get (face-attr-construct 'default) :height))
742                             (mf (face-attr-construct 'modeline))
743                             (mh (plist-get mf :height)))
744                        ;; If the modeline is shorter than the default,
745                        ;; stick with 2 lines.  (It may be necessary to
746                        ;; check how much shorter.)
747                        (and
748                         (not
749                          (or (and (integerp dh)
750                                   (integerp mh)
751                                   (< mh dh))
752                              (and (numberp mh)
753                                   (not (integerp mh))
754                                   (< mh 1))))
755                         (or
756                          ;; If the modeline is taller than the default,
757                          ;; use 3 lines.
758                          (and (integerp dh)
759                               (integerp mh)
760                               (> mh dh))
761                          (and (numberp mh)
762                               (not (integerp mh))
763                               (> mh 1))
764                          ;; If the modeline has a box with non-negative line-width,
765                          ;; use 3 lines.
766                          (let* ((bx (plist-get mf :box))
767                                 (lh (plist-get bx :line-width)))
768                            (and bx
769                                 (or
770                                  (not lh)
771                                  (> lh 0))))
772                          ;; If the modeline has an overline, use 3 lines.
773                          (plist-get (face-attr-construct 'modeline) :overline)))))
774               -3 -2)))
775           (switch-to-buffer calculator-buffer)))
776        ((not (eq (current-buffer) calculator-buffer))
777         (select-window (get-buffer-window calculator-buffer))))
778      (calculator-mode)
779      (setq buffer-read-only t)
780      (calculator-reset)
781      (message "Hit `?' For a quick help screen.")))
782  (if (and calculator-restart-other-mode calculator-electric-mode)
783    (calculator)))
784
785(defun calculator-message (string &rest arguments)
786  "Same as `message', but special handle of electric mode."
787  (apply 'message string arguments)
788  (if calculator-electric-mode
789    (progn (sit-for 1) (message nil))))
790
791;;;---------------------------------------------------------------------
792;;; Operators
793
794(defun calculator-op-arity (op)
795  "Return OP's arity, 2, +1 or -1."
796  (let ((arity (or (nth 3 op) 'x)))
797    (if (numberp arity)
798      arity
799      (if (eq calculator-unary-style 'postfix) +1 -1))))
800
801(defun calculator-op-prec (op)
802  "Return OP's precedence for reducing when inserting into the stack.
803Defaults to 1."
804  (or (nth 4 op) 1))
805
806(defun calculator-add-operators (more-ops)
807  "This function handles operator addition.
808Adds MORE-OPS to `calculator-operator', called initially to handle
809`calculator-initial-operators' and `calculator-user-operators'."
810  (let ((added-ops nil))
811    (while more-ops
812      (or (eq (car (car more-ops)) 'nobind)
813          (let ((i -1) (key (car (car more-ops))))
814            ;; make sure the key is undefined, so it's easy to define
815            ;; prefix keys
816            (while (< (setq i (1+ i)) (length key))
817              (or (keymapp
818                   (lookup-key calculator-mode-map
819                               (substring key 0 (1+ i))))
820                  (progn
821                    (define-key
822                      calculator-mode-map (substring key 0 (1+ i)) nil)
823                    (setq i (length key)))))
824            (define-key calculator-mode-map key 'calculator-op)))
825      (setq added-ops (cons (if (eq (car (car more-ops)) 'nobind)
826                              (cdr (car more-ops))
827                              (car more-ops))
828                            added-ops))
829      (setq more-ops (cdr more-ops)))
830    ;; added-ops come first, but in correct order
831    (setq calculator-operators
832          (append (nreverse added-ops) calculator-operators))))
833
834;;;---------------------------------------------------------------------
835;;; Display stuff
836
837(defun calculator-reset ()
838  "Reset calculator variables."
839  (or calculator-restart-other-mode
840      (setq calculator-stack           nil
841            calculator-curnum          nil
842            calculator-stack-display   nil
843            calculator-display-fragile nil))
844  (setq calculator-restart-other-mode nil)
845  (calculator-update-display))
846
847(defun calculator-get-prompt ()
848  "Return a string to display.
849The string is set not to exceed the screen width."
850  (let* ((calculator-prompt
851          (format calculator-prompt
852                  (cond
853                    ((or calculator-output-radix calculator-input-radix)
854                     (if (eq calculator-output-radix
855                             calculator-input-radix)
856                       (concat
857                        (char-to-string
858                         (car (rassq calculator-output-radix
859                                     calculator-char-radix)))
860                        "=")
861                       (concat
862                        (if calculator-input-radix
863                          (char-to-string
864                           (car (rassq calculator-input-radix
865                                       calculator-char-radix)))
866                          "=")
867                        (char-to-string
868                         (car (rassq calculator-output-radix
869                                     calculator-char-radix))))))
870                    (calculator-deg "D=")
871                    (t "=="))))
872         (prompt
873          (concat calculator-prompt
874                  (cdr calculator-stack-display)
875                  (cond (calculator-curnum
876                         ;; number being typed
877                         (concat calculator-curnum "_"))
878                        ((and (= 1 (length calculator-stack))
879                              calculator-display-fragile)
880                         ;; only the result is shown, next number will
881                         ;; restart
882                         nil)
883                        (t
884                         ;; waiting for a number or an operator
885                         "?"))))
886         (trim (- (length prompt) (1- (window-width)))))
887    (if (<= trim 0)
888      prompt
889      (concat calculator-prompt
890              (substring prompt (+ trim (length calculator-prompt)))))))
891
892(defun calculator-string-to-number (str)
893  "Convert the given STR to a number, according to the value of
894`calculator-input-radix'."
895  (if calculator-input-radix
896    (let ((radix
897           (cdr (assq calculator-input-radix
898                      '((bin . 2) (oct . 8) (hex . 16)))))
899          (i -1) (value 0) (new-value 0))
900      ;; assume mostly valid input (e.g., characters in range)
901      (while (< (setq i (1+ i)) (length str))
902        (setq new-value
903              (let* ((ch (upcase (aref str i)))
904                     (n (cond ((< ch ?0)  nil)
905                              ((<= ch ?9) (- ch ?0))
906                              ((< ch ?A)  nil)
907                              ((<= ch ?Z) (- ch (- ?A 10)))
908                              (t          nil))))
909                (if (and n (<= 0 n) (< n radix))
910                  (+ n (* radix value))
911                  (progn
912                    (calculator-message
913                     "Warning: Ignoring bad input character `%c'." ch)
914                    (sit-for 1)
915                    value))))
916        (if (if (< new-value 0) (> value 0) (< value 0))
917          (calculator-message "Warning: Overflow in input."))
918        (setq value new-value))
919      value)
920    (car (read-from-string
921          (cond ((equal "." str) "0.0")
922                ((string-match "[eE][+-]?$" str) (concat str "0"))
923                ((string-match "\\.[0-9]\\|[eE]" str) str)
924                ((string-match "\\." str)
925                 ;; do this because Emacs reads "23." as an integer
926                 (concat str "0"))
927                ((stringp str) (concat str ".0"))
928                (t "0.0"))))))
929
930(defun calculator-curnum-value ()
931  "Get the numeric value of the displayed number string as a float."
932  (calculator-string-to-number calculator-curnum))
933
934(defun calculator-rotate-displayer (&optional new-disp)
935  "Switch to the next displayer on the `calculator-displayers' list.
936Can be called with an optional argument NEW-DISP to force rotation to
937that argument.
938If radix output mode is active, toggle digit grouping."
939  (interactive)
940  (cond
941    (calculator-output-radix
942     (setq calculator-radix-grouping-mode
943           (not calculator-radix-grouping-mode))
944     (calculator-message
945      "Digit grouping mode %s."
946      (if calculator-radix-grouping-mode "ON" "OFF")))
947    (t
948     (setq calculator-displayers
949           (if (and new-disp (memq new-disp calculator-displayers))
950             (let ((tmp nil))
951               (while (not (eq (car calculator-displayers) new-disp))
952                 (setq tmp (cons (car calculator-displayers) tmp))
953                 (setq calculator-displayers
954                       (cdr calculator-displayers)))
955               (setq calculator-displayers
956                     (nconc calculator-displayers (nreverse tmp))))
957             (nconc (cdr calculator-displayers)
958                    (list (car calculator-displayers)))))
959     (calculator-message
960      "Using %s." (cadr (car calculator-displayers)))))
961  (calculator-enter))
962
963(defun calculator-rotate-displayer-back ()
964  "Like `calculator-rotate-displayer', but rotates modes back.
965If radix output mode is active, toggle digit grouping."
966  (interactive)
967  (calculator-rotate-displayer (car (last calculator-displayers))))
968
969(defun calculator-displayer-prev ()
970  "Send the current displayer function a 'left argument.
971This is used to modify display arguments (if the current displayer
972function supports this).
973If radix output mode is active, increase the grouping size."
974  (interactive)
975  (if calculator-output-radix
976    (progn (setq calculator-radix-grouping-digits
977                 (1+ calculator-radix-grouping-digits))
978           (calculator-enter))
979    (and (car calculator-displayers)
980         (let ((disp (caar calculator-displayers)))
981           (cond
982             ((symbolp disp) (funcall disp 'left))
983             ((and (consp disp) (eq 'std (car disp)))
984              (calculator-standard-displayer 'left (cadr disp))))))))
985
986(defun calculator-displayer-next ()
987  "Send the current displayer function a 'right argument.
988This is used to modify display arguments (if the current displayer
989function supports this).
990If radix output mode is active, decrease the grouping size."
991  (interactive)
992  (if calculator-output-radix
993    (progn (setq calculator-radix-grouping-digits
994                 (max 2 (1- calculator-radix-grouping-digits)))
995           (calculator-enter))
996    (and (car calculator-displayers)
997         (let ((disp (caar calculator-displayers)))
998           (cond
999             ((symbolp disp) (funcall disp 'right))
1000             ((and (consp disp) (eq 'std (car disp)))
1001              (calculator-standard-displayer 'right (cadr disp))))))))
1002
1003(defun calculator-remove-zeros (numstr)
1004  "Get a number string NUMSTR and remove unnecessary zeroes.
1005the behavior of this function is controlled by
1006`calculator-remove-zeros'."
1007  (cond ((and (eq calculator-remove-zeros t)
1008              (string-match "\\.0+\\([eE][+-]?[0-9]*\\)?$" numstr))
1009         ;; remove all redundant zeros leaving an integer
1010         (if (match-beginning 1)
1011           (concat (substring numstr 0 (match-beginning 0))
1012                   (match-string 1 numstr))
1013           (substring numstr 0 (match-beginning 0))))
1014        ((and calculator-remove-zeros
1015              (string-match
1016               "\\..\\([0-9]*[1-9]\\)?\\(0+\\)\\([eE][+-]?[0-9]*\\)?$"
1017               numstr))
1018         ;; remove zeros, except for first after the "."
1019         (if (match-beginning 3)
1020           (concat (substring numstr 0 (match-beginning 2))
1021                   (match-string 3 numstr))
1022           (substring numstr 0 (match-beginning 2))))
1023        (t numstr)))
1024
1025(defun calculator-standard-displayer (num char)
1026  "Standard display function, used to display NUM.
1027Its behavior is determined by `calculator-number-digits' and the given
1028CHAR argument (both will be used to compose a format string).  If the
1029char is \"n\" then this function will choose one between %f or %e, this
1030is a work around %g jumping to exponential notation too fast.
1031
1032The special 'left and 'right symbols will make it change the current
1033number of digits displayed (`calculator-number-digits').
1034
1035It will also remove redundant zeros from the result."
1036  (if (symbolp num)
1037    (cond ((eq num 'left)
1038           (and (> calculator-number-digits 0)
1039                (setq calculator-number-digits
1040                      (1- calculator-number-digits))
1041                (calculator-enter)))
1042          ((eq num 'right)
1043           (setq calculator-number-digits
1044                 (1+ calculator-number-digits))
1045           (calculator-enter)))
1046    (let ((str (if (zerop num)
1047                 "0"
1048                 (format
1049                  (concat "%."
1050                          (number-to-string calculator-number-digits)
1051                          (if (eq char ?n)
1052                            (let ((n (abs num)))
1053                              (if (or (< n 0.001) (> n 1e8)) "e" "f"))
1054                            (string char)))
1055                  num))))
1056      (calculator-remove-zeros str))))
1057
1058(defun calculator-eng-display (num)
1059  "Display NUM in engineering notation.
1060The number of decimal digits used is controlled by
1061`calculator-number-digits', so to change it at runtime you have to use
1062the 'left or 'right when one of the standard modes is used."
1063  (if (symbolp num)
1064    (cond ((eq num 'left)
1065           (setq calculator-eng-extra
1066                 (if calculator-eng-extra
1067                   (1+ calculator-eng-extra)
1068                   1))
1069           (let ((calculator-eng-tmp-show t)) (calculator-enter)))
1070          ((eq num 'right)
1071           (setq calculator-eng-extra
1072                 (if calculator-eng-extra
1073                   (1- calculator-eng-extra)
1074                   -1))
1075           (let ((calculator-eng-tmp-show t)) (calculator-enter))))
1076    (let ((exp 0))
1077      (and (not (= 0 num))
1078           (progn
1079             (while (< (abs num) 1.0)
1080               (setq num (* num 1000.0)) (setq exp (- exp 3)))
1081             (while (> (abs num) 999.0)
1082               (setq num (/ num 1000.0)) (setq exp (+ exp 3)))
1083             (and calculator-eng-tmp-show
1084                  (not (= 0 calculator-eng-extra))
1085                  (let ((i calculator-eng-extra))
1086                    (while (> i 0)
1087                      (setq num (* num 1000.0)) (setq exp (- exp 3))
1088                      (setq i (1- i)))
1089                    (while (< i 0)
1090                      (setq num (/ num 1000.0)) (setq exp (+ exp 3))
1091                      (setq i (1+ i)))))))
1092      (or calculator-eng-tmp-show (setq calculator-eng-extra nil))
1093      (let ((str (format (concat "%." (number-to-string
1094                                       calculator-number-digits)
1095                                 "f")
1096                         num)))
1097        (concat (let ((calculator-remove-zeros
1098                       ;; make sure we don't leave integers
1099                       (and calculator-remove-zeros 'x)))
1100                  (calculator-remove-zeros str))
1101                "e" (number-to-string exp))))))
1102
1103(defun calculator-number-to-string (num)
1104  "Convert NUM to a displayable string."
1105  (cond
1106    ((and (numberp num) calculator-output-radix)
1107     ;; print with radix - for binary I convert the octal number
1108     (let ((str (format (if (eq calculator-output-radix 'hex) "%x" "%o")
1109                        (calculator-truncate
1110                         (if calculator-2s-complement num (abs num))))))
1111       (if (eq calculator-output-radix 'bin)
1112         (let ((i -1) (s ""))
1113           (while (< (setq i (1+ i)) (length str))
1114             (setq s
1115                   (concat s
1116                           (cdr (assq (aref str i)
1117                                      '((?0 . "000") (?1 . "001")
1118                                        (?2 . "010") (?3 . "011")
1119                                        (?4 . "100") (?5 . "101")
1120                                        (?6 . "110") (?7 . "111")))))))
1121           (string-match "^0*\\(.+\\)" s)
1122           (setq str (match-string 1 s))))
1123       (if calculator-radix-grouping-mode
1124         (let ((d (/ (length str) calculator-radix-grouping-digits))
1125               (r (% (length str) calculator-radix-grouping-digits)))
1126           (while (>= (setq d (1- d)) (if (zerop r) 1 0))
1127             (let ((i (+ r (* d calculator-radix-grouping-digits))))
1128               (setq str (concat (substring str 0 i)
1129                                 calculator-radix-grouping-separator
1130                                 (substring str i)))))))
1131       (upcase
1132        (if (and (not calculator-2s-complement) (< num 0))
1133          (concat "-" str)
1134          str))))
1135    ((and (numberp num) calculator-displayer)
1136     (cond
1137       ((stringp calculator-displayer)
1138        (format calculator-displayer num))
1139       ((symbolp calculator-displayer)
1140        (funcall calculator-displayer num))
1141       ((and (consp calculator-displayer)
1142             (eq 'std (car calculator-displayer)))
1143        (calculator-standard-displayer num (cadr calculator-displayer)))
1144       ((listp calculator-displayer)
1145        (eval calculator-displayer))
1146       (t (prin1-to-string num t))))
1147    ;; operators are printed here
1148    (t (prin1-to-string (nth 1 num) t))))
1149
1150(defun calculator-update-display (&optional force)
1151  "Update the display.
1152If optional argument FORCE is non-nil, don't use the cached string."
1153  (set-buffer calculator-buffer)
1154  ;; update calculator-stack-display
1155  (if (or force
1156          (not (eq (car calculator-stack-display) calculator-stack)))
1157    (setq calculator-stack-display
1158          (cons calculator-stack
1159                (if calculator-stack
1160                  (concat
1161                   (let ((calculator-displayer
1162                          (if (and calculator-displayers
1163                                   (= 1 (length calculator-stack)))
1164                            ;; customizable display for a single value
1165                            (caar calculator-displayers)
1166                            calculator-displayer)))
1167                     (mapconcat 'calculator-number-to-string
1168                                (reverse calculator-stack)
1169                                " "))
1170                   " "
1171                   (and calculator-display-fragile
1172                        calculator-saved-list
1173                        (= (car calculator-stack)
1174                           (nth calculator-saved-ptr
1175                                calculator-saved-list))
1176                        (if (= 0 calculator-saved-ptr)
1177                          (format "[%s]" (length calculator-saved-list))
1178                          (format "[%s/%s]"
1179                                  (- (length calculator-saved-list)
1180                                     calculator-saved-ptr)
1181                                  (length calculator-saved-list)))))
1182                  ""))))
1183  (let ((inhibit-read-only t))
1184    (erase-buffer)
1185    (insert (calculator-get-prompt)))
1186  (set-buffer-modified-p nil)
1187  (if calculator-display-fragile
1188    (goto-char (1+ (length calculator-prompt)))
1189    (goto-char (1- (point)))))
1190
1191;;;---------------------------------------------------------------------
1192;;; Stack computations
1193
1194(defun calculator-reduce-stack (prec)
1195  "Reduce the stack using top operator.
1196PREC is a precedence - reduce everything with higher precedence."
1197  (while
1198      (cond
1199        ((and (cdr (cdr calculator-stack))         ; have three values
1200              (consp   (nth 0 calculator-stack))   ; two operators & num
1201              (numberp (nth 1 calculator-stack))
1202              (consp   (nth 2 calculator-stack))
1203              (eq '\) (nth 1 (nth 0 calculator-stack)))
1204              (eq '\( (nth 1 (nth 2 calculator-stack))))
1205         ;; reduce "... ( x )" --> "... x"
1206         (setq calculator-stack
1207               (cons (nth 1 calculator-stack)
1208                     (nthcdr 3 calculator-stack)))
1209         ;; another iteration
1210         t)
1211        ((and (cdr (cdr calculator-stack))         ; have three values
1212              (numberp (nth 0 calculator-stack))   ; two nums & operator
1213              (consp   (nth 1 calculator-stack))
1214              (numberp (nth 2 calculator-stack))
1215              (= 2 (calculator-op-arity            ; binary operator
1216                    (nth 1 calculator-stack)))
1217              (<= prec                             ; with higher prec.
1218                  (calculator-op-prec (nth 1 calculator-stack))))
1219         ;; reduce "... x op y" --> "... r", r is the result
1220         (setq calculator-stack
1221               (cons (calculator-funcall
1222                      (nth 2 (nth 1 calculator-stack))
1223                      (nth 2 calculator-stack)
1224                      (nth 0 calculator-stack))
1225                     (nthcdr 3 calculator-stack)))
1226         ;; another iteration
1227         t)
1228        ((and (>= (length calculator-stack) 2)     ; have two values
1229              (numberp (nth 0 calculator-stack))   ; number & operator
1230              (consp   (nth 1 calculator-stack))
1231              (= -1 (calculator-op-arity           ; prefix-unary op
1232                     (nth 1 calculator-stack)))
1233              (<= prec                             ; with higher prec.
1234                  (calculator-op-prec (nth 1 calculator-stack))))
1235         ;; reduce "... op x" --> "... r" for prefix op
1236         (setq calculator-stack
1237               (cons (calculator-funcall
1238                      (nth 2 (nth 1 calculator-stack))
1239                      (nth 0 calculator-stack))
1240                     (nthcdr 2 calculator-stack)))
1241         ;; another iteration
1242         t)
1243        ((and (cdr calculator-stack)               ; have two values
1244              (consp   (nth 0 calculator-stack))   ; operator & number
1245              (numberp (nth 1 calculator-stack))
1246              (= +1 (calculator-op-arity           ; postfix-unary op
1247                     (nth 0 calculator-stack)))
1248              (<= prec                             ; with higher prec.
1249                  (calculator-op-prec (nth 0 calculator-stack))))
1250         ;; reduce "... x op" --> "... r" for postfix op
1251         (setq calculator-stack
1252               (cons (calculator-funcall
1253                      (nth 2 (nth 0 calculator-stack))
1254                      (nth 1 calculator-stack))
1255                     (nthcdr 2 calculator-stack)))
1256         ;; another iteration
1257         t)
1258        ((and calculator-stack                     ; have one value
1259              (consp (nth 0 calculator-stack))     ; an operator
1260              (= 0 (calculator-op-arity            ; 0-ary op
1261                    (nth 0 calculator-stack))))
1262         ;; reduce "... op" --> "... r" for 0-ary op
1263         (setq calculator-stack
1264               (cons (calculator-funcall
1265                      (nth 2 (nth 0 calculator-stack)))
1266                     (nthcdr 1 calculator-stack)))
1267         ;; another iteration
1268         t)
1269        ((and (cdr calculator-stack)               ; have two values
1270              (numberp (nth 0 calculator-stack))   ; both numbers
1271              (numberp (nth 1 calculator-stack)))
1272         ;; get rid of redundant numbers:
1273         ;;   reduce "... y x" --> "... x"
1274         ;; needed for 0-ary ops that puts more values
1275         (setcdr calculator-stack (cdr (cdr calculator-stack))))
1276        (t ;; no more iterations
1277           nil))))
1278
1279(defun calculator-funcall (f &optional X Y)
1280  "If F is a symbol, evaluate (F X Y).
1281Otherwise, it should be a list, evaluate it with X, Y bound to the
1282arguments."
1283  ;; remember binary ops for calculator-repR/L
1284  (if Y (setq calculator-last-opXY (list f X Y)))
1285  (condition-case nil
1286      ;; there used to be code here that returns 0 if the result was
1287      ;; smaller than calculator-epsilon (1e-15).  I don't think this is
1288      ;; necessary now.
1289      (if (symbolp f)
1290        (cond ((and X Y) (funcall f X Y))
1291              (X         (funcall f X))
1292              (t         (funcall f)))
1293        ;; f is an expression
1294        (let* ((__f__ f) ; so we can get this value below...
1295               (TX (calculator-truncate X))
1296               (TY (and Y (calculator-truncate Y)))
1297               (DX (if calculator-deg (/ (* X pi) 180) X))
1298               (L  calculator-saved-list)
1299               (Fbound (fboundp 'F))
1300               (Fsave  (and Fbound (symbol-function 'F)))
1301               (Dbound (fboundp 'D))
1302               (Dsave  (and Dbound (symbol-function 'D))))
1303          ;; a shortened version of flet
1304          (fset 'F (function
1305                    (lambda (&optional x y)
1306                      (calculator-funcall __f__ x y))))
1307          (fset 'D (function
1308                    (lambda (x)
1309                      (if calculator-deg (/ (* x 180) pi) x))))
1310          (unwind-protect (eval f)
1311            (if Fbound (fset 'F Fsave) (fmakunbound 'F))
1312            (if Dbound (fset 'D Dsave) (fmakunbound 'D)))))
1313    (error 0)))
1314
1315;;;---------------------------------------------------------------------
1316;;; Input interaction
1317
1318(defun calculator-last-input (&optional keys)
1319  "Last char (or event or event sequence) that was read.
1320Optional string argument KEYS will force using it as the keys entered."
1321  (let ((inp (or keys (this-command-keys))))
1322    (if (or (stringp inp) (not (arrayp inp)))
1323      inp
1324      ;; this translates kp-x to x and [tries to] create a string to
1325      ;; lookup operators
1326      (let* ((i -1) (converted-str (make-string (length inp) ? )) k)
1327        ;; converts an array to a string the ops lookup with keypad
1328        ;; input
1329        (while (< (setq i (1+ i)) (length inp))
1330          (setq k (aref inp i))
1331          ;; if Emacs will someday have a event-key, then this would
1332          ;; probably be modified anyway
1333          (and (if (fboundp 'key-press-event-p) (key-press-event-p k))
1334	       (if (fboundp 'event-key)
1335		   (and (event-key k) (setq k (event-key k)))))
1336          ;; assume all symbols are translatable with an ascii-character
1337          (and (symbolp k)
1338               (setq k (or (get k 'ascii-character) ? )))
1339          (aset converted-str i k))
1340        converted-str))))
1341
1342(defun calculator-clear-fragile (&optional op)
1343  "Clear the fragile flag if it was set, then maybe reset all.
1344OP is the operator (if any) that caused this call."
1345  (if (and calculator-display-fragile
1346           (or (not op)
1347               (= -1 (calculator-op-arity op))
1348               (= 0 (calculator-op-arity op))))
1349    ;; reset if last calc finished, and now get a num or prefix or 0-ary
1350    ;; op
1351    (calculator-reset))
1352  (setq calculator-display-fragile nil))
1353
1354(defun calculator-digit ()
1355  "Enter a single digit."
1356  (interactive)
1357  (let ((inp (aref (calculator-last-input) 0)))
1358    (if (and (or calculator-display-fragile
1359                 (not (numberp (car calculator-stack))))
1360             (cond
1361               ((not calculator-input-radix)     (<= inp ?9))
1362               ((eq calculator-input-radix 'bin) (<= inp ?1))
1363               ((eq calculator-input-radix 'oct) (<= inp ?7))
1364               (t t)))
1365      ;; enter digit if starting a new computation or have an op on the
1366      ;; stack
1367      (progn
1368        (calculator-clear-fragile)
1369        (let ((digit (upcase (char-to-string inp))))
1370          (if (equal calculator-curnum "0")
1371            (setq calculator-curnum nil))
1372          (setq calculator-curnum
1373                (concat (or calculator-curnum "") digit)))
1374        (calculator-update-display)))))
1375
1376(defun calculator-decimal ()
1377  "Enter a decimal period."
1378  (interactive)
1379  (if (and (not calculator-input-radix)
1380           (or calculator-display-fragile
1381               (not (numberp (car calculator-stack))))
1382           (not (and calculator-curnum
1383                     (string-match "[.eE]" calculator-curnum))))
1384    ;; enter the period on the same condition as a digit, only if no
1385    ;; period or exponent entered yet
1386    (progn
1387      (calculator-clear-fragile)
1388      (setq calculator-curnum (concat (or calculator-curnum "0") "."))
1389      (calculator-update-display))))
1390
1391(defun calculator-exp ()
1392  "Enter an `E' exponent character, or a digit in hex input mode."
1393  (interactive)
1394  (if calculator-input-radix
1395    (calculator-digit)
1396    (if (and (or calculator-display-fragile
1397                 (not (numberp (car calculator-stack))))
1398             (not (and calculator-curnum
1399                       (string-match "[eE]" calculator-curnum))))
1400      ;; same condition as above, also no E so far
1401      (progn
1402        (calculator-clear-fragile)
1403        (setq calculator-curnum (concat (or calculator-curnum "1") "e"))
1404        (calculator-update-display)))))
1405
1406(defun calculator-op (&optional keys)
1407  "Enter an operator on the stack, doing all necessary reductions.
1408Optional string argument KEYS will force using it as the keys entered."
1409  (interactive)
1410  (catch 'op-error
1411    (let* ((last-inp (calculator-last-input keys))
1412           (op (assoc last-inp calculator-operators)))
1413      (calculator-clear-fragile op)
1414      (if (and calculator-curnum (/= (calculator-op-arity op) 0))
1415        (setq calculator-stack
1416              (cons (calculator-curnum-value) calculator-stack)))
1417      (setq calculator-curnum nil)
1418      (if (and (= 2 (calculator-op-arity op))
1419               (not (and calculator-stack
1420                         (numberp (nth 0 calculator-stack)))))
1421        ;; we have a binary operator but no number - search for a prefix
1422        ;; version
1423        (let ((rest-ops calculator-operators))
1424          (while (not (equal last-inp (car (car rest-ops))))
1425            (setq rest-ops (cdr rest-ops)))
1426          (setq op (assoc last-inp (cdr rest-ops)))
1427          (if (not (and op (= -1 (calculator-op-arity op))))
1428            ;;(error "Binary operator without a first operand")
1429            (progn
1430              (calculator-message
1431               "Binary operator without a first operand")
1432              (throw 'op-error nil)))))
1433      (calculator-reduce-stack
1434       (cond ((eq (nth 1 op) '\() 10)
1435             ((eq (nth 1 op) '\)) 0)
1436             (t (calculator-op-prec op))))
1437      (if (or (and (= -1 (calculator-op-arity op))
1438                   (numberp (car calculator-stack)))
1439              (and (/= (calculator-op-arity op) -1)
1440                   (/= (calculator-op-arity op) 0)
1441                   (not (numberp (car calculator-stack)))))
1442        ;;(error "Unterminated expression")
1443        (progn
1444          (calculator-message "Unterminated expression")
1445          (throw 'op-error nil)))
1446      (setq calculator-stack (cons op calculator-stack))
1447      (calculator-reduce-stack (calculator-op-prec op))
1448      (and (= (length calculator-stack) 1)
1449           (numberp (nth 0 calculator-stack))
1450           ;; the display is fragile if it contains only one number
1451           (setq calculator-display-fragile t)
1452           ;; add number to the saved-list
1453           calculator-add-saved
1454           (if (= 0 calculator-saved-ptr)
1455             (setq calculator-saved-list
1456                   (cons (car calculator-stack) calculator-saved-list))
1457             (let ((p (nthcdr (1- calculator-saved-ptr)
1458                              calculator-saved-list)))
1459               (setcdr p (cons (car calculator-stack) (cdr p))))))
1460      (calculator-update-display))))
1461
1462(defun calculator-op-or-exp ()
1463  "Either enter an operator or a digit.
1464Used with +/- for entering them as digits in numbers like 1e-3 (there is
1465no need for negative numbers since these are handled by unary
1466operators)."
1467  (interactive)
1468  (if (and (not calculator-display-fragile)
1469           calculator-curnum
1470           (string-match "[eE]$" calculator-curnum))
1471    (calculator-digit)
1472    (calculator-op)))
1473
1474;;;---------------------------------------------------------------------
1475;;; Input/output modes (not display)
1476
1477(defun calculator-dec/deg-mode ()
1478  "Set decimal mode for display & input, if decimal, toggle deg mode."
1479  (interactive)
1480  (if calculator-curnum
1481    (setq calculator-stack
1482          (cons (calculator-curnum-value) calculator-stack)))
1483  (setq calculator-curnum nil)
1484  (if (or calculator-input-radix calculator-output-radix)
1485    (progn (setq calculator-input-radix nil)
1486           (setq calculator-output-radix nil))
1487    ;; already decimal - toggle degrees mode
1488    (setq calculator-deg (not calculator-deg)))
1489  (calculator-update-display t))
1490
1491(defun calculator-radix-mode (&optional keys)
1492  "Set input and display radix modes.
1493Optional string argument KEYS will force using it as the keys entered."
1494  (interactive)
1495  (calculator-radix-input-mode keys)
1496  (calculator-radix-output-mode keys))
1497
1498(defun calculator-radix-input-mode (&optional keys)
1499  "Set input radix modes.
1500Optional string argument KEYS will force using it as the keys entered."
1501  (interactive)
1502  (if calculator-curnum
1503    (setq calculator-stack
1504          (cons (calculator-curnum-value) calculator-stack)))
1505  (setq calculator-curnum nil)
1506  (setq calculator-input-radix
1507        (let ((inp (calculator-last-input keys)))
1508          (cdr (assq (upcase (aref inp (1- (length inp))))
1509                     calculator-char-radix))))
1510  (calculator-update-display))
1511
1512(defun calculator-radix-output-mode (&optional keys)
1513  "Set display radix modes.
1514Optional string argument KEYS will force using it as the keys entered."
1515  (interactive)
1516  (if calculator-curnum
1517    (setq calculator-stack
1518          (cons (calculator-curnum-value) calculator-stack)))
1519  (setq calculator-curnum nil)
1520  (setq calculator-output-radix
1521        (let ((inp (calculator-last-input keys)))
1522          (cdr (assq (upcase (aref inp (1- (length inp))))
1523                     calculator-char-radix))))
1524  (calculator-update-display t))
1525
1526;;;---------------------------------------------------------------------
1527;;; Saved values list
1528
1529(defun calculator-save-on-list ()
1530  "Evaluate current expression, put result on the saved values list."
1531  (interactive)
1532  (let ((calculator-add-saved t)) ; marks the result to be added
1533    (calculator-enter)))
1534
1535(defun calculator-clear-saved ()
1536  "Clear the list of saved values in `calculator-saved-list'."
1537  (interactive)
1538  (setq calculator-saved-list nil)
1539  (setq calculator-saved-ptr 0)
1540  (calculator-update-display t))
1541
1542(defun calculator-saved-move (n)
1543  "Go N elements up the list of saved values."
1544  (interactive)
1545  (and calculator-saved-list
1546       (or (null calculator-stack) calculator-display-fragile)
1547       (progn
1548         (setq calculator-saved-ptr
1549               (max (min (+ n calculator-saved-ptr)
1550                         (length calculator-saved-list))
1551                    0))
1552         (if (nth calculator-saved-ptr calculator-saved-list)
1553           (setq calculator-stack
1554                 (list (nth calculator-saved-ptr calculator-saved-list))
1555                 calculator-display-fragile t)
1556           (calculator-reset))
1557         (calculator-update-display))))
1558
1559(defun calculator-saved-up ()
1560  "Go up the list of saved values."
1561  (interactive)
1562  (calculator-saved-move +1))
1563
1564(defun calculator-saved-down ()
1565  "Go down the list of saved values."
1566  (interactive)
1567  (calculator-saved-move -1))
1568
1569;;;---------------------------------------------------------------------
1570;;; Misc functions
1571
1572(defun calculator-open-paren ()
1573  "Equivalents of `(' use this."
1574  (interactive)
1575  (calculator-op "("))
1576
1577(defun calculator-close-paren ()
1578  "Equivalents of `)' use this."
1579  (interactive)
1580  (calculator-op ")"))
1581
1582(defun calculator-enter ()
1583  "Evaluate current expression."
1584  (interactive)
1585  (calculator-op "="))
1586
1587(defun calculator-backspace ()
1588  "Backward delete a single digit or a stack element."
1589  (interactive)
1590  (if calculator-curnum
1591    (setq calculator-curnum
1592          (if (> (length calculator-curnum) 1)
1593            (substring calculator-curnum
1594                       0 (1- (length calculator-curnum)))
1595            nil))
1596    (setq calculator-stack (cdr calculator-stack)))
1597  (calculator-update-display))
1598
1599(defun calculator-clear ()
1600  "Clear current number."
1601  (interactive)
1602  (setq calculator-curnum nil)
1603  (cond
1604    ;; if the current number is from the saved-list - remove it
1605    ((and calculator-display-fragile
1606          calculator-saved-list
1607          (= (car calculator-stack)
1608             (nth calculator-saved-ptr calculator-saved-list)))
1609     (if (= 0 calculator-saved-ptr)
1610       (setq calculator-saved-list (cdr calculator-saved-list))
1611       (let ((p (nthcdr (1- calculator-saved-ptr)
1612                        calculator-saved-list)))
1613         (setcdr p (cdr (cdr p)))
1614         (setq calculator-saved-ptr (1- calculator-saved-ptr))))
1615     (if calculator-saved-list
1616       (setq calculator-stack
1617             (list (nth calculator-saved-ptr calculator-saved-list)))
1618       (calculator-reset)))
1619    ;; reset if fragile or double clear
1620    ((or calculator-display-fragile (eq last-command this-command))
1621     (calculator-reset)))
1622  (calculator-update-display))
1623
1624(defun calculator-copy ()
1625  "Copy current number to the `kill-ring'."
1626  (interactive)
1627  (let ((calculator-displayer
1628         (or calculator-copy-displayer calculator-displayer))
1629        (calculator-displayers
1630         (if calculator-copy-displayer nil calculator-displayers)))
1631    (calculator-enter)
1632    ;; remove trailing spaces and an index
1633    (let ((s (cdr calculator-stack-display)))
1634      (and s
1635           (if (string-match "^\\([^ ]+\\) *\\(\\[[0-9/]+\\]\\)? *$" s)
1636             (setq s (match-string 1 s)))
1637           (kill-new s)))))
1638
1639(defun calculator-set-register (reg)
1640  "Set a register value for REG."
1641  (interactive "cRegister to store into: ")
1642  (let* ((as  (assq reg calculator-registers))
1643         (val (progn (calculator-enter) (car calculator-stack))))
1644    (if as
1645      (setcdr as val)
1646      (setq calculator-registers
1647            (cons (cons reg val) calculator-registers)))
1648    (calculator-message "[%c] := %S" reg val)))
1649
1650(defun calculator-put-value (val)
1651  "Paste VAL as if entered.
1652Used by `calculator-paste' and `get-register'."
1653  (if (and (numberp val)
1654           ;; (not calculator-curnum)
1655           (or calculator-display-fragile
1656               (not (numberp (car calculator-stack)))))
1657    (progn
1658      (calculator-clear-fragile)
1659      (setq calculator-curnum (let ((calculator-displayer "%S"))
1660                                (calculator-number-to-string val)))
1661      (calculator-update-display))))
1662
1663(defun calculator-paste ()
1664  "Paste a value from the `kill-ring'."
1665  (interactive)
1666  (calculator-put-value
1667   (let ((str (replace-regexp-in-string
1668               "^ *\\(.+[^ ]\\) *$" "\\1" (current-kill 0))))
1669     (and (not calculator-input-radix)
1670          calculator-paste-decimals
1671          (string-match "\\([0-9]+\\)\\(\\.[0-9]+\\)?\\(e[0-9]+\\)?"
1672                        str)
1673          (or (match-string 1 str)
1674              (match-string 2 str)
1675              (match-string 3 str))
1676          (setq str (concat (or (match-string 1 str) "0")
1677                            (or (match-string 2 str) ".0")
1678                            (or (match-string 3 str) ""))))
1679     (condition-case nil (calculator-string-to-number str)
1680       (error nil)))))
1681
1682(defun calculator-get-register (reg)
1683  "Get a value from a register REG."
1684  (interactive "cRegister to get value from: ")
1685  (calculator-put-value (cdr (assq reg calculator-registers))))
1686
1687(defun calculator-help ()
1688  ;; this is used as the quick reference screen you get with `h'
1689  "Quick reference:
1690* numbers/operators/parens/./e - enter expressions
1691  + - * / \\(div) %(rem) _(-X,postfix) ;(1/X,postfix) ^(exp) L(og)
1692  Q(sqrt) !(fact) S(in) C(os) T(an) |(or) #(xor) &(and) ~(not)
1693* >/< repeats last binary operation with its 2nd (1st) arg as postfix op
1694* I inverses next trig function        * '/\"/{} - display/display args
1695* D         - switch to all-decimal, or toggle deg/rad mode
1696* B/O/H/X   - binary/octal/hex mode for i/o (X is a shortcut for H)
1697* i/o       - prefix for d/b/o/x - set only input/output modes
1698* enter/=   - evaluate current expr.   * s/g      - set/get a register
1699* space     - evaluate & save on list  * l/v      - list total/average
1700* up/down/C-p/C-n - browse saved       * C-delete - clear all saved
1701* C-insert  - copy whole expr.         * C-return - evaluate, copy, exit
1702* insert    - paste a number           * backspace- delete backwards
1703* delete    - clear argument or list value or whole expression (twice)
1704* escape/q  - exit."
1705  (interactive)
1706  (if (eq last-command 'calculator-help)
1707    (let ((mode-name "Calculator")
1708          (major-mode 'calculator-mode)
1709          (g-map (current-global-map))
1710          (win (selected-window)))
1711      (require 'ehelp)
1712      (if calculator-electric-mode
1713        (use-global-map calculator-saved-global-map))
1714      (if (or (not calculator-electric-mode)
1715              ;; XEmacs has a problem with electric-describe-mode
1716              (string-match "XEmacs" (emacs-version)))
1717        (describe-mode)
1718        (electric-describe-mode))
1719      (if calculator-electric-mode
1720        (use-global-map g-map))
1721      (select-window win) ; these are for XEmacs (also below)
1722      (message nil))
1723    (let ((one (one-window-p t))
1724          (win (selected-window))
1725          (help-buf (get-buffer-create "*Help*")))
1726      (save-window-excursion
1727        (with-output-to-temp-buffer "*Help*"
1728          (princ (documentation 'calculator-help)))
1729        (if one
1730          (shrink-window-if-larger-than-buffer
1731           (get-buffer-window help-buf)))
1732        (message
1733         "`%s' again for more help, any other key continues normally."
1734         (calculator-last-input))
1735        (select-window win)
1736        (sit-for 360))
1737      (select-window win))))
1738
1739(defun calculator-quit ()
1740  "Quit calculator."
1741  (interactive)
1742  (set-buffer calculator-buffer)
1743  (let ((inhibit-read-only t)) (erase-buffer))
1744  (if (not calculator-electric-mode)
1745    (progn
1746      (condition-case nil
1747          (while (get-buffer-window calculator-buffer)
1748            (delete-window (get-buffer-window calculator-buffer)))
1749        (error nil))
1750      (kill-buffer calculator-buffer)))
1751  (setq calculator-buffer nil)
1752  (message "Calculator done.")
1753  (if calculator-electric-mode (throw 'calculator-done nil)))
1754
1755(defun calculator-save-and-quit ()
1756  "Quit the calculator, saving the result on the `kill-ring'."
1757  (interactive)
1758  (calculator-enter)
1759  (calculator-copy)
1760  (calculator-quit))
1761
1762(defun calculator-repR (x)
1763  "Repeats the last binary operation with its second 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) x (nth 2 calculator-last-opXY)))
1770    x))
1771
1772(defun calculator-repL (x)
1773  "Repeats the last binary operation with its first argument and X.
1774To use this, apply a binary operator (evaluate it), then call this."
1775  (if calculator-last-opXY
1776    ;; avoid rebinding calculator-last-opXY
1777    (let ((calculator-last-opXY calculator-last-opXY))
1778      (calculator-funcall
1779       (car calculator-last-opXY) (nth 1 calculator-last-opXY) x))
1780    x))
1781
1782(defun calculator-fact (x)
1783  "Simple factorial of X."
1784  (let ((r (if (<= x 10) 1 1.0)))
1785    (while (> x 0)
1786      (setq r (* r (truncate x)))
1787      (setq x (1- x)))
1788    (+ 0.0 r)))
1789
1790(defun calculator-truncate (n)
1791  "Truncate N, return 0 in case of overflow."
1792  (condition-case nil (truncate n) (error 0)))
1793
1794
1795(provide 'calculator)
1796
1797;;; arch-tag: a1b9766c-af8a-4a74-b466-65ad8eeb0c73
1798;;; calculator.el ends here
1799