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