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