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