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