/
calculator.el
1826 lines (1672 loc) · 73.3 KB
/
calculator.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; calculator.el --- a [not so] simple calculator for Emacs
;; Copyright (C) 1998, 2000-2011 Free Software Foundation, Inc.
;; Author: Eli Barzilay <eli@barzilay.org>
;; Keywords: tools, convenience
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;;=====================================================================
;;; Commentary:
;;
;; A calculator for Emacs.
;; Why should you reach for your mouse to get xcalc (calc.exe, gcalc or
;; whatever), when you have Emacs running already?
;;
;; If this is not part of your Emacs distribution, then simply bind
;; `calculator' to a key and make it an autoloaded function, e.g.:
;; (autoload 'calculator "calculator"
;; "Run the Emacs calculator." t)
;; (global-set-key [(control return)] 'calculator)
;;
;; Written by Eli Barzilay: Maze is Life! eli@barzilay.org
;; http://www.barzilay.org/
;;
;; For latest version, check
;; http://www.barzilay.org/misc/calculator.el
;;
;;; History:
;; I hate history.
(eval-when-compile (require 'cl))
;;;=====================================================================
;;; Customization:
(defgroup calculator nil
"Simple Emacs calculator."
:prefix "calculator"
:version "21.1"
:group 'tools
:group 'applications)
(defcustom calculator-electric-mode nil
"Run `calculator' electrically, in the echo area.
Electric mode saves some place but changes the way you interact with the
calculator."
:type 'boolean
:group 'calculator)
(defcustom calculator-use-menu t
"Make `calculator' create a menu.
Note that this requires easymenu. Must be set before loading."
:type 'boolean
:group 'calculator)
(defcustom calculator-bind-escape nil
"If non-nil, set escape to exit the calculator."
:type 'boolean
:group 'calculator)
(defcustom calculator-unary-style 'postfix
"Value is either 'prefix or 'postfix.
This determines the default behavior of unary operators."
:type '(choice (const prefix) (const postfix))
:group 'calculator)
(defcustom calculator-prompt "Calc=%s> "
"The prompt used by the Emacs calculator.
It should contain a \"%s\" somewhere that will indicate the i/o radixes;
this will be a two-character string as described in the documentation
for `calculator-mode'."
:type 'string
:group 'calculator)
(defcustom calculator-number-digits 3
"The calculator's number of digits used for standard display.
Used by the `calculator-standard-display' function - it will use the
format string \"%.NC\" where this number is N and C is a character given
at runtime."
:type 'integer
:group 'calculator)
(defcustom calculator-radix-grouping-mode t
"Use digit grouping in radix output mode.
If this is set, chunks of `calculator-radix-grouping-digits' characters
will be separated by `calculator-radix-grouping-separator' when in radix
output mode is active (determined by `calculator-output-radix')."
:type 'boolean
:group 'calculator)
(defcustom calculator-radix-grouping-digits 4
"The number of digits used for grouping display in radix modes.
See `calculator-radix-grouping-mode'."
:type 'integer
:group 'calculator)
(defcustom calculator-radix-grouping-separator "'"
"The separator used in radix grouping display.
See `calculator-radix-grouping-mode'."
:type 'string
:group 'calculator)
(defcustom calculator-remove-zeros t
"Non-nil value means delete all redundant zero decimal digits.
If this value is not t, and not nil, redundant zeros are removed except
for one and if it is nil, nothing is removed.
Used by the `calculator-remove-zeros' function."
:type '(choice (const t) (const leave-decimal) (const nil))
:group 'calculator)
(defcustom calculator-displayer '(std ?n)
"A displayer specification for numerical values.
This is the displayer used to show all numbers in an expression. Result
values will be displayed according to the first element of
`calculator-displayers'.
The displayer is a symbol, a string or an expression. A symbol should
be the name of a one-argument function, a string is used with a single
argument and an expression will be evaluated with the variable `num'
bound to whatever should be displayed. If it is a function symbol, it
should be able to handle special symbol arguments, currently 'left and
'right which will be sent by special keys to modify display parameters
associated with the displayer function (for example to change the number
of digits displayed).
An exception to the above is the case of the list (std C) where C is a
character, in this case the `calculator-standard-displayer' function
will be used with this character for a format string."
:group 'calculator)
(defcustom calculator-displayers
'(((std ?n) "Standard display, decimal point or scientific")
(calculator-eng-display "Eng display")
((std ?f) "Standard display, decimal point")
((std ?e) "Standard display, scientific")
("%S" "Emacs printer"))
"A list of displayers.
Each element is a list of a displayer and a description string. The
first element is the one which is currently used, this is for the display
of result values not values in expressions. A displayer specification
is the same as the values that can be stored in `calculator-displayer'.
`calculator-rotate-displayer' rotates this list."
:type 'sexp
:group 'calculator)
(defcustom calculator-paste-decimals t
"If non-nil, convert pasted integers so they have a decimal point.
This makes it possible to paste big integers since they will be read as
floats, otherwise the Emacs reader will fail on them."
:type 'boolean
:group 'calculator)
(defcustom calculator-copy-displayer nil
"If non-nil, this is any value that can be used for
`calculator-displayer', to format a string before copying it with
`calculator-copy'. If nil, then `calculator-displayer's normal value is
used."
:type 'boolean
:group 'calculator)
(defcustom calculator-2s-complement nil
"If non-nil, show negative numbers in 2s complement in radix modes.
Otherwise show as a negative number."
:type 'boolean
:group 'calculator)
(defcustom calculator-mode-hook nil
"List of hook functions for `calculator-mode' to run.
Note: if `calculator-electric-mode' is on, then this hook will get
activated in the minibuffer - in that case it should not do much more
than local key settings and other effects that will change things
outside the scope of calculator related code."
:type 'hook
:group 'calculator)
(defcustom calculator-user-registers nil
"An association list of user-defined register bindings.
Each element in this list is a list of a character and a number that
will be stored in that character's register.
For example, use this to define the golden ratio number:
(setq calculator-user-registers '((?g . 1.61803398875)))
before you load calculator."
:type '(repeat (cons character number))
:set (lambda (_ val)
(and (boundp 'calculator-registers)
(setq calculator-registers
(append val calculator-registers)))
(setq calculator-user-registers val))
:group 'calculator)
(defcustom calculator-user-operators nil
"A list of additional operators.
This is a list in the same format as specified in the documentation for
`calculator-operators', that you can use to bind additional calculator
operators. It is probably not a good idea to modify this value with
`customize' since it is too complex...
Examples:
* A very simple one, adding a postfix \"x-to-y\" conversion keys, using
t as a prefix key:
(setq calculator-user-operators
'((\"tf\" cl-to-fr (+ 32 (/ (* X 9) 5)) 1)
(\"tc\" fr-to-cl (/ (* (- X 32) 5) 9) 1)
(\"tp\" kg-to-lb (/ X 0.453592) 1)
(\"tk\" lb-to-kg (* X 0.453592) 1)
(\"tF\" mt-to-ft (/ X 0.3048) 1)
(\"tM\" ft-to-mt (* X 0.3048) 1)))
* Using a function-like form is very simple, X for an argument (Y the
second in case of a binary operator), TX is a truncated version of X
and F does a recursive call, Here is a [very inefficient] Fibonacci
number calculation:
(add-to-list 'calculator-user-operators
'(\"F\" fib (if (<= TX 1)
1
(+ (F (- TX 1)) (F (- TX 2)))) 0))
Note that this will be either postfix or prefix, according to
`calculator-unary-style'."
:type '(repeat (list string symbol sexp integer integer))
:group 'calculator)
;;;=====================================================================
;;; Code:
;;;---------------------------------------------------------------------
;;; Variables
(defvar calculator-initial-operators
'(;; "+"/"-" have keybindings of themselves, not calculator-ops
("=" = identity 1 -1)
(nobind "+" + + 2 4)
(nobind "-" - - 2 4)
(nobind "+" + + -1 9)
(nobind "-" - - -1 9)
("(" \( identity -1 -1)
(")" \) identity +1 10)
;; normal keys
("|" or (logior TX TY) 2 2)
("#" xor (logxor TX TY) 2 2)
("&" and (logand TX TY) 2 3)
("*" * * 2 5)
("/" / / 2 5)
("\\" div (/ TX TY) 2 5)
("%" rem (% TX TY) 2 5)
("L" log log 2 6)
("S" sin (sin DX) x 6)
("C" cos (cos DX) x 6)
("T" tan (tan DX) x 6)
("IS" asin (D (asin X)) x 6)
("IC" acos (D (acos X)) x 6)
("IT" atan (D (atan X)) x 6)
("Q" sqrt sqrt x 7)
("^" ^ calculator-expt 2 7)
("!" ! calculator-fact x 7)
(";" 1/ (/ 1 X) 1 7)
("_" - - 1 8)
("~" ~ (lognot TX) x 8)
(">" repR calculator-repR 1 8)
("<" repL calculator-repL 1 8)
("v" avg (/ (apply '+ L) (length L)) 0 8)
("l" tot (apply '+ L) 0 8)
)
"A list of initial operators.
This is a list in the same format as `calculator-operators'. Whenever
`calculator' starts, it looks at the value of this variable, and if it
is not empty, its contents is prepended to `calculator-operators' and
the appropriate key bindings are made.
This variable is then reset to nil. Don't use this if you want to add
user-defined operators, use `calculator-user-operators' instead.")
(defvar calculator-operators nil
"The calculator operators, each a list with:
1. The key that is bound to for this operation (usually a string);
2. The displayed symbol for this function;
3. The function symbol, or a form that uses the variables `X' and `Y',
(if it is a binary operator), `TX' and `TY' (truncated integer
versions), `DX' (converted to radians if degrees mode is on), `D'
(function for converting radians to degrees if deg mode is on), `L'
(list of saved values), `F' (function for recursive iteration calls)
and evaluates to the function value - these variables are capital;
4. The function's arity, optional, one of: 2 => binary, -1 => prefix
unary, +1 => postfix unary, 0 => a 0-arg operator func, non-number =>
postfix/prefix as determined by `calculator-unary-style' (the
default);
5. The function's precedence - should be in the range of 1 (lowest) to
9 (highest) (optional, defaults to 1);
It it possible have a unary prefix version of a binary operator if it
comes later in this list. If the list begins with the symbol 'nobind,
then no key binding will take place - this is only useful for predefined
keys.
Use `calculator-user-operators' to add operators to this list, see its
documentation for an example.")
(defvar calculator-stack nil
"Stack contents - operations and operands.")
(defvar calculator-curnum nil
"Current number being entered (as a string).")
(defvar calculator-stack-display nil
"Cons of the stack and its string representation.")
(defvar calculator-char-radix
'((?D . nil) (?B . bin) (?O . oct) (?H . hex) (?X . hex))
"A table to convert input characters to corresponding radix symbols.")
(defvar calculator-output-radix nil
"The mode for display, one of: nil (decimal), 'bin, 'oct or 'hex.")
(defvar calculator-input-radix nil
"The mode for input, one of: nil (decimal), 'bin, 'oct or 'hex.")
(defvar calculator-deg nil
"Non-nil if trig functions operate on degrees instead of radians.")
(defvar calculator-saved-list nil
"A list of saved values collected.")
(defvar calculator-saved-ptr 0
"The pointer to the current saved number.")
(defvar calculator-add-saved nil
"Bound to t when a value should be added to the saved-list.")
(defvar calculator-display-fragile nil
"When non-nil, we see something that the next digit should replace.")
(defvar calculator-buffer nil
"The current calculator buffer.")
(defvar calculator-eng-extra nil
"Internal value used by `calculator-eng-display'.")
(defvar calculator-eng-tmp-show nil
"Internal value used by `calculator-eng-display'.")
(defvar calculator-last-opXY nil
"The last binary operation and its arguments.
Used for repeating operations in calculator-repR/L.")
(defvar calculator-registers ; use user-bindings first
(append calculator-user-registers
(list (cons ?e float-e) (cons ?p float-pi)))
"The association list of calculator register values.")
(defvar calculator-saved-global-map nil
"Saved global key map.")
(defvar calculator-restart-other-mode nil
"Used to hack restarting with the electric mode changed.")
;;;---------------------------------------------------------------------
;;; Key bindings
(defvar calculator-mode-map
(let ((map (make-sparse-keymap)))
(suppress-keymap map t)
(define-key map "i" nil)
(define-key map "o" nil)
(let ((p
'((calculator-open-paren "[")
(calculator-close-paren "]")
(calculator-op-or-exp "+" "-" [kp-add] [kp-subtract])
(calculator-digit "0" "1" "2" "3" "4" "5" "6" "7" "8"
"9" "a" "b" "c" "d" "f"
[kp-0] [kp-1] [kp-2] [kp-3] [kp-4]
[kp-5] [kp-6] [kp-7] [kp-8] [kp-9])
(calculator-op [kp-divide] [kp-multiply])
(calculator-decimal "." [kp-decimal])
(calculator-exp "e")
(calculator-dec/deg-mode "D")
(calculator-set-register "s")
(calculator-get-register "g")
(calculator-radix-mode "H" "X" "O" "B")
(calculator-radix-input-mode "id" "ih" "ix" "io" "ib"
"iD" "iH" "iX" "iO" "iB")
(calculator-radix-output-mode "od" "oh" "ox" "oo" "ob"
"oD" "oH" "oX" "oO" "oB")
(calculator-rotate-displayer "'")
(calculator-rotate-displayer-back "\"")
(calculator-displayer-prev "{")
(calculator-displayer-next "}")
(calculator-saved-up [up] [?\C-p])
(calculator-saved-down [down] [?\C-n])
(calculator-quit "q" [?\C-g])
(calculator-enter [enter] [linefeed] [kp-enter]
[return] [?\r] [?\n])
(calculator-save-on-list " " [space])
(calculator-clear-saved [?\C-c] [(control delete)])
(calculator-save-and-quit [(control return)]
[(control kp-enter)])
(calculator-paste [insert] [(shift insert)]
[paste] [mouse-2] [?\C-y])
(calculator-clear [delete] [?\C-?] [?\C-d])
(calculator-help [?h] [??] [f1] [help])
(calculator-copy [(control insert)] [copy])
(calculator-backspace [backspace])
)))
(while p
;; reverse the keys so first defs come last - makes the more
;; sensible bindings visible in the menu
(let ((func (car (car p))) (keys (reverse (cdr (car p)))))
(while keys
(define-key map (car keys) func)
(setq keys (cdr keys))))
(setq p (cdr p))))
(if calculator-bind-escape
(progn (define-key map [?\e] 'calculator-quit)
(define-key map [escape] 'calculator-quit))
(define-key map [?\e ?\e ?\e] 'calculator-quit))
;; make C-h work in text-mode
(or window-system (define-key map [?\C-h] 'calculator-backspace))
;; set up a menu
(if (and calculator-use-menu (not (boundp 'calculator-menu)))
(let ((radix-selectors
(mapcar (lambda (x)
`([,(nth 0 x)
(calculator-radix-mode ,(nth 2 x))
:style radio
:keys ,(nth 2 x)
:selected
(and
(eq calculator-input-radix ',(nth 1 x))
(eq calculator-output-radix ',(nth 1 x)))]
[,(concat (nth 0 x) " Input")
(calculator-radix-input-mode ,(nth 2 x))
:keys ,(concat "i" (downcase (nth 2 x)))
:style radio
:selected
(eq calculator-input-radix ',(nth 1 x))]
[,(concat (nth 0 x) " Output")
(calculator-radix-output-mode ,(nth 2 x))
:keys ,(concat "o" (downcase (nth 2 x)))
:style radio
:selected
(eq calculator-output-radix ',(nth 1 x))]))
'(("Decimal" nil "D")
("Binary" bin "B")
("Octal" oct "O")
("Hexadecimal" hex "H"))))
(op (lambda (name key)
`[,name (calculator-op ,key) :keys ,key])))
(easy-menu-define
calculator-menu map "Calculator menu."
`("Calculator"
["Help"
(let ((last-command 'calculator-help)) (calculator-help))
:keys "?"]
"---"
["Copy" calculator-copy]
["Paste" calculator-paste]
"---"
["Electric mode"
(progn (calculator-quit)
(setq calculator-restart-other-mode t)
(run-with-timer 0.1 nil (lambda () (message nil)))
;; the message from the menu will be visible,
;; couldn't make it go away...
(calculator))
:active (not calculator-electric-mode)]
["Normal mode"
(progn (setq calculator-restart-other-mode t)
(calculator-quit))
:active calculator-electric-mode]
"---"
("Functions"
,(funcall op "Repeat-right" ">")
,(funcall op "Repeat-left" "<")
"------General------"
,(funcall op "Reciprocal" ";")
,(funcall op "Log" "L")
,(funcall op "Square-root" "Q")
,(funcall op "Factorial" "!")
"------Trigonometric------"
,(funcall op "Sinus" "S")
,(funcall op "Cosine" "C")
,(funcall op "Tangent" "T")
,(funcall op "Inv-Sinus" "IS")
,(funcall op "Inv-Cosine" "IC")
,(funcall op "Inv-Tangent" "IT")
"------Bitwise------"
,(funcall op "Or" "|")
,(funcall op "Xor" "#")
,(funcall op "And" "&")
,(funcall op "Not" "~"))
("Saved List"
["Eval+Save" calculator-save-on-list]
["Prev number" calculator-saved-up]
["Next number" calculator-saved-down]
["Delete current" calculator-clear
:active (and calculator-display-fragile
calculator-saved-list
(= (car calculator-stack)
(nth calculator-saved-ptr
calculator-saved-list)))]
["Delete all" calculator-clear-saved]
"---"
,(funcall op "List-total" "l")
,(funcall op "List-average" "v"))
("Registers"
["Get register" calculator-get-register]
["Set register" calculator-set-register])
("Modes"
["Radians"
(progn
(and (or calculator-input-radix calculator-output-radix)
(calculator-radix-mode "D"))
(and calculator-deg (calculator-dec/deg-mode)))
:keys "D"
:style radio
:selected (not (or calculator-input-radix
calculator-output-radix
calculator-deg))]
["Degrees"
(progn
(and (or calculator-input-radix calculator-output-radix)
(calculator-radix-mode "D"))
(or calculator-deg (calculator-dec/deg-mode)))
:keys "D"
:style radio
:selected (and calculator-deg
(not (or calculator-input-radix
calculator-output-radix)))]
"---"
,@(mapcar 'car radix-selectors)
("Separate I/O"
,@(mapcar (lambda (x) (nth 1 x)) radix-selectors)
"---"
,@(mapcar (lambda (x) (nth 2 x)) radix-selectors)))
("Decimal Display"
,@(mapcar (lambda (d)
(vector (cadr d)
;; Note: inserts actual object here
`(calculator-rotate-displayer ',d)))
calculator-displayers)
"---"
["Change Prev Display" calculator-displayer-prev]
["Change Next Display" calculator-displayer-next])
"---"
["Copy+Quit" calculator-save-and-quit]
["Quit" calculator-quit]))))
map)
"The calculator key map.")
;;;---------------------------------------------------------------------
;;; Startup and mode stuff
(define-derived-mode calculator-mode fundamental-mode "Calculator"
;; this help is also used as the major help screen
"A [not so] simple calculator for Emacs.
This calculator is used in the same way as other popular calculators
like xcalc or calc.exe - but using an Emacs interface.
Expressions are entered using normal infix notation, parens are used as
normal. Unary functions are usually postfix, but some depends on the
value of `calculator-unary-style' (if the style for an operator below is
specified, then it is fixed, otherwise it depends on this variable).
`+' and `-' can be used as either binary operators or prefix unary
operators. Numbers can be entered with exponential notation using `e',
except when using a non-decimal radix mode for input (in this case `e'
will be the hexadecimal digit). If the result of a calculation is too
large (out of range for Emacs), the value of \"inf\" is returned.
Here are the editing keys:
* `RET' `=' evaluate the current expression
* `C-insert' copy the whole current expression to the `kill-ring'
* `C-return' evaluate, save result the `kill-ring' and exit
* `insert' paste a number if the one was copied (normally)
* `delete' `C-d' clear last argument or whole expression (hit twice)
* `backspace' delete a digit or a previous expression element
* `h' `?' pop-up a quick reference help
* `ESC' `q' exit (`ESC' can be used if `calculator-bind-escape' is
non-nil, otherwise use three consecutive `ESC's)
These operators are pre-defined:
* `+' `-' `*' `/' the common binary operators
* `\\' `%' integer division and reminder
* `_' `;' postfix unary negation and reciprocal
* `^' `L' binary operators for x^y and log(x) in base y
* `Q' `!' unary square root and factorial
* `S' `C' `T' unary trigonometric operators - sin, cos and tan
* `|' `#' `&' `~' bitwise operators - or, xor, and, not
The trigonometric functions can be inverted if prefixed with an `I', see
below for the way to use degrees instead of the default radians.
Two special postfix unary operators are `>' and `<': whenever a binary
operator is performed, it is remembered along with its arguments; then
`>' (`<') will apply the same operator with the same right (left)
argument.
hex/oct/bin modes can be set for input and for display separately.
Another toggle-able mode is for using degrees instead of radians for
trigonometric functions.
The keys to switch modes are (`X' is shortcut for `H'):
* `D' switch to all-decimal mode, or toggle degrees/radians
* `B' `O' `H' `X' binary/octal/hexadecimal modes for input & display
* `i' `o' followed by one of `D' `B' `O' `H' `X' (case
insensitive) sets only the input or display radix mode
The prompt indicates the current modes:
* \"D=\": degrees mode;
* \"?=\": (? is B/O/H) this is the radix for both input and output;
* \"=?\": (? is B/O/H) the display radix (when input is decimal);
* \"??\": (? is D/B/O/H) 1st char for input radix, 2nd for display.
Also, the quote key can be used to switch display modes for decimal
numbers (double-quote rotates back), and the two brace characters
\(\"{\" and \"}\" change display parameters that these displayers use (if
they handle such). If output is using any radix mode, then these keys
toggle digit grouping mode and the chunk size.
Values can be saved for future reference in either a list of saved
values, or in registers.
The list of saved values is useful for statistics operations on some
collected data. It is possible to navigate in this list, and if the
value shown is the current one on the list, an indication is displayed
as \"[N]\" if this is the last number and there are N numbers, or
\"[M/N]\" if the M-th value is shown.
* `SPC' evaluate the current value as usual, but also adds
the result to the list of saved values
* `l' `v' computes total / average of saved values
* `up' `C-p' browse to the previous value in the list
* `down' `C-n' browse to the next value in the list
* `delete' `C-d' remove current value from the list (if it is on it)
* `C-delete' `C-c' delete the whole list
Registers are variable-like place-holders for values:
* `s' followed by a character attach the current value to that character
* `g' followed by a character fetches the attached value
There are many variables that can be used to customize the calculator.
Some interesting customization variables are:
* `calculator-electric-mode' use only the echo-area electrically.
* `calculator-unary-style' set most unary ops to pre/postfix style.
* `calculator-user-registers' to define user-preset registers.
* `calculator-user-operators' to add user-defined operators.
See the documentation for these variables, and \"calculator.el\" for
more information.
\\{calculator-mode-map}")
(eval-when-compile (require 'electric) (require 'ehelp))
;;;###autoload
(defun calculator ()
"Run the Emacs calculator.
See the documentation for `calculator-mode' for more information."
(interactive)
(if calculator-restart-other-mode
(setq calculator-electric-mode (not calculator-electric-mode)))
(if calculator-initial-operators
(progn (calculator-add-operators calculator-initial-operators)
(setq calculator-initial-operators nil)
;; don't change this since it is a customization variable,
;; its set function will add any new operators
(calculator-add-operators calculator-user-operators)))
(setq calculator-buffer (get-buffer-create "*calculator*"))
(if calculator-electric-mode
(save-window-excursion
(progn (require 'electric) (message nil)) ; hide load message
(let (old-g-map old-l-map (echo-keystrokes 0)
(garbage-collection-messages nil)) ; no gc msg when electric
(set-window-buffer (minibuffer-window) calculator-buffer)
(select-window (minibuffer-window))
(calculator-reset)
(calculator-update-display)
(setq old-l-map (current-local-map))
(setq old-g-map (current-global-map))
(setq calculator-saved-global-map (current-global-map))
(use-local-map nil)
(use-global-map calculator-mode-map)
(run-hooks 'calculator-mode-hook)
(unwind-protect
(catch 'calculator-done
(Electric-command-loop
'calculator-done
;; can't use 'noprompt, bug in electric.el
(lambda () 'noprompt)
nil
(lambda (x y) (calculator-update-display))))
(and calculator-buffer
(catch 'calculator-done (calculator-quit)))
(use-local-map old-l-map)
(use-global-map old-g-map))))
(progn
(cond
((not (get-buffer-window calculator-buffer))
(let ((window-min-height 2))
;; maybe leave two lines for our window because of the normal
;; `raised' modeline in Emacs 21
(select-window
(split-window-vertically
;; If the modeline might interfere with the calculator buffer,
;; use 3 lines instead.
(if (and (fboundp 'face-attr-construct)
(let* ((dh (plist-get (face-attr-construct 'default) :height))
(mf (face-attr-construct 'modeline))
(mh (plist-get mf :height)))
;; If the modeline is shorter than the default,
;; stick with 2 lines. (It may be necessary to
;; check how much shorter.)
(and
(not
(or (and (integerp dh)
(integerp mh)
(< mh dh))
(and (numberp mh)
(not (integerp mh))
(< mh 1))))
(or
;; If the modeline is taller than the default,
;; use 3 lines.
(and (integerp dh)
(integerp mh)
(> mh dh))
(and (numberp mh)
(not (integerp mh))
(> mh 1))
;; If the modeline has a box with non-negative line-width,
;; use 3 lines.
(let* ((bx (plist-get mf :box))
(lh (plist-get bx :line-width)))
(and bx
(or
(not lh)
(> lh 0))))
;; If the modeline has an overline, use 3 lines.
(plist-get (face-attr-construct 'modeline) :overline)))))
-3 -2)))
(switch-to-buffer calculator-buffer)))
((not (eq (current-buffer) calculator-buffer))
(select-window (get-buffer-window calculator-buffer))))
(calculator-mode)
(setq buffer-read-only t)
(calculator-reset)
(message "Hit `?' For a quick help screen.")))
(if (and calculator-restart-other-mode calculator-electric-mode)
(calculator)))
(defun calculator-message (string &rest arguments)
"Same as `message', but special handle of electric mode."
(apply 'message string arguments)
(if calculator-electric-mode
(progn (sit-for 1) (message nil))))
;;;---------------------------------------------------------------------
;;; Operators
(defun calculator-op-arity (op)
"Return OP's arity, 2, +1 or -1."
(let ((arity (or (nth 3 op) 'x)))
(if (numberp arity)
arity
(if (eq calculator-unary-style 'postfix) +1 -1))))
(defun calculator-op-prec (op)
"Return OP's precedence for reducing when inserting into the stack.
Defaults to 1."
(or (nth 4 op) 1))
(defun calculator-add-operators (more-ops)
"This function handles operator addition.
Adds MORE-OPS to `calculator-operator', called initially to handle
`calculator-initial-operators' and `calculator-user-operators'."
(let ((added-ops nil))
(while more-ops
(or (eq (car (car more-ops)) 'nobind)
(let ((i -1) (key (car (car more-ops))))
;; make sure the key is undefined, so it's easy to define
;; prefix keys
(while (< (setq i (1+ i)) (length key))
(or (keymapp
(lookup-key calculator-mode-map
(substring key 0 (1+ i))))
(progn
(define-key
calculator-mode-map (substring key 0 (1+ i)) nil)
(setq i (length key)))))
(define-key calculator-mode-map key 'calculator-op)))
(setq added-ops (cons (if (eq (car (car more-ops)) 'nobind)
(cdr (car more-ops))
(car more-ops))
added-ops))
(setq more-ops (cdr more-ops)))
;; added-ops come first, but in correct order
(setq calculator-operators
(append (nreverse added-ops) calculator-operators))))
;;;---------------------------------------------------------------------
;;; Display stuff
(defun calculator-reset ()
"Reset calculator variables."
(or calculator-restart-other-mode
(setq calculator-stack nil
calculator-curnum nil
calculator-stack-display nil
calculator-display-fragile nil))
(setq calculator-restart-other-mode nil)
(calculator-update-display))
(defun calculator-get-prompt ()
"Return a string to display.
The string is set not to exceed the screen width."
(let* ((calculator-prompt
(format calculator-prompt
(cond
((or calculator-output-radix calculator-input-radix)
(if (eq calculator-output-radix
calculator-input-radix)
(concat
(char-to-string
(car (rassq calculator-output-radix
calculator-char-radix)))
"=")
(concat
(if calculator-input-radix
(char-to-string
(car (rassq calculator-input-radix
calculator-char-radix)))
"=")
(char-to-string
(car (rassq calculator-output-radix
calculator-char-radix))))))
(calculator-deg "D=")
(t "=="))))
(prompt
(concat calculator-prompt
(cdr calculator-stack-display)
(cond (calculator-curnum
;; number being typed
(concat calculator-curnum "_"))
((and (= 1 (length calculator-stack))
calculator-display-fragile)
;; only the result is shown, next number will
;; restart
nil)
(t
;; waiting for a number or an operator
"?"))))
(trim (- (length prompt) (1- (window-width)))))
(if (<= trim 0)
prompt
(concat calculator-prompt
(substring prompt (+ trim (length calculator-prompt)))))))
(defun calculator-string-to-number (str)
"Convert the given STR to a number, according to the value of
`calculator-input-radix'."
(if calculator-input-radix
(let ((radix
(cdr (assq calculator-input-radix
'((bin . 2) (oct . 8) (hex . 16)))))
(i -1) (value 0) (new-value 0))
;; assume mostly valid input (e.g., characters in range)
(while (< (setq i (1+ i)) (length str))
(setq new-value
(let* ((ch (upcase (aref str i)))
(n (cond ((< ch ?0) nil)
((<= ch ?9) (- ch ?0))
((< ch ?A) nil)
((<= ch ?Z) (- ch (- ?A 10)))
(t nil))))
(if (and n (<= 0 n) (< n radix))
(+ n (* radix value))
(progn
(calculator-message
"Warning: Ignoring bad input character `%c'." ch)
(sit-for 1)
value))))
(if (if (< new-value 0) (> value 0) (< value 0))
(calculator-message "Warning: Overflow in input."))
(setq value new-value))
value)
(car (read-from-string
(cond ((equal "." str) "0.0")
((string-match "[eE][+-]?$" str) (concat str "0"))
((string-match "\\.[0-9]\\|[eE]" str) str)
((string-match "\\." str)
;; do this because Emacs reads "23." as an integer
(concat str "0"))
((stringp str) (concat str ".0"))
(t "0.0"))))))
(defun calculator-curnum-value ()
"Get the numeric value of the displayed number string as a float."
(calculator-string-to-number calculator-curnum))
(defun calculator-rotate-displayer (&optional new-disp)
"Switch to the next displayer on the `calculator-displayers' list.
Can be called with an optional argument NEW-DISP to force rotation to
that argument.
If radix output mode is active, toggle digit grouping."
(interactive)
(cond
(calculator-output-radix
(setq calculator-radix-grouping-mode
(not calculator-radix-grouping-mode))
(calculator-message
"Digit grouping mode %s."
(if calculator-radix-grouping-mode "ON" "OFF")))
(t
(setq calculator-displayers
(if (and new-disp (memq new-disp calculator-displayers))
(let ((tmp nil))
(while (not (eq (car calculator-displayers) new-disp))
(setq tmp (cons (car calculator-displayers) tmp))
(setq calculator-displayers
(cdr calculator-displayers)))
(setq calculator-displayers
(nconc calculator-displayers (nreverse tmp))))
(nconc (cdr calculator-displayers)
(list (car calculator-displayers)))))
(calculator-message
"Using %s." (cadr (car calculator-displayers)))))
(calculator-enter))
(defun calculator-rotate-displayer-back ()
"Like `calculator-rotate-displayer', but rotates modes back.
If radix output mode is active, toggle digit grouping."
(interactive)
(calculator-rotate-displayer (car (last calculator-displayers))))
(defun calculator-displayer-prev ()
"Send the current displayer function a 'left argument.
This is used to modify display arguments (if the current displayer
function supports this).
If radix output mode is active, increase the grouping size."
(interactive)
(if calculator-output-radix
(progn (setq calculator-radix-grouping-digits
(1+ calculator-radix-grouping-digits))
(calculator-enter))
(and (car calculator-displayers)
(let ((disp (caar calculator-displayers)))
(cond
((symbolp disp) (funcall disp 'left))
((and (consp disp) (eq 'std (car disp)))
(calculator-standard-displayer 'left (cadr disp))))))))
(defun calculator-displayer-next ()
"Send the current displayer function a 'right argument.
This is used to modify display arguments (if the current displayer
function supports this).
If radix output mode is active, decrease the grouping size."
(interactive)
(if calculator-output-radix
(progn (setq calculator-radix-grouping-digits
(max 2 (1- calculator-radix-grouping-digits)))
(calculator-enter))
(and (car calculator-displayers)
(let ((disp (caar calculator-displayers)))
(cond
((symbolp disp) (funcall disp 'right))
((and (consp disp) (eq 'std (car disp)))
(calculator-standard-displayer 'right (cadr disp))))))))
(defun calculator-remove-zeros (numstr)
"Get a number string NUMSTR and remove unnecessary zeros.
The behavior of this function is controlled by
`calculator-remove-zeros'."
(cond ((and (eq calculator-remove-zeros t)
(string-match "\\.0+\\([eE][+-]?[0-9]*\\)?$" numstr))
;; remove all redundant zeros leaving an integer
(if (match-beginning 1)
(concat (substring numstr 0 (match-beginning 0))
(match-string 1 numstr))
(substring numstr 0 (match-beginning 0))))
((and calculator-remove-zeros