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