1 ;;; calc.el --- the GNU Emacs calculator
3 ;; Copyright (C) 1990-1993, 2001-2011 Free Software Foundation, Inc.
5 ;; Author: David Gillespie <daveg@synaptics.com>
6 ;; Maintainer: Jay Belanger <jay.p.belanger@gmail.com>
7 ;; Keywords: convenience, extensions
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; Calc is split into many files. This file is the main entry point.
27 ;; This file includes autoload commands for various other basic Calc
28 ;; facilities. The more advanced features are based in calc-ext, which
29 ;; in turn contains autoloads for the rest of the Calc files. This
30 ;; odd set of interactions is designed to make Calc's loading time
31 ;; be as short as possible when only simple calculations are needed.
33 ;; Original author's address:
34 ;; Dave Gillespie, daveg@synaptics.com, uunet!synaptx!daveg.
35 ;; Synaptics, Inc., 2698 Orchard Parkway, San Jose, CA 95134.
37 ;; The old address daveg@csvax.cs.caltech.edu will continue to
38 ;; work for the foreseeable future.
40 ;; Bug reports and suggestions are always welcome! (Type M-x
41 ;; report-calc-bug to send them).
43 ;; All functions, macros, and Lisp variables defined here begin with one
44 ;; of the prefixes "math", "Math", or "calc", with the exceptions of
45 ;; "full-calc", "full-calc-keypad", "another-calc", "quick-calc",
46 ;; "report-calc-bug", and "defmath". User-accessible variables begin
51 ;; Fix rewrite mechanism to do less gratuitous rearrangement of terms.
52 ;; Implement a pattern-based "refers" predicate.
54 ;; Make it possible to Undo a selection command.
55 ;; Figure out how to allow selecting rows of matrices.
56 ;; If cursor was in selection before, move it after j n, j p, j L, etc.
57 ;; Consider reimplementing calc-delete-selection using rewrites.
59 ;; Implement line-breaking in non-flat compositions (is this desirable?).
60 ;; Implement matrix formatting with multi-line components.
62 ;; Have "Z R" define a user command based on a set of rewrite rules.
63 ;; Support "incf" and "decf" in defmath definitions.
64 ;; Have defmath generate calls to calc-binary-op or calc-unary-op.
65 ;; Make some way to define algebraic functions using keyboard macros.
67 ;; Allow calc-word-size=0 => Common Lisp-style signed bitwise arithmetic.
68 ;; Consider digamma function (and thus arb. prec. Euler's gamma constant).
69 ;; May as well make continued-fractions stuff available to the user.
71 ;; How about matrix eigenvalues, SVD, pseudo-inverse, etc.?
72 ;; Should cache matrix inverses as well as decompositions.
73 ;; If dividing by a non-square matrix, use least-squares automatically.
74 ;; Consider supporting matrix exponentials.
76 ;; Have ninteg detect and work around singularities at the endpoints.
77 ;; Use an adaptive subdivision algorithm for ninteg.
78 ;; Provide nsum and nprod to go along with ninteg.
80 ;; Handle TeX-mode parsing of \matrix{ ... } where ... contains braces.
81 ;; Support AmS-TeX's \{d,t,}frac, \{d,t,}binom notations.
82 ;; Format and parse sums and products in Eqn and Math modes.
84 ;; Get math-read-big-expr to read sums, products, etc.
85 ;; Change calc-grab-region to use math-read-big-expr.
86 ;; Have a way to define functions using := in Embedded Mode.
88 ;; Support polar plotting with GNUPLOT.
89 ;; Make a calc-graph-histogram function.
91 ;; Replace hokey formulas for complex functions with formulas designed
92 ;; to minimize roundoff while maintaining the proper branch cuts.
93 ;; Test accuracy of advanced math functions over whole complex plane.
94 ;; Extend Bessel functions to provide arbitrary precision.
95 ;; Extend advanced math functions to handle error forms and intervals.
96 ;; Provide a better implementation for math-sin-cos-raw.
97 ;; Provide a better implementation for math-hypot.
98 ;; Provide a better implementation for math-make-frac.
99 ;; Provide a better implementation for calcFunc-prfac.
100 ;; Provide a better implementation for calcFunc-factor.
102 ;; Provide more examples in the tutorial section of the manual.
103 ;; Cover in the tutorial: simplification modes, declarations,
104 ;; bitwise stuff, selections, matrix mapping, financial functions.
105 ;; Provide more Lisp programming examples in the manual.
106 ;; Finish the Internals section of the manual (and bring it up to date).
108 ;; Tim suggests adding spreadsheet-like features.
109 ;; Implement language modes for Gnuplot, Lisp, Ada, APL, ...?
111 ;; For atan series, if x > tan(pi/12) (about 0.268) reduce using the identity
112 ;; atan(x) = atan((x * sqrt(3) - 1) / (sqrt(3) + x)) + pi/6.
114 ;; A better integration algorithm:
115 ;; Use breadth-first instead of depth-first search, as follows:
116 ;; The integral cache allows unfinished integrals in symbolic notation
117 ;; on the righthand side. An entry with no unfinished integrals on the
118 ;; RHS is "complete"; references to it elsewhere are replaced by the
119 ;; integrated value. More than one cache entry for the same integral
120 ;; may exist, though if one becomes complete, the others may be deleted.
121 ;; The integrator works by using every applicable rule (such as
122 ;; substitution, parts, linearity, etc.) to generate possible righthand
123 ;; sides, all of which are entered into the cache. Now, as long as the
124 ;; target integral is not complete (and the time limit has not run out)
125 ;; choose an incomplete integral from the cache and, for every integral
126 ;; appearing in its RHS's, add those integrals to the cache using the
127 ;; same substitition, parts, etc. rules. The cache should be organized
128 ;; as a priority queue, choosing the "simplest" incomplete integral at
129 ;; each step, or choosing randomly among equally simple integrals.
130 ;; Simplicity equals small size, and few steps removed from the original
131 ;; target integral. Note that when the integrator finishes, incomplete
132 ;; integrals can be left in the cache, so the algorithm can start where
133 ;; it left off if another similar integral is later requested.
134 ;; Breadth-first search would avoid the nagging problem of, e.g., whether
135 ;; to use parts or substitution first, and which decomposition is best.
136 ;; All are tried, and any path that diverges will quickly be put on the
137 ;; back burner by the priority queue.
138 ;; Note: Probably a good idea to call math-simplify-extended before
139 ;; measuring a formula's simplicity.
145 ;; Declare functions which are defined elsewhere.
146 (declare-function calc-set-language
"calc-lang" (lang &optional option no-refresh
))
147 (declare-function calc-edit-finish
"calc-yank" (&optional keep
))
148 (declare-function calc-edit-cancel
"calc-yank" ())
149 (declare-function calc-do-quick-calc
"calc-aent" ())
150 (declare-function calc-do-calc-eval
"calc-aent" (str separator args
))
151 (declare-function calc-do-keypad
"calc-keypd" (&optional full-display interactive
))
152 (declare-function calcFunc-unixtime
"calc-forms" (date &optional zone
))
153 (declare-function math-parse-date
"calc-forms" (math-pd-str))
154 (declare-function math-lessp
"calc-ext" (a b
))
155 (declare-function math-compare
"calc-ext" (a b
))
156 (declare-function calc-embedded-finish-command
"calc-embed" ())
157 (declare-function calc-embedded-select-buffer
"calc-embed" ())
158 (declare-function calc-embedded-mode-line-change
"calc-embed" ())
159 (declare-function calc-push-list-in-macro
"calc-prog" (vals m sels
))
160 (declare-function calc-replace-selections
"calc-sel" (n vals m
))
161 (declare-function calc-record-list
"calc-misc" (vals &optional prefix
))
162 (declare-function calc-normalize-fancy
"calc-ext" (val))
163 (declare-function calc-do-handle-whys
"calc-misc" ())
164 (declare-function calc-top-selected
"calc-sel" (&optional n m
))
165 (declare-function calc-sel-error
"calc-sel" ())
166 (declare-function calc-pop-stack-in-macro
"calc-prog" (n mm
))
167 (declare-function calc-embedded-stack-change
"calc-embed" ())
168 (declare-function calc-refresh-evaltos
"calc-ext" (&optional which-var
))
169 (declare-function calc-do-refresh
"calc-misc" ())
170 (declare-function calc-binary-op-fancy
"calc-ext" (name func arg ident unary
))
171 (declare-function calc-unary-op-fancy
"calc-ext" (name func arg
))
172 (declare-function calc-delete-selection
"calc-sel" (n))
173 (declare-function calc-alg-digit-entry
"calc-aent" ())
174 (declare-function calc-alg-entry
"calc-aent" (&optional initial prompt
))
175 (declare-function calc-dots
"calc-incom" ())
176 (declare-function calc-temp-minibuffer-message
"calc-misc" (m))
177 (declare-function math-read-radix-digit
"calc-misc" (dig))
178 (declare-function calc-digit-dots
"calc-incom" ())
179 (declare-function math-normalize-fancy
"calc-ext" (a))
180 (declare-function math-normalize-nonstandard
"calc-ext" ())
181 (declare-function math-recompile-eval-rules
"calc-alg" ())
182 (declare-function math-apply-rewrites
"calc-rewr" (expr rules
&optional heads math-apply-rw-ruleset
))
183 (declare-function calc-record-why
"calc-misc" (&rest stuff
))
184 (declare-function math-dimension-error
"calc-vec" ())
185 (declare-function calc-incomplete-error
"calc-incom" (a))
186 (declare-function math-float-fancy
"calc-arith" (a))
187 (declare-function math-neg-fancy
"calc-arith" (a))
188 (declare-function calc-add-fractions
"calc-frac" (a b
))
189 (declare-function math-add-objects-fancy
"calc-arith" (a b
))
190 (declare-function math-add-symb-fancy
"calc-arith" (a b
))
191 (declare-function math-mul-zero
"calc-arith" (a b
))
192 (declare-function calc-mul-fractions
"calc-frac" (a b
))
193 (declare-function math-mul-objects-fancy
"calc-arith" (a b
))
194 (declare-function math-mul-symb-fancy
"calc-arith" (a b
))
195 (declare-function math-reject-arg
"calc-misc" (&optional a p option
))
196 (declare-function math-div-by-zero
"calc-arith" (a b
))
197 (declare-function math-div-zero
"calc-arith" (a b
))
198 (declare-function math-make-frac
"calc-frac" (num den
))
199 (declare-function calc-div-fractions
"calc-frac" (a b
))
200 (declare-function math-div-objects-fancy
"calc-arith" (a b
))
201 (declare-function math-div-symb-fancy
"calc-arith" (a b
))
202 (declare-function math-compose-expr
"calccomp" (a prec
))
203 (declare-function math-comp-width
"calccomp" (c))
204 (declare-function math-composition-to-string
"calccomp" (c &optional width
))
205 (declare-function math-stack-value-offset-fancy
"calccomp" ())
206 (declare-function math-format-flat-expr-fancy
"calc-ext" (a prec
))
207 (declare-function math-adjust-fraction
"calc-ext" (a))
208 (declare-function math-format-binary
"calc-bin" (a))
209 (declare-function math-format-radix
"calc-bin" (a))
210 (declare-function math-format-twos-complement
"calc-bin" (a))
211 (declare-function math-group-float
"calc-ext" (str))
212 (declare-function math-mod
"calc-misc" (a b
))
213 (declare-function math-format-number-fancy
"calc-ext" (a prec
))
214 (declare-function math-format-bignum-fancy
"calc-ext" (a))
215 (declare-function math-read-number-fancy
"calc-ext" (s))
216 (declare-function calc-do-grab-region
"calc-yank" (top bot arg
))
217 (declare-function calc-do-grab-rectangle
"calc-yank" (top bot arg
&optional reduce
))
218 (declare-function calc-do-embedded
"calc-embed" (calc-embed-arg end obeg oend
))
219 (declare-function calc-do-embedded-activate
"calc-embed" (calc-embed-arg cbuf
))
220 (declare-function math-do-defmath
"calc-prog" (func args body
))
221 (declare-function calc-load-everything
"calc-ext" ())
228 :group
'applications
)
230 ;; Do not autoload, so it is evaluated at run-time rather than at dump time.
232 (defcustom calc-settings-file
233 (locate-user-emacs-file "calc.el" ".calc.el")
234 "File in which to record permanent settings."
238 (defcustom calc-language-alist
239 '((latex-mode . latex
)
241 (plain-tex-mode . tex
)
244 (pascal-mode . pascal
)
247 (fortran-mode . fortran
)
249 (texinfo-mode . calc-normal-language
))
250 "Alist of major modes with appropriate Calc languages."
252 :type
'(alist :key-type
(symbol :tag
"Major mode")
253 :value-type
(symbol :tag
"Calc language")))
255 (defcustom calc-embedded-announce-formula
256 "%Embed\n\\(% .*\n\\)*"
257 "A regular expression which is sure to be followed by a calc-embedded formula."
261 (defcustom calc-embedded-announce-formula-alist
262 '((c++-mode .
"//Embed\n\\(// .*\n\\)*")
263 (c-mode .
"/\\*Embed\\*/\n\\(/\\* .*\\*/\n\\)*")
264 (f90-mode .
"!Embed\n\\(! .*\n\\)*")
265 (fortran-mode .
"C Embed\n\\(C .*\n\\)*")
266 (html-helper-mode .
"<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
267 (html-mode .
"<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
268 (nroff-mode .
"\\\\\"Embed\n\\(\\\\\" .*\n\\)*")
269 (pascal-mode .
"{Embed}\n\\({.*}\n\\)*")
270 (sgml-mode .
"<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
271 (xml-mode .
"<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
272 (texinfo-mode .
"@c Embed\n\\(@c .*\n\\)*"))
273 "Alist of major modes with appropriate values for `calc-embedded-announce-formula'."
275 :type
'(alist :key-type
(symbol :tag
"Major mode")
276 :value-type
(regexp :tag
"Regexp to announce formula")))
278 (defcustom calc-embedded-open-formula
279 "\\`\\|^\n\\|\\$\\$?\\|\\\\\\[\\|^\\\\begin[^{].*\n\\|^\\\\begin{.*[^x]}.*\n\\|^@.*\n\\|^\\.EQ.*\n\\|\\\\(\\|^%\n\\|^\\.\\\\\"\n"
280 "A regular expression for the opening delimiter of a formula used by calc-embedded."
284 (defcustom calc-embedded-close-formula
285 "\\'\\|\n$\\|\\$\\$?\\|\\\\]\\|^\\\\end[^{].*\n\\|^\\\\end{.*[^x]}.*\n\\|^@.*\n\\|^\\.EN.*\n\\|\\\\)\\|\n%\n\\|^\\.\\\\\"\n"
286 "A regular expression for the closing delimiter of a formula used by calc-embedded."
290 (defcustom calc-embedded-open-close-formula-alist
292 "Alist of major modes with pairs of formula delimiters used by calc-embedded."
294 :type
'(alist :key-type
(symbol :tag
"Major mode")
295 :value-type
(list (regexp :tag
"Opening formula delimiter")
296 (regexp :tag
"Closing formula delimiter"))))
298 (defcustom calc-embedded-word-regexp
299 "[-+]?[0-9]+\\(\\.[0-9]+\\)?\\([eE][-+]?[0-9]+\\)?"
300 "A regular expression determining a word for calc-embedded-word."
304 (defcustom calc-embedded-word-regexp-alist
306 "Alist of major modes with word regexps used by calc-embedded-word."
308 :type
'(alist :key-type
(symbol :tag
"Major mode")
309 :value-type
(regexp :tag
"Regexp for word")))
311 (defcustom calc-embedded-open-plain
313 "A string which is the opening delimiter for a \"plain\" formula.
314 If calc-show-plain mode is enabled, this is inserted at the front of
319 (defcustom calc-embedded-close-plain
321 "A string which is the closing delimiter for a \"plain\" formula.
322 See calc-embedded-open-plain."
326 (defcustom calc-embedded-open-close-plain-alist
327 '((c++-mode
"// %% " " %%\n")
328 (c-mode "/* %% " " %% */\n")
329 (f90-mode "! %% " " %%\n")
330 (fortran-mode "C %% " " %%\n")
331 (html-helper-mode "<!-- %% " " %% -->\n")
332 (html-mode "<!-- %% " " %% -->\n")
333 (nroff-mode "\\\" %% " " %%\n")
334 (pascal-mode "{%% " " %%}\n")
335 (sgml-mode "<!-- %% " " %% -->\n")
336 (xml-mode "<!-- %% " " %% -->\n")
337 (texinfo-mode "@c %% " " %%\n"))
338 "Alist of major modes with pairs of delimiters for \"plain\" formulas."
340 :type
'(alist :key-type
(symbol :tag
"Major mode")
341 :value-type
(list (string :tag
"Opening \"plain\" delimiter")
342 (string :tag
"Closing \"plain\" delimiter"))))
344 (defcustom calc-embedded-open-new-formula
346 "A string which is inserted at front of formula by calc-embedded-new-formula."
350 (defcustom calc-embedded-close-new-formula
352 "A string which is inserted at end of formula by calc-embedded-new-formula."
356 (defcustom calc-embedded-open-close-new-formula-alist
358 "Alist of major modes with pairs of new formula delimiters used by calc-embedded."
360 :type
'(alist :key-type
(symbol :tag
"Major mode")
361 :value-type
(list (string :tag
"Opening new formula delimiter")
362 (string :tag
"Closing new formula delimiter"))))
364 (defcustom calc-embedded-open-mode
366 "A string which should precede calc-embedded mode annotations.
367 This is not required to be present for user-written mode annotations."
371 (defcustom calc-embedded-close-mode
373 "A string which should follow calc-embedded mode annotations.
374 This is not required to be present for user-written mode annotations."
378 (defcustom calc-embedded-open-close-mode-alist
379 '((c++-mode
"// " "\n")
380 (c-mode "/* " " */\n")
382 (fortran-mode "C " "\n")
383 (html-helper-mode "<!-- " " -->\n")
384 (html-mode "<!-- " " -->\n")
385 (nroff-mode "\\\" " "\n")
386 (pascal-mode "{ " " }\n")
387 (sgml-mode "<!-- " " -->\n")
388 (xml-mode "<!-- " " -->\n")
389 (texinfo-mode "@c " "\n"))
390 "Alist of major modes with pairs of strings to delimit annotations."
392 :type
'(alist :key-type
(symbol :tag
"Major mode")
393 :value-type
(list (string :tag
"Opening annotation delimiter")
394 (string :tag
"Closing annotation delimiter"))))
396 (defcustom calc-gnuplot-name
397 (if (eq system-type
'windows-nt
) "pgnuplot" "gnuplot")
398 "Name of GNUPLOT program, for calc-graph features."
402 (defcustom calc-gnuplot-plot-command
404 "Name of command for displaying GNUPLOT output; %s = file name to print."
406 :type
'(choice (string) (sexp)))
408 (defcustom calc-gnuplot-print-command
410 "Name of command for printing GNUPLOT output; %s = file name to print."
412 :type
'(choice (string) (sexp)))
414 (defcustom calc-multiplication-has-precedence
416 "If non-nil, multiplication has precedence over division
421 (defcustom calc-undo-length
423 "The number of undo steps that will be preserved when Calc is quit."
427 (defcustom calc-highlight-selections-with-faces
429 "If non-nil, use a separate face to indicate selected sub-formulas.
430 If `calc-show-selections' is non-nil, then selected sub-formulas are shown
431 by displaying the rest of the formula in `calc-nonselected-face'.
432 If `calc-show-selections' is nil, then selected sub-formulas are shown
433 by displaying the sub-formula in `calc-selected-face'."
437 (defcustom calc-default-field-reference-level
439 "The default reference level for logarithmic units (field)."
443 (defcustom calc-default-power-reference-level
445 "The default reference level for logarithmic units (power)."
450 (defface calc-nonselected-face
453 "Face used to show the non-selected portion of a formula."
456 (defface calc-selected-face
458 "Face used to show the selected portion of a formula."
461 (defvar calc-bug-address
"jay.p.belanger@gmail.com"
462 "Address of the maintainer of Calc, for use by `report-calc-bug'.")
464 (defvar calc-scan-for-dels t
465 "If t, scan keymaps to find all DEL-like keys.
466 if nil, only DEL itself is mapped to calc-pop.")
468 (defvar calc-stack
'((top-of-stack 1 nil
))
470 Entries are 3-lists: Formula, Height (in lines), Selection (or nil).")
472 (defvar calc-stack-top
1
473 "Index into `calc-stack' of \"top\" of stack.
474 This is 1 unless `calc-truncate-stack' has been used.")
476 (defvar calc-display-sci-high
0
477 "Floating-point numbers with this positive exponent or higher above the
478 current precision are displayed in scientific notation in calc-mode.")
480 (defvar calc-display-sci-low -
3
481 "Floating-point numbers with this negative exponent or lower are displayed
482 scientific notation in calc-mode.")
484 (defvar calc-other-modes nil
485 "List of used-defined strings to append to Calculator mode line.")
487 (defvar calc-Y-help-msgs nil
488 "List of strings for Y prefix help.")
490 (defvar calc-loaded-settings-file nil
491 "t if `calc-settings-file' has been loaded yet.")
494 (defvar calc-mode-var-list
'()
495 "List of variables used in customizing GNU Calc.")
497 (defmacro defcalcmodevar
(var defval
&optional doc
)
498 "Declare VAR as a Calc variable, with default value DEFVAL
500 The variable VAR will be added to `calc-mode-var-list'."
502 (defvar ,var
,defval
,doc
)
503 (add-to-list 'calc-mode-var-list
(list (quote ,var
) ,defval
))))
505 (defun calc-mode-var-list-restore-default-values ()
506 "Restore the default values of the variables in `calc-mode-var-list'."
507 (mapcar (function (lambda (v) (set (car v
) (nth 1 v
))))
510 (defun calc-mode-var-list-restore-saved-values ()
511 "Restore the user-saved values of the variables in `calc-mode-var-list'."
512 (let ((newvarlist '()))
515 (file (substitute-in-file-name calc-settings-file
)))
517 (file-regular-p file
)
518 (set-buffer (find-file-noselect file
))
519 (goto-char (point-min))
520 (search-forward ";;; Mode settings stored by Calc" nil t
)
524 (search-forward "\n;;; End of mode settings" nil t
)))
526 (calc-mode-var-list-restore-default-values)
527 (eval-region pos
(point))
528 (let ((varlist calc-mode-var-list
))
530 (let ((var (car varlist
)))
532 (cons (list (car var
) (symbol-value (car var
)))
534 (setq varlist
(cdr varlist
)))))))
536 (mapcar (function (lambda (v) (set (car v
) (nth 1 v
))))
538 (calc-mode-var-list-restore-default-values))))
540 (defcalcmodevar calc-always-load-extensions nil
541 "If non-nil, load the calc-ext module automatically when Calc is loaded.")
543 (defcalcmodevar calc-line-numbering t
544 "If non-nil, display line numbers in Calculator stack.")
546 (defcalcmodevar calc-line-breaking t
547 "If non-nil, break long values across multiple lines in Calculator stack.")
549 (defcalcmodevar calc-display-just nil
550 "If nil, stack display is left-justified.
551 If `right', stack display is right-justified.
552 If `center', stack display is centered.")
554 (defcalcmodevar calc-display-origin nil
555 "Horizontal origin of displayed stack entries.
556 In left-justified mode, this is effectively indentation. (Default 0).
557 In right-justified mode, this is effectively window width.
558 In centered mode, center of stack entry is placed here.")
560 (defcalcmodevar calc-number-radix
10
561 "Radix for entry and display of numbers in calc-mode, 2-36.")
563 (defcalcmodevar calc-leading-zeros nil
564 "If non-nil, leading zeros are provided to pad integers to calc-word-size.")
566 (defcalcmodevar calc-group-digits nil
567 "If non-nil, group digits in large displayed integers by inserting spaces.
568 If an integer, group that many digits at a time.
569 If t, use 4 for binary and hex, 3 otherwise.")
571 (defcalcmodevar calc-group-char
","
572 "The character (in the form of a string) to be used for grouping digits.
573 This is used only when calc-group-digits mode is on.")
575 (defcalcmodevar calc-point-char
"."
576 "The character (in the form of a string) to be used as a decimal point.")
578 (defcalcmodevar calc-frac-format
'(":" nil
)
579 "Format of displayed fractions; a string of one or two of \":\" or \"/\".")
581 (defcalcmodevar calc-prefer-frac nil
582 "If non-nil, prefer fractional over floating-point results.")
584 (defcalcmodevar calc-hms-format
"%s@ %s' %s\""
585 "Format of displayed hours-minutes-seconds angles, a format string.
586 String must contain three %s marks for hours, minutes, seconds respectively.")
588 (defcalcmodevar calc-date-format
'((H ":" mm C SS pp
" ")
589 Www
" " Mmm
" " D
", " YYYY
)
590 "Format of displayed date forms.")
592 (defcalcmodevar calc-float-format
'(float 0)
593 "Format to use for display of floating-point numbers in calc-mode.
594 Must be a list of one of the following forms:
595 (float 0) Floating point format, display full precision.
596 (float N) N > 0: Floating point format, at most N significant figures.
597 (float -N) -N < 0: Floating point format, calc-internal-prec - N figs.
598 (fix N) N >= 0: Fixed point format, N places after decimal point.
599 (sci 0) Scientific notation, full precision.
600 (sci N) N > 0: Scientific notation, N significant figures.
601 (sci -N) -N < 0: Scientific notation, calc-internal-prec - N figs.
602 (eng 0) Engineering notation, full precision.
603 (eng N) N > 0: Engineering notation, N significant figures.
604 (eng -N) -N < 0: Engineering notation, calc-internal-prec - N figs.")
606 (defcalcmodevar calc-full-float-format
'(float 0)
607 "Format to use when full precision must be displayed.")
609 (defcalcmodevar calc-complex-format nil
610 "Format to use for display of complex numbers in calc-mode. Must be one of:
615 (defcalcmodevar calc-complex-mode
'cplx
616 "Preferred form, either `cplx' or `polar', for complex numbers.")
618 (defcalcmodevar calc-infinite-mode nil
619 "If nil, 1 / 0 is left unsimplified.
620 If 0, 1 / 0 is changed to inf (zeros are considered positive).
621 Otherwise, 1 / 0 is changed to uinf (undirected infinity).")
623 (defcalcmodevar calc-display-strings nil
624 "If non-nil, display vectors of byte-sized integers as strings.")
626 (defcalcmodevar calc-matrix-just
'center
627 "If nil, vector elements are left-justified.
628 If `right', vector elements are right-justified.
629 If `center', vector elements are centered.")
631 (defcalcmodevar calc-break-vectors nil
632 "If non-nil, display vectors one element per line.")
634 (defcalcmodevar calc-full-vectors t
635 "If non-nil, display long vectors in full. If nil, use abbreviated form.")
637 (defcalcmodevar calc-full-trail-vectors t
638 "If non-nil, display long vectors in full in the trail.")
640 (defcalcmodevar calc-vector-commas
","
641 "If non-nil, separate elements of displayed vectors with this string.")
643 (defcalcmodevar calc-vector-brackets
"[]"
644 "If non-nil, surround displayed vectors with these characters.")
646 (defcalcmodevar calc-matrix-brackets
'(R O
)
647 "A list of code-letter symbols that control \"big\" matrix display.
648 If `R' is present, display inner brackets for matrices.
649 If `O' is present, display outer brackets for matrices (above/below).
650 If `C' is present, display outer brackets for matrices (centered).")
652 (defcalcmodevar calc-language nil
653 "Language or format for entry and display of stack values. Must be one of:
654 nil Use standard Calc notation.
655 flat Use standard Calc notation, one-line format.
656 big Display formulas in 2-d notation (enter w/std notation).
657 unform Use unformatted display: add(a, mul(b,c)).
658 c Use C language notation.
659 pascal Use Pascal language notation.
660 fortran Use Fortran language notation.
661 tex Use TeX notation.
662 latex Use LaTeX notation.
663 eqn Use eqn notation.
664 yacas Use Yacas notation.
665 maxima Use Maxima notation.
666 giac Use Giac notation.
667 math Use Mathematica(tm) notation.
668 maple Use Maple notation.")
670 (defcalcmodevar calc-language-option nil
671 "Numeric prefix argument for the command that set `calc-language'.")
673 (defcalcmodevar calc-left-label
""
674 "Label to display at left of formula.")
676 (defcalcmodevar calc-right-label
""
677 "Label to display at right of formula.")
679 (defcalcmodevar calc-word-size
32
680 "Minimum number of bits per word, if any, for binary operations in calc-mode.")
682 (defcalcmodevar calc-previous-modulo nil
683 "Most recently used value of M in a modulo form.")
685 (defcalcmodevar calc-simplify-mode nil
686 "Type of simplification applied to results.
687 If `none', results are not simplified when pushed on the stack.
688 If `num', functions are simplified only when args are constant.
689 If nil, only fast simplifications are applied.
690 If `binary', `math-clip' is applied if appropriate.
691 If `alg', `math-simplify' is applied.
692 If `ext', `math-simplify-extended' is applied.
693 If `units', `math-simplify-units' is applied.")
695 (defcalcmodevar calc-auto-recompute t
696 "If non-nil, recompute evalto's automatically when necessary.")
698 (defcalcmodevar calc-display-raw nil
699 "If non-nil, display shows unformatted Lisp exprs. (For debugging)")
701 (defcalcmodevar calc-internal-prec
12
702 "Number of digits of internal precision for calc-mode calculations.")
704 (defcalcmodevar calc-angle-mode
'deg
705 "If deg, angles are in degrees; if rad, angles are in radians.
706 If hms, angles are in degrees-minutes-seconds.")
708 (defcalcmodevar calc-algebraic-mode nil
709 "If non-nil, numeric entry accepts whole algebraic expressions.
710 If nil, algebraic expressions must be preceded by \"'\".")
712 (defcalcmodevar calc-incomplete-algebraic-mode nil
713 "Like calc-algebraic-mode except only affects ( and [ keys.")
715 (defcalcmodevar calc-symbolic-mode nil
716 "If non-nil, inexact numeric computations like sqrt(2) are postponed.
717 If nil, computations on numbers always yield numbers where possible.")
719 (defcalcmodevar calc-matrix-mode nil
720 "If `matrix', variables are assumed to be matrix-valued.
721 If a number, variables are assumed to be NxN matrices.
722 If `sqmatrix', variables are assumed to be square matrices of an unspecified size.
723 If `scalar', variables are assumed to be scalar-valued.
724 If nil, symbolic math routines make no assumptions about variables.")
726 (defcalcmodevar calc-twos-complement-mode nil
727 "If non-nil, display integers in two's complement mode.")
730 (defcalcmodevar calc-shift-prefix nil
731 "If non-nil, shifted letter keys are prefix keys rather than normal meanings.")
733 (defcalcmodevar calc-window-height
7
734 "Initial height of Calculator window.")
736 (defcalcmodevar calc-display-trail t
737 "If non-nil, M-x calc creates a window to display Calculator trail.")
739 (defcalcmodevar calc-show-selections t
740 "If non-nil, selected sub-formulas are shown by obscuring rest of formula.
741 If nil, selected sub-formulas are highlighted by obscuring the sub-formulas.")
743 (defcalcmodevar calc-use-selections t
744 "If non-nil, commands operate only on selected portions of formulas.
745 If nil, selections displayed but ignored.")
747 (defcalcmodevar calc-assoc-selections t
748 "If non-nil, selection hides deep structure of associative formulas.")
750 (defcalcmodevar calc-display-working-message
'lots
751 "If non-nil, display \"Working...\" for potentially slow Calculator commands.")
753 (defcalcmodevar calc-auto-why
'maybe
754 "If non-nil, automatically execute a \"why\" command to explain odd results.")
756 (defcalcmodevar calc-timing nil
757 "If non-nil, display timing information on each slow command.")
759 (defcalcmodevar calc-mode-save-mode
'local
)
761 (defcalcmodevar calc-standard-date-formats
763 "<H:mm:SSpp >Www Mmm D, YYYY"
764 "D Mmm YYYY<, h:mm:SS>"
765 "Www Mmm BD< hh:mm:ss> YYYY"
773 (defcalcmodevar calc-autorange-units nil
774 "If non-nil, automatically set unit prefixes to keep units in a reasonable range.")
776 (defcalcmodevar calc-was-keypad-mode nil
777 "Non-nil if Calc was last invoked in keypad mode.")
779 (defcalcmodevar calc-full-mode nil
780 "Non-nil if Calc was last invoked in full-screen mode.")
782 (defcalcmodevar calc-user-parse-tables nil
783 "Alist of languages with user-defined parse rules.")
785 (defcalcmodevar calc-gnuplot-default-device
"default"
786 "The default device name for GNUPLOT plotting.")
788 (defcalcmodevar calc-gnuplot-default-output
"STDOUT"
789 "The default output file for GNUPLOT plotting.")
791 (defcalcmodevar calc-gnuplot-print-device
"postscript"
792 "The default device name for GNUPLOT printing.")
794 (defcalcmodevar calc-gnuplot-print-output
"auto"
795 "The default output for GNUPLOT printing.")
797 (defcalcmodevar calc-gnuplot-geometry nil
798 "The default geometry for the GNUPLOT window.")
800 (defcalcmodevar calc-graph-default-resolution
15
801 "The default number of data points when plotting curves.")
803 (defcalcmodevar calc-graph-default-resolution-3d
5
804 "The default number of x- and y- data points when plotting surfaces.")
806 (defcalcmodevar calc-invocation-macro nil
807 "A user defined macro for starting Calc.
808 Used by `calc-user-invocation'.")
810 (defcalcmodevar calc-show-banner t
811 "*If non-nil, show a friendly greeting above the stack.")
813 (defconst calc-local-var-list
'(calc-stack
817 calc-always-load-extensions
828 calc-incomplete-algebraic-mode
845 calc-standard-date-formats
847 calc-full-float-format
851 calc-full-trail-vectors
865 calc-assoc-selections
869 (defvar calc-mode-hook nil
870 "Hook run when entering calc-mode.")
872 (defvar calc-trail-mode-hook nil
873 "Hook run when entering calc-trail-mode.")
875 (defvar calc-start-hook nil
876 "Hook run when calc is started.")
878 (defvar calc-end-hook nil
879 "Hook run when calc is quit.")
881 (defvar calc-load-hook nil
882 "Hook run when calc.el is loaded.")
884 (defvar calc-window-hook nil
885 "Hook called to create the Calc window.")
887 (defvar calc-trail-window-hook nil
888 "Hook called to create the Calc trail window.")
890 (defvar calc-embedded-new-buffer-hook nil
891 "Hook run when starting embedded mode in a new buffer.")
893 (defvar calc-embedded-new-formula-hook nil
894 "Hook run when starting embedded mode in a new formula.")
896 (defvar calc-embedded-mode-hook nil
897 "Hook run when starting embedded mode.")
899 ;; Set up the autoloading linkage.
900 (let ((name (and (fboundp 'calc-dispatch
)
901 (eq (car-safe (symbol-function 'calc-dispatch
)) 'autoload
)
902 (nth 1 (symbol-function 'calc-dispatch
))))
905 ;; If Calc files exist on the load-path, we're all set.
906 (while (and p
(not (file-exists-p
907 (expand-file-name "calc-misc.elc" (car p
)))))
911 ;; If Calc is autoloaded using a path name, look there for Calc files.
912 ;; This works for both relative ("calc/calc.elc") and absolute paths.
913 (and name
(file-name-directory name
)
915 (name2 (concat (file-name-directory name
)
917 (while (and p2
(not (file-exists-p
918 (expand-file-name name2
(car p2
)))))
921 (setq load-path
(nconc load-path
926 name
(car p2
))))))))))))
928 ;; The following modes use specially-formatted data.
929 (put 'calc-mode
'mode-class
'special
)
930 (put 'calc-trail-mode
'mode-class
'special
)
932 ;; Define "inexact-result" as an e-lisp error symbol.
933 (put 'inexact-result
'error-conditions
'(error inexact-result calc-error
))
934 (put 'inexact-result
'error-message
"Calc internal error (inexact-result)")
936 ;; Define "math-overflow" and "math-underflow" as e-lisp error symbols.
937 (put 'math-overflow
'error-conditions
'(error math-overflow calc-error
))
938 (put 'math-overflow
'error-message
"Floating-point overflow occurred")
939 (put 'math-underflow
'error-conditions
'(error math-underflow calc-error
))
940 (put 'math-underflow
'error-message
"Floating-point underflow occurred")
942 (defvar calc-trail-pointer nil
943 "The \"current\" entry in trail buffer.")
944 (defvar calc-trail-overlay nil
945 "The value of overlay-arrow-string.")
946 (defvar calc-undo-list nil
947 "The list of previous operations for undo.")
948 (defvar calc-redo-list nil
949 "The list of recent undo operations.")
950 (defvar calc-main-buffer nil
951 "A pointer to Calculator buffer.")
952 (defvar calc-buffer-list nil
953 "A list of all Calc buffers.")
954 (defvar calc-trail-buffer nil
955 "A pointer to Calc Trail buffer.")
957 "Explanations of most recent errors.")
958 (defvar calc-next-why nil
)
959 (defvar calc-inverse-flag nil
960 "If non-nil, next operation is Inverse.")
961 (defvar calc-hyperbolic-flag nil
962 "If non-nil, next operation is Hyperbolic.")
963 (defvar calc-option-flag nil
964 "If non-nil, next operation has Optional behavior.")
965 (defvar calc-keep-args-flag nil
966 "If non-nil, next operation should not remove its arguments from stack.")
967 (defvar calc-function-open
"("
968 "Open-parenthesis string for function call notation.")
969 (defvar calc-function-close
")"
970 "Close-parenthesis string for function call notation.")
971 (defvar calc-language-output-filter nil
972 "Function through which to pass strings after formatting.")
973 (defvar calc-language-input-filter nil
974 "Function through which to pass strings before parsing.")
975 (defvar calc-radix-formatter nil
976 "Formatting function used for non-decimal numbers.")
977 (defvar calc-lang-slash-idiv nil
978 "A list of languages in which / might represent integer division.")
979 (defvar calc-lang-allow-underscores nil
980 "A list of languages which allow underscores in variable names.")
981 (defvar calc-lang-allow-percentsigns nil
982 "A list of languages which allow percent signs in variable names.")
983 (defvar calc-lang-c-type-hex nil
984 "Languages in which octal and hex numbers are written with leading 0 and 0x,")
985 (defvar calc-lang-brackets-are-subscripts nil
986 "Languages in which subscripts are indicated by brackets.")
987 (defvar calc-lang-parens-are-subscripts nil
988 "Languages in which subscripts are indicated by parentheses.")
990 (defvar calc-last-kill nil
991 "The last number killed in calc-mode.")
992 (defvar calc-dollar-values nil
993 "Values to be used for '$'.")
994 (defvar calc-dollar-used nil
995 "The highest order of '$' that occurred.")
996 (defvar calc-hashes-used nil
997 "The highest order of '#' that occurred.")
998 (defvar calc-quick-prev-results nil
999 "Previous results from Quick Calc.")
1000 (defvar calc-said-hello nil
1001 "Non-nil if the welcomd message has been displayed.")
1002 (defvar calc-executing-macro nil
1003 "Non-nil if a keyboard macro is executing from the \"K\" key.")
1004 (defvar calc-any-selections nil
1005 "Non-nil if there are selections present.")
1006 (defvar calc-help-phase
0
1007 "The number of consecutive \"?\" keystrokes.")
1008 (defvar calc-full-help-flag nil
1009 "Non-nil if `calc-full-help' is being executed.")
1010 (defvar calc-refresh-count
0
1011 "The number of `calc-refresh' calls.")
1012 (defvar calc-display-dirty nil
1013 "Non-nil if the stack display might not reflect the latest mode settings.")
1014 (defvar calc-prepared-composition nil
)
1015 (defvar calc-selection-cache-default-entry nil
)
1016 (defvar calc-embedded-info nil
1017 "If non-nil, a vector consisting of information for embedded mode.")
1018 (defvar calc-embedded-active nil
1019 "Alist of buffers with sorted lists of calc-embedded-infos.")
1020 (defvar calc-standalone-flag nil
1021 "Non-nil if Emacs started with standalone Calc.")
1022 (defvar var-EvalRules nil
1023 "User defined rules that Calc will apply automatically.")
1024 (defvar math-eval-rules-cache-tag t
)
1025 (defvar math-radix-explicit-format t
)
1026 (defvar math-expr-function-mapping nil
1027 "Alist of language specific functions with Calc functions.")
1028 (defvar math-expr-variable-mapping nil
1029 "Alist of language specific variables with Calc variables.")
1030 (defvar math-read-expr-quotes nil
)
1031 (defvar math-working-step nil
)
1032 (defvar math-working-step-2 nil
)
1033 (defvar var-i
'(special-const (math-imaginary 1)))
1034 (defvar var-pi
'(special-const (math-pi)))
1035 (defvar var-Ï€
'(special-const (math-pi)))
1036 (defvar var-e
'(special-const (math-e)))
1037 (defvar var-phi
'(special-const (math-phi)))
1038 (defvar var-φ
'(special-const (math-phi)))
1039 (defvar var-gamma
'(special-const (math-gamma-const)))
1040 (defvar var-γ
'(special-const (math-gamma-const)))
1041 (defvar var-Modes
'(special-const (math-get-modes-vec)))
1043 (mapc (lambda (v) (or (boundp v
) (set v nil
)))
1044 calc-local-var-list
)
1046 (defvar calc-mode-map
1047 (let ((map (make-keymap)))
1048 (suppress-keymap map t
)
1049 (define-key map
"+" 'calc-plus
)
1050 (define-key map
"-" 'calc-minus
)
1051 (define-key map
"*" 'calc-times
)
1052 (define-key map
"/" 'calc-divide
)
1053 (define-key map
"%" 'calc-mod
)
1054 (define-key map
"&" 'calc-inv
)
1055 (define-key map
"^" 'calc-power
)
1056 (define-key map
"\M-%" 'calc-percent
)
1057 (define-key map
"e" 'calcDigit-start
)
1058 (define-key map
"i" 'calc-info
)
1059 (define-key map
"n" 'calc-change-sign
)
1060 (define-key map
"q" 'calc-quit
)
1061 (define-key map
"Y" 'nil
)
1062 (define-key map
"Y?" 'calc-shift-Y-prefix-help
)
1063 (define-key map
"?" 'calc-help
)
1064 (define-key map
" " 'calc-enter
)
1065 (define-key map
"'" 'calc-algebraic-entry
)
1066 (define-key map
"$" 'calc-auto-algebraic-entry
)
1067 (define-key map
"\"" 'calc-auto-algebraic-entry
)
1068 (define-key map
"\t" 'calc-roll-down
)
1069 (define-key map
"\M-\t" 'calc-roll-up
)
1070 (define-key map
"\C-x\C-t" 'calc-transpose-lines
)
1071 (define-key map
"\C-m" 'calc-enter
)
1072 (define-key map
"\M-\C-m" 'calc-last-args-stub
)
1073 (define-key map
"\C-j" 'calc-over
)
1074 (define-key map
"\C-y" 'calc-yank
)
1075 (define-key map
[mouse-2
] 'calc-yank
)
1076 (define-key map
[remap undo
] 'calc-undo
)
1078 (mapc (lambda (x) (define-key map
(char-to-string x
) 'undefined
))
1080 (mapc (lambda (x) (define-key map
(char-to-string x
) 'calc-missing-key
))
1081 (concat "ABCDEFGHIJKLMNOPQRSTUVXZabcdfghjkmoprstuvwxyz"
1082 ":\\|!()[]<>{},;=~`\C-k\C-w\C-_"))
1083 (define-key map
"\M-w" 'calc-missing-key
)
1084 (define-key map
"\M-k" 'calc-missing-key
)
1085 (define-key map
"\M-\C-w" 'calc-missing-key
)
1086 (mapc (lambda (x) (define-key map
(char-to-string x
) 'calcDigit-start
))
1089 "The key map for Calc.")
1091 (defvar calc-digit-map
1092 (let ((map (make-keymap)))
1093 (map-keymap (lambda (key bind
)
1094 (define-key map
(vector key
)
1095 (if (eq bind
'undefined
)
1096 'undefined
'calcDigit-nondigit
)))
1098 (mapc (lambda (x) (define-key map
(char-to-string x
) 'calcDigit-key
))
1099 "_0123456789.e+-:n#@oh'\"mspM")
1100 (mapc (lambda (x) (define-key map
(char-to-string x
) 'calcDigit-letter
))
1101 "abcdfgijklqrtuvwxyzABCDEFGHIJKLNOPQRSTUVWXYZ")
1102 (define-key map
"'" 'calcDigit-algebraic
)
1103 (define-key map
"`" 'calcDigit-edit
)
1104 (define-key map
"\C-g" 'abort-recursive-edit
)
1106 "The key map for entering Calc digits.")
1111 (define-key calc-digit-map x
'calcDigit-backspace
)
1112 (define-key calc-mode-map x
'calc-pop
)
1113 (define-key calc-mode-map
1114 (if (and (vectorp x
) (featurep 'xemacs
))
1115 (if (= (length x
) 1)
1116 (vector (if (consp (aref x
0))
1117 (cons 'meta
(aref x
0))
1118 (list 'meta
(aref x
0))))
1123 (if calc-scan-for-dels
1124 (append (where-is-internal 'delete-backward-char global-map
)
1125 (where-is-internal 'backward-delete-char global-map
)
1126 (where-is-internal 'backward-delete-char-untabify global-map
)
1130 (defvar calc-dispatch-map
1131 (let ((map (make-keymap)))
1133 (let* ((x-chr (car x
))
1134 (x-str (char-to-string x-chr
))
1136 (define-key map x-str x-def
)
1137 (when (string-match "[a-z]" x-str
)
1138 ;; Map upper case char to same definition.
1139 (define-key map
(upcase x-str
) x-def
)
1140 (unless (string-match "[gmv]" x-str
)
1141 ;; Map control prefixed char to same definition.
1142 (define-key map
(vector (list 'control x-chr
)) x-def
)))
1143 (define-key map
(format "\e%c" x-chr
) x-def
)))
1144 '( ( ?a . calc-embedded-activate
)
1145 ( ?b . calc-big-or-small
)
1147 ( ?d . calc-embedded-duplicate
)
1148 ( ?e . calc-embedded
)
1149 ( ?f . calc-embedded-new-formula
)
1150 ( ?g . calc-grab-region
)
1151 ( ?h . calc-dispatch-help
)
1153 ( ?j . calc-embedded-select
)
1154 ( ?k . calc-keypad
)
1155 ( ?l . calc-load-everything
)
1156 ( ?m . read-kbd-macro
)
1157 ( ?n . calc-embedded-next
)
1158 ( ?o . calc-other-window
)
1159 ( ?p . calc-embedded-previous
)
1161 ( ?r . calc-grab-rectangle
)
1162 ( ?s . calc-info-summary
)
1163 ( ?t . calc-tutorial
)
1164 ( ?u . calc-embedded-update-formula
)
1165 ( ?w . calc-embedded-word
)
1167 ( ?y . calc-copy-to-buffer
)
1168 ( ?z . calc-user-invocation
)
1169 ( ?
\' . calc-embedded-new-formula
)
1170 ( ?\
` . calc-embedded-edit
)
1171 ( ?
: . calc-grab-sum-down
)
1172 ( ?_ . calc-grab-sum-across
)
1174 ( ?? . calc-dispatch-help
)
1175 ( ?
# . calc-same-interface
)
1176 ( ?
& . calc-same-interface
)
1177 ( ?
\\ . calc-same-interface
)
1178 ( ?
= . calc-same-interface
)
1179 ( ?
* . calc-same-interface
)
1180 ( ?
/ . calc-same-interface
)
1181 ( ?
+ . calc-same-interface
)
1182 ( ?- . calc-same-interface
) ))
1184 "The key map for starting Calc.")
1187 ;;;; (Autoloads here)
1188 (load "calc-loaddefs.el" nil t
)
1190 ;;;###autoload (define-key ctl-x-map "*" 'calc-dispatch)
1193 (defun calc-dispatch (&optional arg
)
1194 "Invoke the GNU Emacs Calculator. See `calc-dispatch-help' for details."
1196 ; (sit-for echo-keystrokes)
1197 (condition-case err
; look for other keys bound to calc-dispatch
1198 (let ((keys (this-command-keys)))
1199 (unless (or (not (stringp keys
))
1200 (string-match "\\`\C-u\\|\\`\e[-0-9#]\\|`[\M--\M-0-\M-9]" keys
)
1201 (eq (lookup-key calc-dispatch-map keys
) 'calc-same-interface
))
1202 (when (and (string-match "\\`[\C-@-\C-_]" keys
)
1204 (lookup-key calc-dispatch-map
(substring keys
0 1))))
1205 (define-key calc-dispatch-map
(substring keys
0 1) nil
))
1206 (define-key calc-dispatch-map keys
'calc-same-interface
)))
1208 (calc-do-dispatch arg
))
1210 (defvar calc-dispatch-help nil
)
1211 (defun calc-do-dispatch (arg)
1212 "Start the Calculator."
1213 (let ((key (calc-read-key-sequence
1214 (if calc-dispatch-help
1215 "Calc options: Calc, Keypad, Quick, Embed; eXit; Info, Tutorial; Grab; ?=more"
1216 (format "%s (Type ? for a list of Calc options)"
1217 (key-description (this-command-keys))))
1218 calc-dispatch-map
)))
1219 (setq key
(lookup-key calc-dispatch-map key
))
1223 (or (commandp key
) (require 'calc-ext
))
1224 (call-interactively key
))
1227 (defun calc-read-key-sequence (prompt map
)
1228 "Read keys, with prompt PROMPT and keymap MAP."
1229 (let ((prompt2 (format "%s " (key-description (this-command-keys))))
1230 (glob (current-global-map))
1231 (loc (current-local-map)))
1232 (or (input-pending-p) (message "%s" prompt
))
1233 (let ((key (calc-read-key t
)))
1234 (calc-unread-command (cdr key
))
1237 (use-global-map map
)
1239 (read-key-sequence nil
))
1240 (use-global-map glob
)
1241 (use-local-map loc
)))))
1243 (defvar calc-alg-map
) ; Defined in calc-ext.el
1246 (defvar calc-embedded-modes
) ; Defined in calc-embed.el
1247 (defvar calc-override-minor-modes
) ; Defined in calc-embed.el
1248 (defun calc-kill-stack-buffer ()
1249 "Check to see if user wants to kill the Calc stack buffer.
1250 This will look for buffers using the Calc buffer for embedded mode,
1251 and inform the user if there are any.
1252 If the user wants to kill the Calc buffer, this will remove
1253 embedded information from the appropriate buffers and tidy up
1255 (let ((cb (current-buffer))
1259 (cea calc-embedded-active
))
1260 ;; Get a list of all buffers using this buffer for
1263 (when (and (eq cb
(aref (nth 1 (car cea
)) 1))
1264 (buffer-name (car (car cea
))))
1265 (setq info-list
(cons (car cea
) info-list
)))
1266 (setq cea
(cdr cea
)))
1267 ;; Eventually, prompt user with a list of buffers using embedded mode.
1271 (concat "This Calc stack is being used for embedded mode. Kill anyway?")))
1273 (with-current-buffer (car (car info-list
))
1274 (when calc-embedded-info
1275 (setq calc-embedded-info nil
1276 mode-line-buffer-identification
(car calc-embedded-modes
)
1277 truncate-lines
(nth 2 calc-embedded-modes
)
1278 buffer-read-only nil
)
1279 (use-local-map (nth 1 calc-embedded-modes
))
1280 (setq minor-mode-overriding-map-alist
1281 (remq calc-override-minor-modes minor-mode-overriding-map-alist
))
1282 (let ((str mode-line-buffer-identification
))
1283 (setq mode-line-buffer-identification str
))
1284 (set-buffer-modified-p (buffer-modified-p))))
1285 (setq calc-embedded-active
1286 (delete (car info-list
) calc-embedded-active
))
1287 (setq info-list
(cdr info-list
))))
1290 (setq calc-buffer-list
(delete cb calc-buffer-list
))
1291 (with-current-buffer calc-trail-buffer
1292 (if (eq cb calc-main-buffer
)
1293 ;; If there are other Calc stacks, make another one
1294 ;; the calc-main-buffer ...
1295 (if calc-buffer-list
1296 (setq calc-main-buffer
(car calc-buffer-list
))
1297 ;; ... otherwise kill the trail and its windows.
1298 (let ((wl (get-buffer-window-list calc-trail-buffer
)))
1300 (delete-window (car wl
))
1301 (setq wl
(cdr wl
))))
1302 (kill-buffer calc-trail-buffer
)
1303 (setq calc-trail-buffer nil
))))
1307 "Calculator major mode.
1309 This is an RPN calculator featuring arbitrary-precision integer, rational,
1310 floating-point, complex, matrix, and symbolic arithmetic.
1312 RPN calculation: 2 RET 3 + produces 5.
1313 Algebraic style: ' 2+3 RET produces 5.
1315 Basic operators are +, -, *, /, ^, & (reciprocal), % (modulo), n (change-sign).
1317 Press ? repeatedly for more complete help. Press `h i' to read the
1318 Calc manual on-line, `h s' to read the summary, or `h t' for the tutorial.
1320 Notations: 3.14e6 3.14 * 10^6
1321 _23 negative number -23 (or type `23 n')
1322 17:3 the fraction 17/3
1323 5:2:3 the fraction 5 and 2/3
1324 16#12C the integer 12C base 16 = 300 base 10
1325 8#177:100 the fraction 177:100 base 8 = 127:64 base 10
1326 (2, 4) complex number 2 + 4i
1327 (2; 4) polar complex number (r; theta)
1328 [1, 2, 3] vector ([[1, 2], [3, 4]] is a matrix)
1329 [1 .. 4) semi-open interval, 1 <= x < 4
1330 2 +/- 3 (p key) number with mean 2, standard deviation 3
1331 2 mod 3 (M key) number 2 computed modulo 3
1332 <1 jan 91> Date form (enter using ' key)
1339 (lambda (v) (set-default v
(symbol-value v
)))) calc-local-var-list
)
1340 (kill-all-local-variables)
1341 (use-local-map (if (eq calc-algebraic-mode
'total
)
1342 (progn (require 'calc-ext
) calc-alg-map
) calc-mode-map
))
1343 (mapc (function (lambda (v) (make-local-variable v
))) calc-local-var-list
)
1344 (make-local-variable 'overlay-arrow-position
)
1345 (make-local-variable 'overlay-arrow-string
)
1346 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
1347 (add-hook 'kill-buffer-query-functions
1348 'calc-kill-stack-buffer
1350 (setq truncate-lines t
)
1351 (setq buffer-read-only t
)
1352 (setq major-mode
'calc-mode
)
1353 (setq mode-name
"Calculator")
1354 (setq calc-stack-top
(length (or (memq (assq 'top-of-stack calc-stack
)
1356 (setq calc-stack
(list (list 'top-of-stack
1358 (setq calc-stack-top
(- (length calc-stack
) calc-stack-top -
1))
1359 (or calc-loaded-settings-file
1360 (null calc-settings-file
)
1361 (equal calc-settings-file user-init-file
)
1363 (setq calc-loaded-settings-file t
)
1364 (load (file-name-sans-extension calc-settings-file
) t
))) ; t = missing-ok
1365 (let ((p command-line-args
))
1367 (and (equal (car p
) "-f")
1368 (string-match "calc" (nth 1 p
))
1369 (string-match "full" (nth 1 p
))
1370 (setq calc-standalone-flag t
))
1372 (require 'calc-menu
)
1373 (run-mode-hooks 'calc-mode-hook
)
1375 (calc-set-mode-line)
1376 (calc-check-defines)
1377 (if calc-buffer-list
(setq calc-stack
(copy-sequence calc-stack
)))
1378 (add-to-list 'calc-buffer-list
(current-buffer) t
))
1380 (defvar calc-check-defines
'calc-check-defines
) ; suitable for run-hooks
1381 (defun calc-check-defines ()
1382 (if (symbol-plist 'calc-define
)
1383 (let ((plist (copy-sequence (symbol-plist 'calc-define
))))
1384 (while (and plist
(null (nth 1 plist
)))
1385 (setq plist
(cdr (cdr plist
))))
1389 (require 'calc-macs
)
1390 (set-buffer "*Calculator*")
1392 (put 'calc-define
(car plist
) nil
)
1393 (eval (nth 1 plist
))
1394 (setq plist
(cdr (cdr plist
))))
1395 ;; See if this has added any more calc-define properties.
1396 (calc-check-defines))
1397 (setplist 'calc-define nil
)))))
1399 (defun calc-trail-mode (&optional buf
)
1401 This mode is used by the *Calc Trail* buffer, which records all results
1402 obtained by the GNU Emacs Calculator.
1404 Calculator commands beginning with the `t' key are used to manipulate
1407 This buffer uses the same key map as the *Calculator* buffer; calculator
1408 commands given here will actually operate on the *Calculator* stack."
1411 (use-local-map calc-mode-map
)
1412 (setq major-mode
'calc-trail-mode
)
1413 (setq mode-name
"Calc Trail")
1414 (setq truncate-lines t
)
1415 (setq buffer-read-only t
)
1416 (make-local-variable 'overlay-arrow-position
)
1417 (make-local-variable 'overlay-arrow-string
)
1419 (set (make-local-variable 'calc-main-buffer
) buf
))
1420 (when (= (buffer-size) 0)
1421 (let ((buffer-read-only nil
))
1422 (insert (propertize "Emacs Calculator Trail\n" 'face
'italic
))))
1423 (run-mode-hooks 'calc-trail-mode-hook
))
1425 (defun calc-create-buffer ()
1426 "Create and initialize a buffer for the Calculator."
1427 (set-buffer (get-buffer-create "*Calculator*"))
1428 (or (eq major-mode
'calc-mode
)
1430 (setq max-lisp-eval-depth
(max max-lisp-eval-depth
1000))
1431 (when calc-always-load-extensions
1432 (require 'calc-ext
))
1435 (calc-set-language calc-language calc-language-option t
)))
1438 (defun calc (&optional arg full-display interactive
)
1439 "The Emacs Calculator. Full documentation is listed under \"calc-mode\"."
1440 (interactive "P\ni\np")
1444 (if (= (prefix-numeric-value arg
) -
1)
1445 (calc-grab-region (region-beginning) (region-end) nil
)
1446 (when (= (prefix-numeric-value arg
) -
2)
1448 (when (get-buffer-window "*Calc Keypad*")
1450 (set-buffer (window-buffer (selected-window))))
1451 (if (eq major-mode
'calc-mode
)
1453 (let ((oldbuf (current-buffer)))
1454 (calc-create-buffer)
1455 (setq calc-was-keypad-mode nil
)
1456 (if (or (eq full-display t
)
1457 (and (null full-display
) calc-full-mode
))
1458 (switch-to-buffer (current-buffer) t
)
1459 (if (get-buffer-window (current-buffer))
1460 (select-window (get-buffer-window (current-buffer)))
1461 (if calc-window-hook
1462 (run-hooks 'calc-window-hook
)
1463 (let ((w (get-largest-window)))
1464 (if (and pop-up-windows
1465 (> (window-height w
)
1466 (+ window-min-height calc-window-height
2)))
1468 (setq w
(split-window w
1469 (- (window-height w
)
1470 calc-window-height
2)
1472 (set-window-buffer w
(current-buffer))
1474 (pop-to-buffer (current-buffer)))))))
1475 (with-current-buffer (calc-trail-buffer)
1476 (and calc-display-trail
1477 (= (window-width) (frame-width))
1478 (calc-trail-display 1 t
)))
1479 (message "Welcome to the GNU Emacs Calculator! Press `?' or `h' for help, `q' to quit")
1480 (run-hooks 'calc-start-hook
)
1481 (and (windowp full-display
)
1482 (window-point full-display
)
1483 (select-window full-display
))
1484 (calc-check-defines)
1485 (when (and calc-said-hello interactive
)
1488 (setq calc-said-hello t
)))))
1491 (defun full-calc (&optional interactive
)
1492 "Invoke the Calculator and give it a full-sized window."
1494 (calc nil t interactive
))
1496 (defun calc-same-interface (arg)
1497 "Invoke the Calculator using the most recent interface (calc or calc-keypad)."
1499 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1500 (> (recursion-depth) 0))
1501 (exit-recursive-edit)
1502 (if (eq major-mode
'calc-edit-mode
)
1503 (calc-edit-finish arg
)
1504 (if calc-was-keypad-mode
1506 (calc arg calc-full-mode t
)))))
1508 (defun calc-quit (&optional non-fatal interactive
)
1509 "Quit the Calculator in an appropriate manner."
1510 (interactive "i\np")
1511 (and calc-standalone-flag
(not non-fatal
)
1512 (save-buffers-kill-emacs nil
))
1513 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1514 (> (recursion-depth) 0))
1515 (exit-recursive-edit))
1516 (if (eq major-mode
'calc-edit-mode
)
1518 (if (and interactive
1520 (eq (current-buffer) (aref calc-embedded-info
0)))
1522 (unless (eq major-mode
'calc-mode
)
1523 (calc-create-buffer))
1524 (run-hooks 'calc-end-hook
)
1525 (if (integerp calc-undo-length
)
1527 ((= calc-undo-length
0)
1528 (setq calc-undo-list nil calc-redo-list nil
))
1529 ((> calc-undo-length
0)
1530 (let ((tail (nthcdr (1- calc-undo-length
) calc-undo-list
)))
1531 (if tail
(setcdr tail nil
)))
1532 (setq calc-redo-list nil
))))
1533 (mapc (function (lambda (v) (set-default v
(symbol-value v
))))
1534 calc-local-var-list
)
1535 (let ((buf (current-buffer))
1536 (win (get-buffer-window (current-buffer)))
1537 (kbuf (get-buffer "*Calc Keypad*")))
1538 (delete-windows-on (calc-trail-buffer))
1539 ;; The next few lines will set `calc-window-height' so that the
1540 ;; next time Calc is called, the window will be the same size
1541 ;; as the current window.
1543 (not (window-full-height-p win
))
1544 (window-full-width-p win
) ; avoid calc-keypad
1545 (not (get-buffer-window "*Calc Keypad*")))
1546 (setq calc-window-height
(- (window-height win
) 2)))
1548 (delete-windows-on buf
)
1549 (and kbuf
(delete-windows-on kbuf
)))
1551 (bury-buffer calc-trail-buffer
)
1552 (and kbuf
(bury-buffer kbuf
))))))
1555 (defun quick-calc ()
1556 "Do a quick calculation in the minibuffer without invoking full Calculator."
1558 (calc-do-quick-calc))
1561 (defun calc-eval (str &optional separator
&rest args
)
1562 "Do a quick calculation and return the result as a string.
1563 Return value will either be the formatted result in string form,
1564 or a list containing a character position and an error message in string form."
1565 (calc-do-calc-eval str separator args
))
1568 (defun calc-keypad (&optional interactive
)
1569 "Invoke the Calculator in \"visual keypad\" mode.
1570 This is most useful in the X window system.
1571 In this mode, click on the Calc \"buttons\" using the left mouse button.
1572 Or, position the cursor manually and do M-x calc-keypad-press."
1575 (calc-do-keypad calc-full-mode interactive
))
1578 (defun full-calc-keypad (&optional interactive
)
1579 "Invoke the Calculator in full-screen \"visual keypad\" mode.
1580 See calc-keypad for details."
1583 (calc-do-keypad t interactive
))
1586 (defvar calc-aborted-prefix nil
)
1587 (defvar calc-start-time nil
)
1588 (defvar calc-command-flags nil
)
1589 (defvar calc-final-point-line
)
1590 (defvar calc-final-point-column
)
1591 ;;; Note that modifications to this function may break calc-pass-errors.
1592 (defun calc-do (do-body &optional do-slow
)
1593 (calc-check-defines)
1594 (let* ((calc-command-flags nil
)
1595 (calc-start-time (and calc-timing
(not calc-start-time
)
1597 (current-time-string)))
1598 (gc-cons-threshold (max gc-cons-threshold
1599 (if calc-timing
2000000 100000)))
1600 calc-final-point-line calc-final-point-column
)
1601 (setq calc-aborted-prefix
"")
1605 (if calc-embedded-info
1606 (calc-embedded-select-buffer)
1607 (calc-select-buffer))
1608 (and (eq calc-algebraic-mode
'total
)
1610 (use-local-map calc-alg-map
))
1611 (when (and do-slow calc-display-working-message
)
1612 (message "Working...")
1613 (calc-set-command-flag 'clear-message
))
1615 (setq calc-aborted-prefix nil
)
1616 (when (memq 'renum-stack calc-command-flags
)
1617 (calc-renumber-stack))
1618 (when (memq 'clear-message calc-command-flags
)
1621 (if (and (eq (car err
) 'error
)
1622 (stringp (nth 1 err
))
1623 (string-match "max-specpdl-size\\|max-lisp-eval-depth"
1625 (error "Computation got stuck or ran too long. Type `M' to increase the limit")
1626 (setq calc-aborted-prefix nil
)
1627 (signal (car err
) (cdr err
)))))
1628 (when calc-aborted-prefix
1629 (calc-record "<Aborted>" calc-aborted-prefix
))
1630 (and calc-start-time
1631 (let* ((calc-internal-prec 12)
1632 (calc-date-format nil
)
1633 (end-time (current-time-string))
1634 (time (if (equal calc-start-time end-time
)
1637 (calcFunc-unixtime (math-parse-date end-time
) 0)
1638 (calcFunc-unixtime (math-parse-date calc-start-time
)
1640 (if (math-lessp 1 time
)
1641 (calc-record time
"(t)"))))
1642 (or (memq 'no-align calc-command-flags
)
1643 (eq major-mode
'calc-trail-mode
)
1644 (calc-align-stack-window))
1645 (and (memq 'position-point calc-command-flags
)
1646 (if (eq major-mode
'calc-mode
)
1648 (goto-char (point-min))
1649 (forward-line (1- calc-final-point-line
))
1650 (move-to-column calc-final-point-column
))
1651 (save-current-buffer
1652 (calc-select-buffer)
1653 (goto-char (point-min))
1654 (forward-line (1- calc-final-point-line
))
1655 (move-to-column calc-final-point-column
))))
1656 (unless (memq 'keep-flags calc-command-flags
)
1658 (calc-select-buffer)
1659 (setq calc-inverse-flag nil
1660 calc-hyperbolic-flag nil
1661 calc-option-flag nil
1662 calc-keep-args-flag nil
)))
1663 (when (memq 'do-edit calc-command-flags
)
1664 (switch-to-buffer (get-buffer-create "*Calc Edit*")))
1665 (calc-set-mode-line)
1666 (when calc-embedded-info
1667 (calc-embedded-finish-command))))
1668 (identity nil
)) ; allow a GC after timing is done
1671 (defun calc-set-command-flag (f)
1672 (unless (memq f calc-command-flags
)
1673 (setq calc-command-flags
(cons f calc-command-flags
))))
1675 (defun calc-select-buffer ()
1676 (or (eq major-mode
'calc-mode
)
1677 (if calc-main-buffer
1678 (set-buffer calc-main-buffer
)
1679 (let ((buf (get-buffer "*Calculator*")))
1682 (error "Calculator buffer not available"))))))
1684 (defun calc-cursor-stack-index (&optional index
)
1685 (goto-char (point-max))
1686 (forward-line (- (calc-substack-height (or index
1)))))
1688 (defun calc-stack-size ()
1689 (- (length calc-stack
) calc-stack-top
))
1691 (defun calc-substack-height (n)
1694 (setq n
(+ n calc-stack-top
))
1695 (while (and (> n
0) stack
)
1696 (setq sum
(+ sum
(nth 1 (car stack
)))
1701 (defun calc-set-mode-line ()
1703 (calc-select-buffer)
1704 (let* ((fmt (car calc-float-format
))
1705 (figs (nth 1 calc-float-format
))
1707 (format "Calc%s%s: %d %s %-14s"
1708 (if (and calc-embedded-info
1709 (eq (aref calc-embedded-info
1) (current-buffer)))
1711 (if (and (> (length (buffer-name)) 12)
1712 (equal (substring (buffer-name) 0 12)
1714 (substring (buffer-name) 12)
1717 (capitalize (symbol-name calc-angle-mode
))
1720 ;; Input-related modes
1721 (if (eq calc-algebraic-mode
'total
) "Alg* "
1722 (if calc-algebraic-mode
"Alg "
1723 (if calc-incomplete-algebraic-mode
"Alg[( " "")))
1725 ;; Computational modes
1726 (if calc-symbolic-mode
"Symb " "")
1727 (cond ((eq calc-matrix-mode
'matrix
) "Matrix ")
1728 ((integerp calc-matrix-mode
)
1729 (format "Matrix%d " calc-matrix-mode
))
1730 ((eq calc-matrix-mode
'sqmatrix
) "SqMatrix ")
1731 ((eq calc-matrix-mode
'scalar
) "Scalar ")
1733 (if (eq calc-complex-mode
'polar
) "Polar " "")
1734 (if calc-prefer-frac
"Frac " "")
1735 (cond ((null calc-infinite-mode
) "")
1736 ((eq calc-infinite-mode
1) "+Inf ")
1738 (cond ((eq calc-simplify-mode
'none
) "NoSimp ")
1739 ((eq calc-simplify-mode
'num
) "NumSimp ")
1740 ((eq calc-simplify-mode
'binary
)
1741 (format "BinSimp%d " calc-word-size
))
1742 ((eq calc-simplify-mode
'alg
) "AlgSimp ")
1743 ((eq calc-simplify-mode
'ext
) "ExtSimp ")
1744 ((eq calc-simplify-mode
'units
) "UnitSimp ")
1748 (cond ((= calc-number-radix
10) "")
1749 ((= calc-number-radix
2) "Bin ")
1750 ((= calc-number-radix
8) "Oct ")
1751 ((= calc-number-radix
16) "Hex ")
1752 (t (format "Radix%d " calc-number-radix
)))
1753 (if calc-twos-complement-mode
"TwosComp " "")
1754 (if calc-leading-zeros
"Zero " "")
1755 (cond ((null calc-language
) "")
1756 ((get calc-language
'math-lang-name
)
1757 (concat (get calc-language
'math-lang-name
) " "))
1759 (capitalize (symbol-name calc-language
))
1761 (cond ((eq fmt
'float
)
1762 (if (zerop figs
) "" (format "Norm%d " figs
)))
1763 ((eq fmt
'fix
) (format "Fix%d " figs
))
1765 (if (zerop figs
) "Sci " (format "Sci%d " figs
)))
1767 (if (zerop figs
) "Eng " (format "Eng%d " figs
))))
1768 (cond ((not calc-display-just
)
1769 (if calc-display-origin
1770 (format "Left%d " calc-display-origin
) ""))
1771 ((eq calc-display-just
'right
)
1772 (if calc-display-origin
1773 (format "Right%d " calc-display-origin
)
1776 (if calc-display-origin
1777 (format "Center%d " calc-display-origin
)
1779 (cond ((integerp calc-line-breaking
)
1780 (format "Wid%d " calc-line-breaking
))
1781 (calc-line-breaking "")
1784 ;; Miscellaneous other modes/indicators
1785 (if calc-assoc-selections
"" "Break ")
1786 (cond ((eq calc-mode-save-mode
'save
) "Save ")
1787 ((not calc-embedded-info
) "")
1788 ((eq calc-mode-save-mode
'local
) "Local ")
1789 ((eq calc-mode-save-mode
'edit
) "LocEdit ")
1790 ((eq calc-mode-save-mode
'perm
) "LocPerm ")
1791 ((eq calc-mode-save-mode
'global
) "Global ")
1793 (if calc-auto-recompute
"" "Manual ")
1794 (if (and (fboundp 'calc-gnuplot-alive
)
1795 (calc-gnuplot-alive)) "Graph " "")
1796 (if (and calc-embedded-info
1797 (> (calc-stack-size) 0)
1798 (calc-top 1 'sel
)) "Sel " "")
1799 (if calc-display-dirty
"Dirty " "")
1800 (if calc-option-flag
"Opt " "")
1801 (if calc-inverse-flag
"Inv " "")
1802 (if calc-hyperbolic-flag
"Hyp " "")
1803 (if calc-keep-args-flag
"Keep " "")
1804 (if (/= calc-stack-top
1) "Narrow " "")
1805 (apply 'concat calc-other-modes
)))))
1806 (if (equal new-mode-string mode-line-buffer-identification
)
1808 (setq mode-line-buffer-identification new-mode-string
)
1809 (set-buffer-modified-p (buffer-modified-p))
1810 (and calc-embedded-info
(calc-embedded-mode-line-change))))))
1812 (defun calc-align-stack-window ()
1813 (if (eq major-mode
'calc-mode
)
1815 (let ((win (get-buffer-window (current-buffer))))
1818 (calc-cursor-stack-index 0)
1819 (vertical-motion (- 2 (window-height win
)))
1820 (set-window-start win
(point)))))
1821 (calc-cursor-stack-index 0)
1822 (if (looking-at " *\\.$")
1823 (goto-char (1- (match-end 0)))))
1825 (calc-select-buffer)
1826 (calc-align-stack-window))))
1828 (defun calc-check-stack (n)
1829 (if (> n
(calc-stack-size))
1830 (error "Too few elements on stack"))
1832 (error "Invalid argument")))
1834 (defun calc-push-list (vals &optional m sels
)
1836 (if calc-executing-macro
1837 (calc-push-list-in-macro vals m sels
)
1839 (calc-select-buffer)
1840 (let* ((val (car vals
))
1841 (entry (list val
1 (car sels
)))
1842 (mm (+ (or m
1) calc-stack-top
)))
1843 (calc-cursor-stack-index (1- (or m
1)))
1845 (setcdr (nthcdr (- mm
2) calc-stack
)
1846 (cons entry
(nthcdr (1- mm
) calc-stack
)))
1847 (setq calc-stack
(cons entry calc-stack
)))
1848 (let ((buffer-read-only nil
))
1849 (insert (math-format-stack-value entry
) "\n"))
1850 (calc-record-undo (list 'push mm
))
1851 (calc-set-command-flag 'renum-stack
))))
1852 (setq vals
(cdr vals
)
1855 (defun calc-pop-push-list (n vals
&optional m sels
)
1856 (if (and calc-any-selections
(null sels
))
1857 (calc-replace-selections n vals m
)
1858 (calc-pop-stack n m sels
)
1859 (calc-push-list vals m sels
)))
1861 (defun calc-pop-push-record-list (n prefix vals
&optional m sels
)
1862 (or (and (consp vals
)
1863 (or (integerp (car vals
))
1864 (consp (car vals
))))
1865 (and vals
(setq vals
(list vals
)
1866 sels
(and sels
(list sels
)))))
1867 (calc-check-stack (+ n
(or m
1) -
1))
1870 (calc-record-list vals prefix
)
1871 (calc-record (car vals
) prefix
)))
1872 (calc-pop-push-list n vals m sels
))
1874 (defun calc-enter-result (n prefix vals
&optional m
)
1875 (setq calc-aborted-prefix prefix
)
1876 (if (and (consp vals
)
1877 (or (integerp (car vals
))
1878 (consp (car vals
))))
1879 (setq vals
(mapcar 'calc-normalize vals
))
1880 (setq vals
(calc-normalize vals
)))
1881 (or (and (consp vals
)
1882 (or (integerp (car vals
))
1883 (consp (car vals
))))
1884 (setq vals
(list vals
)))
1885 (if (equal vals
'((nil)))
1887 (calc-pop-push-record-list n prefix vals m
)
1890 (defun calc-normalize (val)
1891 (if (memq calc-simplify-mode
'(nil none num
))
1892 (math-normalize val
)
1894 (calc-normalize-fancy val
)))
1896 (defun calc-handle-whys ()
1898 (calc-do-handle-whys)))
1901 (defun calc-pop-stack (&optional n m sel-ok
) ; pop N objs at level M of stack.
1904 (or calc-keep-args-flag
1905 (let ((mm (+ m calc-stack-top
)))
1906 (if (and calc-any-selections
(not sel-ok
)
1907 (calc-top-selected n m
))
1909 (if calc-executing-macro
1910 (calc-pop-stack-in-macro n mm
)
1911 (calc-record-undo (list 'pop mm
(calc-top-list n m
'full
)))
1913 (calc-select-buffer)
1914 (let ((buffer-read-only nil
))
1917 (calc-cursor-stack-index (1- m
))
1918 (let ((bot (point)))
1919 (calc-cursor-stack-index (+ n m -
1))
1920 (delete-region (point) bot
))
1921 (setcdr (nthcdr (- mm
2) calc-stack
)
1922 (nthcdr (+ n mm -
1) calc-stack
)))
1923 (calc-cursor-stack-index n
)
1924 (setq calc-stack
(nthcdr n calc-stack
))
1925 (delete-region (point) (point-max))))
1926 (calc-set-command-flag 'renum-stack
))))))
1929 (defun calc-get-stack-element (x)
1930 (cond ((eq sel-mode
'entry
)
1934 ((or (null (nth 2 x
))
1936 (not calc-use-selections
))
1942 ;; Get the Nth element of the stack (N=1 is the top element).
1943 (defun calc-top (&optional n sel-mode
)
1945 (calc-check-stack n
)
1946 (calc-get-stack-element (nth (+ n calc-stack-top -
1) calc-stack
)))
1948 (defun calc-top-n (&optional n sel-mode
) ; in case precision has changed
1949 (math-check-complete (calc-normalize (calc-top n sel-mode
))))
1951 (defun calc-top-list (&optional n m sel-mode
)
1954 (calc-check-stack (+ n m -
1))
1956 (let ((top (copy-sequence (nthcdr (+ m calc-stack-top -
1)
1958 (setcdr (nthcdr (1- n
) top
) nil
)
1959 (nreverse (mapcar 'calc-get-stack-element top
)))))
1961 (defun calc-top-list-n (&optional n m sel-mode
)
1962 (mapcar 'math-check-complete
1963 (mapcar 'calc-normalize
(calc-top-list n m sel-mode
))))
1966 (defun calc-renumber-stack ()
1967 (if calc-line-numbering
1969 (calc-cursor-stack-index 0)
1971 (buffer-read-only nil
)
1972 (stack (nthcdr calc-stack-top calc-stack
)))
1973 (if (re-search-forward "^[0-9]+[:*]" nil t
)
1976 (while (re-search-forward "^[0-9]+[:*]" nil t
)
1977 (let ((buffer-read-only nil
))
1981 (calc-cursor-stack-index 0)))
1982 (while (re-search-backward "^[0-9]+[:*]" nil t
)
1985 (insert (format "%03d%s" (% lnum
1000)
1986 (if (and (nth 2 (car stack
))
1987 calc-use-selections
) "*" ":")))
1988 (let ((prefix (int-to-string lnum
)))
1989 (insert prefix
(if (and (nth 2 (car stack
))
1990 calc-use-selections
) "*" ":")
1991 (make-string (- 3 (length prefix
)) 32))))
1993 (setq lnum
(1+ lnum
)
1994 stack
(cdr stack
))))))
1995 (and calc-embedded-info
(calc-embedded-stack-change)))
1997 (defvar calc-any-evaltos nil
)
1998 (defun calc-refresh (&optional align
)
2000 (and (eq major-mode
'calc-mode
)
2001 (not calc-executing-macro
)
2002 (let* ((buffer-read-only nil
)
2003 (save-point (point))
2004 (save-mark (condition-case err
(mark) (error nil
)))
2005 (save-aligned (looking-at "\\.$"))
2007 (calc-any-evaltos nil
))
2008 (setq calc-any-selections nil
)
2010 (when calc-show-banner
2011 (insert (propertize "--- Emacs Calculator Mode ---\n"
2014 (goto-char (point-min))
2015 (when calc-show-banner
2017 (insert (math-format-stack-value (car thing
)) "\n")
2018 (setq thing
(cdr thing
)))
2019 (calc-renumber-stack)
2020 (if calc-display-dirty
2021 (calc-wrapper (setq calc-display-dirty nil
)))
2022 (and calc-any-evaltos calc-auto-recompute
2023 (calc-wrapper (calc-refresh-evaltos)))
2024 (if (or align save-aligned
)
2025 (calc-align-stack-window)
2026 (goto-char save-point
))
2027 (if save-mark
(set-mark save-mark
))))
2028 (and calc-embedded-info
(not (eq major-mode
'calc-mode
))
2029 (with-current-buffer (aref calc-embedded-info
1)
2030 (calc-refresh align
)))
2031 (setq calc-refresh-count
(1+ calc-refresh-count
)))
2033 ;;;; The Calc Trail buffer.
2035 (defun calc-check-trail-aligned ()
2037 (let ((win (get-buffer-window (current-buffer))))
2039 (pos-visible-in-window-p (1- (point-max)) win
)))))
2041 (defun calc-trail-buffer ()
2042 (and (or (null calc-trail-buffer
)
2043 (null (buffer-name calc-trail-buffer
)))
2045 (setq calc-trail-buffer
(get-buffer-create "*Calc Trail*"))
2046 (let ((buf (or (and (not (eq major-mode
'calc-mode
))
2047 (get-buffer "*Calculator*"))
2049 (set-buffer calc-trail-buffer
)
2050 (or (eq major-mode
'calc-trail-mode
)
2051 (calc-trail-mode buf
)))))
2052 (or (and calc-trail-pointer
2053 (eq (marker-buffer calc-trail-pointer
) calc-trail-buffer
))
2054 (with-current-buffer calc-trail-buffer
2055 (goto-char (point-min))
2057 (setq calc-trail-pointer
(point-marker))))
2060 (defun calc-record (val &optional prefix
)
2061 (setq calc-aborted-prefix nil
)
2062 (or calc-executing-macro
2063 (let* ((mainbuf (current-buffer))
2064 (buf (calc-trail-buffer))
2065 (calc-display-raw nil
)
2066 (calc-can-abbrev-vectors t
)
2070 (math-showing-full-precision
2071 (math-format-flat-expr val
0)))
2073 (with-current-buffer buf
2074 (let ((aligned (calc-check-trail-aligned))
2075 (buffer-read-only nil
))
2076 (goto-char (point-max))
2077 (cond ((null prefix
) (insert " "))
2078 ((and (> (length prefix
) 4)
2079 (string-match " " prefix
4))
2080 (insert (substring prefix
0 4) " "))
2081 (t (insert (format "%4s " prefix
))))
2083 (let ((win (get-buffer-window buf
)))
2084 (if (and aligned win
(not (memq 'hold-trail calc-command-flags
)))
2086 (goto-char (1- (point-max))))))))
2090 (defun calc-trail-display (flag &optional no-refresh interactive
)
2091 (interactive "P\ni\np")
2092 (let ((win (get-buffer-window (calc-trail-buffer))))
2093 (if (setq calc-display-trail
2094 (not (if flag
(memq flag
'(nil 0)) win
)))
2097 (if calc-trail-window-hook
2098 (run-hooks 'calc-trail-window-hook
)
2099 (let ((w (split-window nil
(/ (* (window-width) 2) 3) t
)))
2100 (set-window-buffer w calc-trail-buffer
)))
2102 (setq overlay-arrow-string calc-trail-overlay
2103 overlay-arrow-position calc-trail-pointer
)
2115 (calc-refresh))))))))
2118 (defun calc-trail-here ()
2120 (if (eq major-mode
'calc-trail-mode
)
2127 (if (or (bobp) (eobp))
2128 (setq overlay-arrow-position nil
) ; trail is empty
2129 (set-marker calc-trail-pointer
(point) (current-buffer))
2130 (setq calc-trail-overlay
(concat (buffer-substring (point)
2133 overlay-arrow-string calc-trail-overlay
2134 overlay-arrow-position calc-trail-pointer
)
2136 (let ((win (get-buffer-window (current-buffer))))
2139 (forward-line (/ (window-height win
) 2))
2140 (forward-line (- 1 (window-height win
)))
2141 (set-window-start win
(point))
2142 (set-window-point win
(+ calc-trail-pointer
4))
2143 (set-buffer calc-main-buffer
)
2144 (setq overlay-arrow-string calc-trail-overlay
2145 overlay-arrow-position calc-trail-pointer
))))))
2146 (error "Not in Calc Trail buffer")))
2153 (defun calc-record-undo (rec)
2154 (or calc-executing-macro
2155 (if (memq 'undo calc-command-flags
)
2156 (setq calc-undo-list
(cons (cons rec
(car calc-undo-list
))
2157 (cdr calc-undo-list
)))
2158 (setq calc-undo-list
(cons (list rec
) calc-undo-list
)
2160 (calc-set-command-flag 'undo
))))
2165 ;;; Arithmetic commands.
2167 (defun calc-binary-op (name func arg
&optional ident unary func2
)
2168 (setq calc-aborted-prefix name
)
2170 (calc-enter-result 2 name
(cons (or func2 func
)
2171 (mapcar 'math-check-complete
2172 (calc-top-list 2))))
2174 (calc-binary-op-fancy name func arg ident unary
)))
2176 (defun calc-unary-op (name func arg
&optional func2
)
2177 (setq calc-aborted-prefix name
)
2179 (calc-enter-result 1 name
(list (or func2 func
)
2180 (math-check-complete (calc-top 1))))
2182 (calc-unary-op-fancy name func arg
)))
2185 (defun calc-plus (arg)
2188 (calc-binary-op "+" 'calcFunc-add arg
0 nil
'+)))
2190 (defun calc-minus (arg)
2193 (calc-binary-op "-" 'calcFunc-sub arg
0 'neg
'-
)))
2195 (defun calc-times (arg)
2198 (calc-binary-op "*" 'calcFunc-mul arg
1 nil
'*)))
2200 (defun calc-divide (arg)
2203 (calc-binary-op "/" 'calcFunc-div arg
0 'calcFunc-inv
'/)))
2205 (defun calc-left-divide (arg)
2208 (calc-binary-op "ldiv" 'calcFunc-ldiv arg
0 nil nil
)))
2210 (defun calc-change-sign (arg)
2213 (calc-unary-op "chs" 'neg arg
)))
2217 ;;; Stack management commands.
2219 (defun calc-enter (n)
2223 (calc-push-list (calc-top-list 1 (- n
))))
2225 (calc-push-list (calc-top-list (calc-stack-size))))
2227 (calc-push-list (calc-top-list n
))))))
2233 (let* ((nn (prefix-numeric-value n
))
2234 (top (and (null n
) (calc-top 1))))
2235 (cond ((and (null n
)
2236 (eq (car-safe top
) 'incomplete
)
2237 (> (length top
) (if (eq (nth 1 top
) 'intv
) 3 2)))
2238 (calc-pop-push-list 1 (let ((tt (copy-sequence top
)))
2239 (setcdr (nthcdr (- (length tt
) 2) tt
) nil
)
2242 (if (and calc-any-selections
2243 (calc-top-selected 1 (- nn
)))
2244 (calc-delete-selection (- nn
))
2245 (calc-pop-stack 1 (- nn
) t
)))
2247 (calc-pop-stack (calc-stack-size) 1 t
))
2249 (if (and calc-any-selections
2251 (calc-top-selected 1 1))
2252 (calc-delete-selection 1)
2253 (calc-pop-stack nn
)))))))
2258 ;;;; Reading a number using the minibuffer.
2259 (defvar calc-buffer
)
2260 (defvar calc-prev-char
)
2261 (defvar calc-prev-prev-char
)
2262 (defvar calc-digit-value
)
2263 (defun calcDigit-start ()
2266 (if (or calc-algebraic-mode
2267 (and (> calc-number-radix
14) (eq last-command-event ?e
)))
2268 (calc-alg-digit-entry)
2269 (calc-unread-command)
2270 (setq calc-aborted-prefix nil
)
2271 (let* ((calc-digit-value nil
)
2272 (calc-prev-char nil
)
2273 (calc-prev-prev-char nil
)
2274 (calc-buffer (current-buffer))
2275 (buf (if (featurep 'xemacs
)
2277 (catch 'execute-kbd-macro
2279 (read-from-minibuffer
2280 "Calc: " "" calc-digit-map
)))
2281 (error "XEmacs requires RET after %s"
2282 "digit entry in kbd macro"))
2283 (let ((old-esc (lookup-key global-map
"\e")))
2286 (define-key global-map
"\e" nil
)
2287 (read-from-minibuffer "Calc: " "" calc-digit-map
))
2288 (define-key global-map
"\e" old-esc
))))))
2289 (or calc-digit-value
(setq calc-digit-value
(math-read-number buf
)))
2290 (if (stringp calc-digit-value
)
2291 (calc-alg-entry calc-digit-value
)
2292 (if calc-digit-value
2293 (calc-push-list (list (calc-record (calc-normalize
2294 calc-digit-value
))))))
2295 (if (eq calc-prev-char
'dots
)
2300 (defsubst calc-minibuffer-size
()
2301 (- (point-max) (minibuffer-prompt-end)))
2303 (defun calcDigit-nondigit ()
2305 ;; Exercise for the reader: Figure out why this is a good precaution!
2306 (or (boundp 'calc-buffer
)
2307 (use-local-map minibuffer-local-map
))
2308 (let ((str (minibuffer-contents)))
2309 (setq calc-digit-value
(with-current-buffer calc-buffer
2310 (math-read-number str
))))
2311 (if (and (null calc-digit-value
) (> (calc-minibuffer-size) 0))
2314 (calc-temp-minibuffer-message " [Bad format]"))
2315 (or (memq last-command-event
'(32 13))
2316 (progn (setq prefix-arg current-prefix-arg
)
2317 (calc-unread-command (if (and (eq last-command-event
27)
2318 (>= last-input-event
128))
2324 (defun calc-minibuffer-contains (rex)
2326 (goto-char (minibuffer-prompt-end))
2329 (defun calcDigit-key ()
2331 (goto-char (point-max))
2332 (if (or (and (memq last-command-event
'(?
+ ?-
))
2334 (/= (preceding-char) ?e
))
2335 (and (memq last-command-event
'(?m ?s
))
2336 (not (calc-minibuffer-contains "[-+]?[0-9]+\\.?0*[@oh].*"))
2337 (not (calc-minibuffer-contains "[-+]?\\(1[1-9]\\|[2-9][0-9]\\)#.*"))))
2338 (calcDigit-nondigit)
2339 (if (calc-minibuffer-contains "\\([-+]?\\|.* \\)\\'")
2340 (cond ((memq last-command-event
'(?. ?
@)) (insert "0"))
2341 ((and (memq last-command-event
'(?o ?h ?m
))
2342 (not (calc-minibuffer-contains ".*#.*"))) (insert "0"))
2343 ((memq last-command-event
'(?
: ?e
)) (insert "1"))
2344 ((eq last-command-event ?
#)
2345 (insert (int-to-string calc-number-radix
)))))
2346 (if (and (calc-minibuffer-contains "\\([-+]?[0-9]+#\\|[^:]*:\\)\\'")
2347 (eq last-command-event ?
:))
2349 (if (and (calc-minibuffer-contains "[-+]?[0-9]+#\\'")
2350 (eq last-command-event ?.
))
2352 (if (and (calc-minibuffer-contains "[-+]?0*\\([2-9]\\|1[0-4]\\)#\\'")
2353 (eq last-command-event ?e
))
2355 (if (or (and (memq last-command-event
'(?h ?o ?m ?s ?p
))
2356 (calc-minibuffer-contains ".*#.*"))
2357 (and (eq last-command-event ?e
)
2358 (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2359 (and (eq last-command-event ?n
)
2360 (calc-minibuffer-contains "[-+]?\\(2[4-9]\\|[3-9][0-9]\\)#.*")))
2361 (setq last-command-event
(upcase last-command-event
)))
2363 ((memq last-command-event
'(?_ ?n
))
2364 (goto-char (minibuffer-prompt-end))
2365 (if (and (search-forward " +/- " nil t
)
2366 (not (search-forward "e" nil t
)))
2368 (and (not (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2369 (search-forward "e" nil t
))
2370 (if (looking-at "+")
2372 (if (looking-at "-")
2375 (goto-char (point-max)))
2376 ((eq last-command-event ?p
)
2377 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2378 (calc-minibuffer-contains ".*mod.*")
2379 (calc-minibuffer-contains ".*#.*")
2380 (calc-minibuffer-contains ".*[-+e:]\\'"))
2382 (if (not (calc-minibuffer-contains ".* \\'"))
2385 ((and (eq last-command-event ?M
)
2386 (not (calc-minibuffer-contains
2387 "[-+]?\\(2[3-9]\\|[3-9][0-9]\\)#.*")))
2388 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2389 (calc-minibuffer-contains ".*mod *[^ ]+")
2390 (calc-minibuffer-contains ".*[-+e:]\\'"))
2392 (if (calc-minibuffer-contains ".*mod \\'")
2393 (if calc-previous-modulo
2394 (insert (math-format-flat-expr calc-previous-modulo
0))
2396 (if (not (calc-minibuffer-contains ".* \\'"))
2400 (insert (char-to-string last-command-event
))
2401 (if (or (and (calc-minibuffer-contains "[-+]?\\(.*\\+/- *\\|.*mod *\\)?\\([0-9][0-9]?\\)#[#]?[0-9a-zA-Z]*\\(:[0-9a-zA-Z]*\\(:[0-9a-zA-Z]*\\)?\\|.[0-9a-zA-Z]*\\(e[-+]?[0-9]*\\)?\\)?\\'")
2402 (let ((radix (string-to-number
2404 (match-beginning 2) (match-end 2)))))
2407 (or (memq last-command-event
'(?
# ?
: ?. ?e ?
+ ?-
))
2408 (let ((dig (math-read-radix-digit
2409 (upcase last-command-event
))))
2412 (calc-minibuffer-contains
2413 "[-+]?\\(.*\\+/- *\\|.*mod *\\)?\\([0-9]+\\.?0*[@oh] *\\)?\\([0-9]+\\.?0*['m] *\\)?[0-9]*\\(\\.?[0-9]*\\(e[-+]?[0-3]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?\\)?\\|[0-9]:\\([0-9]+:\\)?[0-9]*\\)?[\"s]?\\'"))
2414 (if (and (memq last-command-event
'(?
@ ?o ?h ?
\' ?m
))
2415 (string-match " " calc-hms-format
))
2417 (if (and (eq this-command last-command
)
2418 (eq last-command-event ?.
))
2424 (calc-temp-minibuffer-message " [Bad format]"))))))
2425 (setq calc-prev-prev-char calc-prev-char
2426 calc-prev-char last-command-event
))
2429 (defun calcDigit-backspace ()
2431 (goto-char (point-max))
2432 (cond ((calc-minibuffer-contains ".* \\+/- \\'")
2433 (backward-delete-char 5))
2434 ((calc-minibuffer-contains ".* mod \\'")
2435 (backward-delete-char 5))
2436 ((calc-minibuffer-contains ".* \\'")
2437 (backward-delete-char 2))
2438 ((eq last-command
'calcDigit-start
)
2440 (t (backward-delete-char 1)))
2441 (if (= (calc-minibuffer-size) 0)
2443 (setq last-command-event
13)
2444 (calcDigit-nondigit))))
2449 (defconst math-bignum-digit-length
2450 (truncate (/ (log10 (/ most-positive-fixnum
2)) 2))
2451 "The length of a \"digit\" in Calc bignums.
2452 If a big integer is of the form (bigpos N0 N1 ...), this is the
2453 length of the allowable Emacs integers N0, N1,...
2454 The value of 2*10^(2*MATH-BIGNUM-DIGIT-LENGTH) must be less than the
2455 largest Emacs integer.")
2457 (defconst math-bignum-digit-size
2458 (expt 10 math-bignum-digit-length
)
2459 "An upper bound for the size of the \"digit\"s in Calc bignums.")
2461 (defconst math-small-integer-size
2462 (expt math-bignum-digit-size
2)
2463 "An upper bound for the size of \"small integer\"s in Calc.")
2466 ;;;; Arithmetic routines.
2468 ;; An object as manipulated by one of these routines may take any of the
2471 ;; integer An integer. For normalized numbers, this format
2473 ;; negative math-small-integer-size + 1 to
2474 ;; math-small-integer-size - 1
2476 ;; (bigpos N0 N1 N2 ...) A big positive integer,
2477 ;; N0 + N1*math-bignum-digit-size
2478 ;; + N2*(math-bignum-digit-size)^2 ...
2479 ;; (bigneg N0 N1 N2 ...) A big negative integer,
2480 ;; - N0 - N1*math-bignum-digit-size ...
2481 ;; Each digit N is in the range
2482 ;; 0 ... math-bignum-digit-size -1.
2483 ;; Normalized, always at least three N present,
2484 ;; and the most significant N is nonzero.
2486 ;; (frac NUM DEN) A fraction. NUM and DEN are small or big integers.
2487 ;; Normalized, DEN > 1.
2489 ;; (float NUM EXP) A floating-point number, NUM * 10^EXP;
2490 ;; NUM is a small or big integer, EXP is a small int.
2491 ;; Normalized, NUM is not a multiple of 10, and
2492 ;; abs(NUM) < 10^calc-internal-prec.
2493 ;; Normalized zero is stored as (float 0 0).
2495 ;; (cplx REAL IMAG) A complex number; REAL and IMAG are any of above.
2496 ;; Normalized, IMAG is nonzero.
2498 ;; (polar R THETA) Polar complex number. Normalized, R > 0 and THETA
2499 ;; is neither zero nor 180 degrees (pi radians).
2501 ;; (vec A B C ...) Vector of objects A, B, C, ... A matrix is a
2502 ;; vector of vectors.
2504 ;; (hms H M S) Angle in hours-minutes-seconds form. All three
2505 ;; components have the same sign; H and M must be
2506 ;; numerically integers; M and S are expected to
2507 ;; lie in the range [0,60).
2509 ;; (date N) A date or date/time object. N is an integer to
2510 ;; store a date only, or a fraction or float to
2511 ;; store a date and time.
2513 ;; (sdev X SIGMA) Error form, X +/- SIGMA. When normalized,
2514 ;; SIGMA > 0. X is any complex number and SIGMA
2515 ;; is real numbers; or these may be symbolic
2516 ;; expressions where SIGMA is assumed real.
2518 ;; (intv MASK LO HI) Interval form. MASK is 0=(), 1=(], 2=[), or 3=[].
2519 ;; LO and HI are any real numbers, or symbolic
2520 ;; expressions which are assumed real, and LO < HI.
2521 ;; For [LO..HI], if LO = HI normalization produces LO,
2522 ;; and if LO > HI normalization produces [LO..LO).
2523 ;; For other intervals, if LO > HI normalization
2524 ;; sets HI equal to LO.
2526 ;; (mod N M) Number modulo M. When normalized, 0 <= N < M.
2527 ;; N and M are real numbers.
2529 ;; (var V S) Symbolic variable. V is a Lisp symbol which
2530 ;; represents the variable's visible name. S is
2531 ;; the symbol which actually stores the variable's
2532 ;; value: (var pi var-pi).
2534 ;; In general, combining rational numbers in a calculation always produces
2535 ;; a rational result, but if either argument is a float, result is a float.
2537 ;; In the following comments, [x y z] means result is x, args must be y, z,
2538 ;; respectively, where the code letters are:
2540 ;; O Normalized object (vector or number)
2541 ;; V Normalized vector
2542 ;; N Normalized number of any type
2543 ;; N Normalized complex number
2544 ;; R Normalized real number (float or rational)
2545 ;; F Normalized floating-point number
2546 ;; T Normalized rational number
2547 ;; I Normalized integer
2548 ;; B Normalized big integer
2549 ;; S Normalized small integer
2550 ;; D Digit (small integer, 0..999)
2551 ;; L Normalized bignum digit list (without "bigpos" or "bigneg" symbol)
2552 ;; or normalized vector element list (without "vec")
2553 ;; P Predicate (truth value)
2554 ;; X Any Lisp object
2557 ;; Lower-case letters signify possibly un-normalized values.
2558 ;; "L.D" means a cons of an L and a D.
2559 ;; [N N; n n] means result will be normalized if argument is.
2560 ;; Also, [Public] marks routines intended to be called from outside.
2561 ;; [This notation has been neglected in many recent routines.]
2563 (defvar math-eval-rules-cache
)
2564 (defvar math-eval-rules-cache-other
)
2565 ;;; Reduce an object to canonical (normalized) form. [O o; Z Z] [Public]
2567 (defvar math-normalize-a
)
2568 (defun math-normalize (math-normalize-a)
2570 ((not (consp math-normalize-a
))
2571 (if (integerp math-normalize-a
)
2572 (if (or (>= math-normalize-a math-small-integer-size
)
2573 (<= math-normalize-a
(- math-small-integer-size
)))
2574 (math-bignum math-normalize-a
)
2577 ((eq (car math-normalize-a
) 'bigpos
)
2578 (if (eq (nth (1- (length math-normalize-a
)) math-normalize-a
) 0)
2579 (let* ((last (setq math-normalize-a
2580 (copy-sequence math-normalize-a
))) (digs math-normalize-a
))
2581 (while (setq digs
(cdr digs
))
2582 (or (eq (car digs
) 0) (setq last digs
)))
2584 (if (cdr (cdr (cdr math-normalize-a
)))
2587 ((cdr (cdr math-normalize-a
)) (+ (nth 1 math-normalize-a
)
2588 (* (nth 2 math-normalize-a
)
2589 math-bignum-digit-size
)))
2590 ((cdr math-normalize-a
) (nth 1 math-normalize-a
))
2592 ((eq (car math-normalize-a
) 'bigneg
)
2593 (if (eq (nth (1- (length math-normalize-a
)) math-normalize-a
) 0)
2594 (let* ((last (setq math-normalize-a
(copy-sequence math-normalize-a
)))
2595 (digs math-normalize-a
))
2596 (while (setq digs
(cdr digs
))
2597 (or (eq (car digs
) 0) (setq last digs
)))
2599 (if (cdr (cdr (cdr math-normalize-a
)))
2602 ((cdr (cdr math-normalize-a
)) (- (+ (nth 1 math-normalize-a
)
2603 (* (nth 2 math-normalize-a
)
2604 math-bignum-digit-size
))))
2605 ((cdr math-normalize-a
) (- (nth 1 math-normalize-a
)))
2607 ((eq (car math-normalize-a
) 'float
)
2608 (math-make-float (math-normalize (nth 1 math-normalize-a
))
2609 (nth 2 math-normalize-a
)))
2610 ((or (memq (car math-normalize-a
)
2611 '(frac cplx polar hms date mod sdev intv vec var quote
2612 special-const calcFunc-if calcFunc-lambda
2613 calcFunc-quote calcFunc-condition
2615 (integerp (car math-normalize-a
))
2616 (and (consp (car math-normalize-a
))
2617 (not (eq (car (car math-normalize-a
)) 'lambda
))))
2619 (math-normalize-fancy math-normalize-a
))
2621 (or (and calc-simplify-mode
2623 (math-normalize-nonstandard))
2624 (let ((args (mapcar 'math-normalize
(cdr math-normalize-a
))))
2625 (or (condition-case err
2627 (assq (car math-normalize-a
) '( ( + . math-add
)
2634 ( | . math-concat
) ))))
2635 (or (and var-EvalRules
2637 (or (eq var-EvalRules math-eval-rules-cache-tag
)
2640 (math-recompile-eval-rules)))
2641 (and (or math-eval-rules-cache-other
2642 (assq (car math-normalize-a
)
2643 math-eval-rules-cache
))
2644 (math-apply-rewrites
2645 (cons (car math-normalize-a
) args
)
2646 (cdr math-eval-rules-cache
)
2647 nil math-eval-rules-cache
))))
2649 (apply (cdr func
) args
)
2650 (and (or (consp (car math-normalize-a
))
2651 (fboundp (car math-normalize-a
))
2652 (and (not (featurep 'calc-ext
))
2654 (fboundp (car math-normalize-a
))))
2655 (apply (car math-normalize-a
) args
)))))
2656 (wrong-number-of-arguments
2657 (calc-record-why "*Wrong number of arguments"
2658 (cons (car math-normalize-a
) args
))
2660 (wrong-type-argument
2662 (calc-record-why "Wrong type of argument"
2663 (cons (car math-normalize-a
) args
)))
2666 (calc-record-why "*Argument out of range"
2667 (cons (car math-normalize-a
) args
))
2670 (calc-record-why "No exact representation for result"
2671 (cons (car math-normalize-a
) args
))
2674 (calc-record-why "*Floating-point overflow occurred"
2675 (cons (car math-normalize-a
) args
))
2678 (calc-record-why "*Floating-point underflow occurred"
2679 (cons (car math-normalize-a
) args
))
2682 (if (eq (nth 1 err
) 'var-EvalRules
)
2684 (setq var-EvalRules nil
)
2685 (math-normalize (cons (car math-normalize-a
) args
)))
2686 (calc-record-why "*Variable is void" (nth 1 err
)))))
2687 (if (consp (car math-normalize-a
))
2688 (math-dimension-error)
2689 (cons (car math-normalize-a
) args
))))))))
2693 ;; True if A is a floating-point real or complex number. [P x] [Public]
2694 (defun math-floatp (a)
2695 (cond ((eq (car-safe a
) 'float
) t
)
2696 ((memq (car-safe a
) '(cplx polar mod sdev intv
))
2697 (or (math-floatp (nth 1 a
))
2698 (math-floatp (nth 2 a
))
2699 (and (eq (car a
) 'intv
) (math-floatp (nth 3 a
)))))
2700 ((eq (car-safe a
) 'date
)
2701 (math-floatp (nth 1 a
)))))
2705 ;; Verify that A is a complete object and return A. [x x] [Public]
2706 (defun math-check-complete (a)
2707 (cond ((integerp a
) a
)
2708 ((eq (car-safe a
) 'incomplete
)
2709 (calc-incomplete-error a
))
2711 (t (error "Invalid data object encountered"))))
2715 ;; Coerce integer A to be a bignum. [B S]
2716 (defun math-bignum (a)
2718 (cons 'bigpos
(math-bignum-big a
))
2719 (cons 'bigneg
(math-bignum-big (- a
)))))
2721 (defun math-bignum-big (a) ; [L s]
2724 (cons (% a math-bignum-digit-size
)
2725 (math-bignum-big (/ a math-bignum-digit-size
)))))
2728 ;; Build a normalized floating-point number. [F I S]
2729 (defun math-make-float (mant exp
)
2732 (let* ((ldiff (- calc-internal-prec
(math-numdigs mant
))))
2734 (setq mant
(math-scale-rounding mant ldiff
)
2735 exp
(- exp ldiff
))))
2737 (let ((digs (cdr mant
)))
2738 (if (= (%
(car digs
) 10) 0)
2740 (while (= (car digs
) 0)
2741 (setq digs
(cdr digs
)
2742 exp
(+ exp math-bignum-digit-length
)))
2743 (while (= (%
(car digs
) 10) 0)
2744 (setq digs
(math-div10-bignum digs
)
2746 (setq mant
(math-normalize (cons (car mant
) digs
))))))
2747 (while (= (% mant
10) 0)
2748 (setq mant
(/ mant
10)
2750 (if (and (<= exp -
4000000)
2751 (<= (+ exp
(math-numdigs mant
) -
1) -
4000000))
2752 (signal 'math-underflow nil
)
2753 (if (and (>= exp
3000000)
2754 (>= (+ exp
(math-numdigs mant
) -
1) 4000000))
2755 (signal 'math-overflow nil
)
2756 (list 'float mant exp
)))))
2758 (defun math-div10-bignum (a) ; [l l]
2760 (cons (+ (/ (car a
) 10) (* (%
(nth 1 a
) 10)
2761 (expt 10 (1- math-bignum-digit-length
))))
2762 (math-div10-bignum (cdr a
)))
2763 (list (/ (car a
) 10))))
2765 ;;; Coerce A to be a float. [F N; V V] [Public]
2766 (defun math-float (a)
2767 (cond ((Math-integerp a
) (math-make-float a
0))
2768 ((eq (car a
) 'frac
) (math-div (math-float (nth 1 a
)) (nth 2 a
)))
2769 ((eq (car a
) 'float
) a
)
2770 ((memq (car a
) '(cplx polar vec hms date sdev mod
))
2771 (cons (car a
) (mapcar 'math-float
(cdr a
))))
2772 (t (math-float-fancy a
))))
2776 (cond ((not (consp a
)) (- a
))
2777 ((eq (car a
) 'bigpos
) (cons 'bigneg
(cdr a
)))
2778 ((eq (car a
) 'bigneg
) (cons 'bigpos
(cdr a
)))
2779 ((memq (car a
) '(frac float
))
2780 (list (car a
) (Math-integer-neg (nth 1 a
)) (nth 2 a
)))
2781 ((memq (car a
) '(cplx vec hms date calcFunc-idn
))
2782 (cons (car a
) (mapcar 'math-neg
(cdr a
))))
2783 (t (math-neg-fancy a
))))
2786 ;;; Compute the number of decimal digits in integer A. [S I]
2787 (defun math-numdigs (a)
2790 (let* ((len (1- (length a
)))
2792 (+ (* (1- len
) math-bignum-digit-length
) (math-numdigs top
)))
2794 (cond ((>= a
100) (+ (math-numdigs (/ a
1000)) 3))
2800 (t (math-numdigs (- a
))))))
2802 ;;; Multiply (with truncation toward 0) the integer A by 10^N. [I i S]
2803 (defun math-scale-int (a n
)
2805 ((> n
0) (math-scale-left a n
))
2806 (t (math-normalize (math-scale-right a
(- n
))))))
2808 (defun math-scale-left (a n
) ; [I I S]
2812 (cons (car a
) (math-scale-left-bignum (cdr a
) n
))
2813 (if (>= n math-bignum-digit-length
)
2814 (if (or (>= a math-bignum-digit-size
)
2815 (<= a
(- math-bignum-digit-size
)))
2816 (math-scale-left (math-bignum a
) n
)
2817 (math-scale-left (* a math-bignum-digit-size
)
2818 (- n math-bignum-digit-length
)))
2819 (let ((sz (expt 10 (- (* 2 math-bignum-digit-length
) n
))))
2820 (if (or (>= a sz
) (<= a
(- sz
)))
2821 (math-scale-left (math-bignum a
) n
)
2822 (* a
(expt 10 n
))))))))
2824 (defun math-scale-left-bignum (a n
)
2825 (if (>= n math-bignum-digit-length
)
2826 (while (>= (setq a
(cons 0 a
)
2827 n
(- n math-bignum-digit-length
))
2828 math-bignum-digit-length
)))
2830 (math-mul-bignum-digit a
(expt 10 n
) 0)
2833 (defun math-scale-right (a n
) ; [i i S]
2837 (cons (car a
) (math-scale-right-bignum (cdr a
) n
))
2841 (- (math-scale-right (- a
) n
)))
2842 (if (>= n math-bignum-digit-length
)
2843 (while (and (> (setq a
(/ a math-bignum-digit-size
)) 0)
2844 (>= (setq n
(- n math-bignum-digit-length
))
2845 math-bignum-digit-length
))))
2850 (defun math-scale-right-bignum (a n
) ; [L L S; l l S]
2851 (if (>= n math-bignum-digit-length
)
2852 (setq a
(nthcdr (/ n math-bignum-digit-length
) a
)
2853 n
(% n math-bignum-digit-length
)))
2855 (cdr (math-mul-bignum-digit a
(expt 10 (- math-bignum-digit-length n
)) 0))
2858 ;;; Multiply (with rounding) the integer A by 10^N. [I i S]
2859 (defun math-scale-rounding (a n
)
2861 (math-scale-left a n
))
2865 (let ((val (if (< n
(- math-bignum-digit-length
))
2866 (math-scale-right-bignum
2868 (- (- math-bignum-digit-length
) n
))
2870 (math-mul-bignum-digit
2872 (expt 10 (+ math-bignum-digit-length n
)) 0)
2873 (cdr a
))))) ; n = -math-bignum-digit-length
2874 (if (and val
(>= (car val
) (/ math-bignum-digit-size
2)))
2876 (if (eq (car (cdr val
)) (1- math-bignum-digit-size
))
2877 (math-add-bignum (cdr val
) '(1))
2878 (cons (1+ (car (cdr val
))) (cdr (cdr val
))))
2883 (- (math-scale-rounding (- a
) n
))
2886 (/ (+ (math-scale-right a
(- -
1 n
)) 5) 10))))))
2889 ;;; Compute the sum of A and B. [O O O] [Public]
2890 (defun math-add (a b
)
2892 (and (not (or (consp a
) (consp b
)))
2895 (if (or (<= a
(- math-small-integer-size
)) (>= a math-small-integer-size
))
2898 (and (Math-zerop a
) (not (eq (car-safe a
) 'mod
))
2899 (if (and (math-floatp a
) (Math-ratp b
)) (math-float b
) b
))
2900 (and (Math-zerop b
) (not (eq (car-safe b
) 'mod
))
2901 (if (and (math-floatp b
) (Math-ratp a
)) (math-float a
) a
))
2902 (and (Math-objvecp a
) (Math-objvecp b
)
2904 (and (Math-integerp a
) (Math-integerp b
)
2906 (or (consp a
) (setq a
(math-bignum a
)))
2907 (or (consp b
) (setq b
(math-bignum b
)))
2908 (if (eq (car a
) 'bigneg
)
2909 (if (eq (car b
) 'bigneg
)
2910 (cons 'bigneg
(math-add-bignum (cdr a
) (cdr b
)))
2912 (let ((diff (math-sub-bignum (cdr b
) (cdr a
))))
2914 (cons 'bigneg
(math-sub-bignum (cdr a
) (cdr b
)))
2915 (cons 'bigpos diff
)))))
2916 (if (eq (car b
) 'bigneg
)
2918 (let ((diff (math-sub-bignum (cdr a
) (cdr b
))))
2920 (cons 'bigneg
(math-sub-bignum (cdr b
) (cdr a
)))
2921 (cons 'bigpos diff
))))
2922 (cons 'bigpos
(math-add-bignum (cdr a
) (cdr b
)))))))
2923 (and (Math-ratp a
) (Math-ratp b
)
2925 (calc-add-fractions a b
))
2926 (and (Math-realp a
) (Math-realp b
)
2928 (or (and (consp a
) (eq (car a
) 'float
))
2929 (setq a
(math-float a
)))
2930 (or (and (consp b
) (eq (car b
) 'float
))
2931 (setq b
(math-float b
)))
2932 (math-add-float a b
)))
2933 (and (require 'calc-ext
)
2934 (math-add-objects-fancy a b
))))
2935 (and (require 'calc-ext
)
2936 (math-add-symb-fancy a b
))))
2938 (defun math-add-bignum (a b
) ; [L L L; l l l]
2941 (let* ((a (copy-sequence a
)) (aa a
) (carry nil
) sum
)
2944 (if (< (setq sum
(+ (car aa
) (car b
)))
2945 (1- math-bignum-digit-size
))
2947 (setcar aa
(1+ sum
))
2949 (setcar aa
(- sum
(1- math-bignum-digit-size
))))
2950 (if (< (setq sum
(+ (car aa
) (car b
))) math-bignum-digit-size
)
2952 (setcar aa
(- sum math-bignum-digit-size
))
2958 (nconc a
(math-add-bignum b
'(1)))
2959 (while (eq (car aa
) (1- math-bignum-digit-size
))
2964 (setcar aa
(1+ (car aa
)))
2973 (defun math-sub-bignum (a b
) ; [l l l]
2976 (let* ((a (copy-sequence a
)) (aa a
) (borrow nil
) sum diff
)
2979 (if (>= (setq diff
(- (car aa
) (car b
))) 1)
2981 (setcar aa
(1- diff
))
2983 (setcar aa
(+ diff
(1- math-bignum-digit-size
))))
2984 (if (>= (setq diff
(- (car aa
) (car b
))) 0)
2986 (setcar aa
(+ diff math-bignum-digit-size
))
2992 (while (eq (car aa
) 0)
2993 (setcar aa
(1- math-bignum-digit-size
))
2997 (setcar aa
(1- (car aa
)))
3000 (while (eq (car b
) 0)
3005 (while (eq (car b
) 0)
3011 (defun math-add-float (a b
) ; [F F F]
3012 (let ((ediff (- (nth 2 a
) (nth 2 b
))))
3014 (if (>= ediff
(+ calc-internal-prec calc-internal-prec
))
3016 (math-make-float (math-add (nth 1 b
)
3019 (math-scale-left (nth 1 a
) ediff
)))
3021 (if (>= (setq ediff
(- ediff
))
3022 (+ calc-internal-prec calc-internal-prec
))
3024 (math-make-float (math-add (nth 1 a
)
3025 (math-scale-left (nth 1 b
) ediff
))
3028 ;;; Compute the difference of A and B. [O O O] [Public]
3029 (defun math-sub (a b
)
3030 (if (or (consp a
) (consp b
))
3031 (math-add a
(math-neg b
))
3033 (if (or (<= a
(- math-small-integer-size
)) (>= a math-small-integer-size
))
3037 (defun math-sub-float (a b
) ; [F F F]
3038 (let ((ediff (- (nth 2 a
) (nth 2 b
))))
3040 (if (>= ediff
(+ calc-internal-prec calc-internal-prec
))
3042 (math-make-float (math-add (Math-integer-neg (nth 1 b
))
3045 (math-scale-left (nth 1 a
) ediff
)))
3047 (if (>= (setq ediff
(- ediff
))
3048 (+ calc-internal-prec calc-internal-prec
))
3050 (math-make-float (math-add (nth 1 a
)
3052 (math-scale-left (nth 1 b
) ediff
)))
3056 ;;; Compute the product of A and B. [O O O] [Public]
3057 (defun math-mul (a b
)
3059 (and (not (consp a
)) (not (consp b
))
3060 (< a math-bignum-digit-size
) (> a
(- math-bignum-digit-size
))
3061 (< b math-bignum-digit-size
) (> b
(- math-bignum-digit-size
))
3063 (and (Math-zerop a
) (not (eq (car-safe b
) 'mod
))
3064 (if (Math-scalarp b
)
3065 (if (and (math-floatp b
) (Math-ratp a
)) (math-float a
) a
)
3067 (math-mul-zero a b
)))
3068 (and (Math-zerop b
) (not (eq (car-safe a
) 'mod
))
3069 (if (Math-scalarp a
)
3070 (if (and (math-floatp a
) (Math-ratp b
)) (math-float b
) b
)
3072 (math-mul-zero b a
)))
3073 (and (Math-objvecp a
) (Math-objvecp b
)
3075 (and (Math-integerp a
) (Math-integerp b
)
3077 (or (consp a
) (setq a
(math-bignum a
)))
3078 (or (consp b
) (setq b
(math-bignum b
)))
3080 (cons (if (eq (car a
) (car b
)) 'bigpos
'bigneg
)
3083 (math-mul-bignum (cdr a
) (cdr b
))
3084 (math-mul-bignum-digit (cdr a
) (nth 1 b
) 0))
3085 (math-mul-bignum-digit (cdr b
) (nth 1 a
) 0))))))
3086 (and (Math-ratp a
) (Math-ratp b
)
3088 (calc-mul-fractions a b
))
3089 (and (Math-realp a
) (Math-realp b
)
3091 (or (and (consp a
) (eq (car a
) 'float
))
3092 (setq a
(math-float a
)))
3093 (or (and (consp b
) (eq (car b
) 'float
))
3094 (setq b
(math-float b
)))
3095 (math-make-float (math-mul (nth 1 a
) (nth 1 b
))
3096 (+ (nth 2 a
) (nth 2 b
)))))
3097 (and (require 'calc-ext
)
3098 (math-mul-objects-fancy a b
))))
3099 (and (require 'calc-ext
)
3100 (math-mul-symb-fancy a b
))))
3102 (defun math-infinitep (a &optional undir
)
3103 (while (and (consp a
) (memq (car a
) '(* / neg
)))
3104 (if (or (not (eq (car a
) '*)) (math-infinitep (nth 1 a
)))
3106 (setq a
(nth 2 a
))))
3109 (memq (nth 2 a
) '(var-inf var-uinf var-nan
))
3110 (if (and undir
(eq (nth 2 a
) 'var-inf
))
3111 '(var uinf var-uinf
)
3114 ;;; Multiply digit lists A and B. [L L L; l l l]
3115 (defun math-mul-bignum (a b
)
3117 (let* ((sum (if (<= (car b
) 1)
3121 (math-mul-bignum-digit a
(car b
) 0)))
3122 (sump sum
) c d aa ss prod
)
3123 (while (setq b
(cdr b
))
3124 (setq ss
(setq sump
(or (cdr sump
) (setcdr sump
(list 0))))
3129 (setcar ss
(%
(setq prod
(+ (+ (car ss
) (* (car aa
) d
))
3130 c
)) math-bignum-digit-size
))
3132 (setq c
(/ prod math-bignum-digit-size
)
3133 ss
(or (cdr ss
) (setcdr ss
(list 0)))))
3134 (if (>= prod math-bignum-digit-size
)
3136 (setcar (cdr ss
) (+ (/ prod math-bignum-digit-size
) (car (cdr ss
))))
3137 (setcdr ss
(list (/ prod math-bignum-digit-size
))))))
3140 ;;; Multiply digit list A by digit D. [L L D D; l l D D]
3141 (defun math-mul-bignum-digit (a d c
)
3145 (let* ((a (copy-sequence a
)) (aa a
) prod
)
3148 (%
(setq prod
(+ (* (car aa
) d
) c
))
3149 math-bignum-digit-size
))
3152 c
(/ prod math-bignum-digit-size
)))
3153 (if (>= prod math-bignum-digit-size
)
3154 (setcdr aa
(list (/ prod math-bignum-digit-size
))))
3160 ;;; Compute the integer (quotient . remainder) of A and B, which may be
3161 ;;; small or big integers. Type and consistency of truncation is undefined
3162 ;;; if A or B is negative. B must be nonzero. [I.I I I] [Public]
3163 (defun math-idivmod (a b
)
3165 (math-reject-arg a
"*Division by zero"))
3166 (if (or (consp a
) (consp b
))
3167 (if (and (natnump b
) (< b math-bignum-digit-size
))
3168 (let ((res (math-div-bignum-digit (cdr a
) b
)))
3170 (math-normalize (cons (car a
) (car res
)))
3172 (or (consp a
) (setq a
(math-bignum a
)))
3173 (or (consp b
) (setq b
(math-bignum b
)))
3174 (let ((res (math-div-bignum (cdr a
) (cdr b
))))
3176 (math-normalize (cons (if (eq (car a
) (car b
)) 'bigpos
'bigneg
)
3178 (math-normalize (cons (car a
) (cdr res
))))))
3179 (cons (/ a b
) (% a b
))))
3181 (defun math-quotient (a b
) ; [I I I] [Public]
3182 (if (and (not (consp a
)) (not (consp b
)))
3184 (math-reject-arg a
"*Division by zero")
3186 (if (and (natnump b
) (< b math-bignum-digit-size
))
3188 (math-reject-arg a
"*Division by zero")
3189 (math-normalize (cons (car a
)
3190 (car (math-div-bignum-digit (cdr a
) b
)))))
3191 (or (consp a
) (setq a
(math-bignum a
)))
3192 (or (consp b
) (setq b
(math-bignum b
)))
3193 (let* ((alen (1- (length a
)))
3194 (blen (1- (length b
)))
3195 (d (/ math-bignum-digit-size
(1+ (nth (1- blen
) (cdr b
)))))
3196 (res (math-div-bignum-big (math-mul-bignum-digit (cdr a
) d
0)
3197 (math-mul-bignum-digit (cdr b
) d
0)
3199 (math-normalize (cons (if (eq (car a
) (car b
)) 'bigpos
'bigneg
)
3203 ;;; Divide a bignum digit list by another. [l.l l L]
3204 ;;; The following division algorithm is borrowed from Knuth vol. II, sec. 4.3.1
3205 (defun math-div-bignum (a b
)
3207 (let* ((alen (length a
))
3209 (d (/ math-bignum-digit-size
(1+ (nth (1- blen
) b
))))
3210 (res (math-div-bignum-big (math-mul-bignum-digit a d
0)
3211 (math-mul-bignum-digit b d
0)
3216 (car (math-div-bignum-digit (cdr res
) d
)))))
3217 (let ((res (math-div-bignum-digit a
(car b
))))
3218 (cons (car res
) (list (cdr res
))))))
3220 ;;; Divide a bignum digit list by a digit. [l.D l D]
3221 (defun math-div-bignum-digit (a b
)
3223 (let* ((res (math-div-bignum-digit (cdr a
) b
))
3224 (num (+ (* (cdr res
) math-bignum-digit-size
) (car a
))))
3226 (cons (/ num b
) (car res
))
3230 (defun math-div-bignum-big (a b alen blen
) ; [l.l l L]
3233 (let* ((res (math-div-bignum-big (cdr a
) b
(1- alen
) blen
))
3234 (num (cons (car a
) (cdr res
)))
3235 (res2 (math-div-bignum-part num b blen
)))
3237 (cons (car res2
) (car res
))
3240 (defun math-div-bignum-part (a b blen
) ; a < b*math-bignum-digit-size [D.l l L]
3241 (let* ((num (+ (* (or (nth blen a
) 0) math-bignum-digit-size
)
3242 (or (nth (1- blen
) a
) 0)))
3243 (den (nth (1- blen
) b
))
3244 (guess (min (/ num den
) (1- math-bignum-digit-size
))))
3245 (math-div-bignum-try a b
(math-mul-bignum-digit b guess
0) guess
)))
3247 (defun math-div-bignum-try (a b c guess
) ; [D.l l l D]
3248 (let ((rem (math-sub-bignum a c
)))
3250 (math-div-bignum-try a b
(math-sub-bignum c b
) (1- guess
))
3254 ;;; Compute the quotient of A and B. [O O N] [Public]
3255 (defun math-div (a b
)
3259 (math-div-by-zero a b
))
3260 (and (Math-zerop a
) (not (eq (car-safe b
) 'mod
))
3261 (if (Math-scalarp b
)
3262 (if (and (math-floatp b
) (Math-ratp a
)) (math-float a
) a
)
3264 (math-div-zero a b
)))
3265 (and (Math-objvecp a
) (Math-objvecp b
)
3267 (and (Math-integerp a
) (Math-integerp b
)
3268 (let ((q (math-idivmod a b
)))
3271 (if calc-prefer-frac
3274 (math-make-frac a b
))
3275 (math-div-float (math-make-float a
0)
3276 (math-make-float b
0))))))
3277 (and (Math-ratp a
) (Math-ratp b
)
3279 (calc-div-fractions a b
))
3280 (and (Math-realp a
) (Math-realp b
)
3282 (or (and (consp a
) (eq (car a
) 'float
))
3283 (setq a
(math-float a
)))
3284 (or (and (consp b
) (eq (car b
) 'float
))
3285 (setq b
(math-float b
)))
3286 (math-div-float a b
)))
3287 (and (require 'calc-ext
)
3288 (math-div-objects-fancy a b
))))
3289 (and (require 'calc-ext
)
3290 (math-div-symb-fancy a b
))))
3292 (defun math-div-float (a b
) ; [F F F]
3293 (let ((ldiff (max (- (1+ calc-internal-prec
)
3294 (- (math-numdigs (nth 1 a
)) (math-numdigs (nth 1 b
))))
3296 (math-make-float (math-quotient (math-scale-int (nth 1 a
) ldiff
) (nth 1 b
))
3297 (- (- (nth 2 a
) (nth 2 b
)) ldiff
))))
3302 (defvar calc-selection-cache-entry
)
3303 ;;; Format the number A as a string. [X N; X Z] [Public]
3304 (defun math-format-stack-value (entry)
3305 (setq calc-selection-cache-entry calc-selection-cache-default-entry
)
3306 (let* ((a (car entry
))
3307 (math-comp-selected (nth 2 entry
))
3308 (c (cond ((null a
) "<nil>")
3309 ((eq calc-display-raw t
) (format "%s" a
))
3311 ((eq a
'top-of-stack
) (propertize "." 'font-lock-face
'bold
))
3312 (calc-prepared-composition
3313 calc-prepared-composition
)
3314 ((and (Math-scalarp a
)
3315 (memq calc-language
'(nil flat unform
))
3316 (null math-comp-selected
))
3317 (math-format-number a
))
3318 (t (require 'calc-ext
)
3319 (math-compose-expr a
0))))
3320 (off (math-stack-value-offset c
))
3322 (and math-comp-selected
(setq calc-any-selections t
))
3326 (setq c
(math-comp-concat (make-string off ?\s
) c
)))
3327 (or (equal calc-left-label
"")
3328 (setq c
(math-comp-concat (if (eq a
'top-of-stack
)
3329 (make-string (length calc-left-label
) ?\s
)
3332 (when calc-line-numbering
3333 (setq c
(math-comp-concat (if (eq calc-language
'big
)
3334 (if math-comp-selected
3339 (unless (or (equal calc-right-label
"")
3340 (eq a
'top-of-stack
))
3342 (setq c
(list 'horiz c
3343 (make-string (max (- w
(math-comp-width c
)
3344 (length calc-right-label
)) 0) ?\s
)
3347 (setq s
(if (stringp c
)
3348 (if calc-display-raw
3351 (math-composition-to-string c w
)))
3352 (when calc-language-output-filter
3353 (setq s
(funcall calc-language-output-filter s
)))
3354 (if (eq calc-language
'big
)
3355 (setq s
(concat s
"\n"))
3356 (when calc-line-numbering
3357 (setq s
(concat "1:" (substring s
2)))))
3358 (setcar (cdr entry
) (calc-count-lines s
))
3361 ;; The variables math-svo-c, math-svo-wid and math-svo-off are local
3362 ;; to math-stack-value-offset, but are used by math-stack-value-offset-fancy
3365 (defun math-stack-value-offset (math-svo-c)
3366 (let* ((num (if calc-line-numbering
4 0))
3367 (math-svo-wid (calc-window-width))
3369 (if calc-display-just
3372 (math-stack-value-offset-fancy))
3373 (setq math-svo-off
(or calc-display-origin
0))
3374 (when (integerp calc-line-breaking
)
3375 (setq math-svo-wid calc-line-breaking
)))
3376 (cons (max (- math-svo-off
(length calc-left-label
)) 0)
3377 (+ math-svo-wid num
))))
3379 (defun calc-count-lines (s)
3382 (while (setq pos
(string-match "\n" s pos
))
3387 (defun math-format-value (a &optional w
)
3388 (if (and (Math-scalarp a
)
3389 (memq calc-language
'(nil flat unform
)))
3390 (math-format-number a
)
3392 (let ((calc-line-breaking nil
))
3393 (math-composition-to-string (math-compose-expr a
0) w
))))
3395 (defun calc-window-width ()
3396 (if calc-embedded-info
3397 (let ((win (get-buffer-window (aref calc-embedded-info
0))))
3398 (1- (if win
(window-width win
) (frame-width))))
3399 (- (window-width (get-buffer-window (current-buffer)))
3400 (if calc-line-numbering
5 1))))
3402 (defun math-comp-concat (c1 c2
)
3403 (if (and (stringp c1
) (stringp c2
))
3405 (list 'horiz c1 c2
)))
3409 ;;; Format an expression as a one-line string suitable for re-reading.
3411 (defun math-format-flat-expr (a prec
)
3413 ((or (not (or (consp a
) (integerp a
)))
3414 (eq calc-display-raw t
))
3415 (let ((print-escape-newlines t
))
3416 (concat "'" (prin1-to-string a
))))
3418 (let ((calc-group-digits nil
)
3419 (calc-point-char ".")
3420 (calc-frac-format (if (> (length (car calc-frac-format
)) 1)
3421 '("::" nil
) '(":" nil
)))
3422 (calc-complex-format nil
)
3423 (calc-hms-format "%s@ %s' %s\"")
3424 (calc-language nil
))
3425 (math-format-number a
)))
3428 (math-format-flat-expr-fancy a prec
))))
3432 ;;; Format a number as a string.
3433 (defvar math-half-2-word-size
)
3434 (defun math-format-number (a &optional prec
) ; [X N] [Public]
3436 ((eq calc-display-raw t
) (format "%s" a
))
3437 ((and calc-twos-complement-mode
3438 math-radix-explicit-format
3441 (and (Math-integer-posp a
)
3442 (Math-lessp a math-half-2-word-size
))
3443 (and (Math-integer-negp a
)
3446 (math-compare (Math-integer-neg a
) math-half-2-word-size
)))
3447 (or (= comparison
0)
3448 (= comparison -
1))))))
3450 (math-format-twos-complement a
))
3451 ((and (nth 1 calc-frac-format
) (Math-integerp a
))
3453 (math-format-number (math-adjust-fraction a
)))
3455 (if (not (or calc-group-digits calc-leading-zeros
))
3456 (if (= calc-number-radix
10)
3459 (concat "-" (math-format-number (- a
)))
3461 (if math-radix-explicit-format
3462 (if calc-radix-formatter
3463 (funcall calc-radix-formatter
3465 (if (= calc-number-radix
2)
3466 (math-format-binary a
)
3467 (math-format-radix a
)))
3468 (format "%d#%s" calc-number-radix
3469 (if (= calc-number-radix
2)
3470 (math-format-binary a
)
3471 (math-format-radix a
))))
3472 (math-format-radix a
))))
3473 (math-format-number (math-bignum a
))))
3475 ((not (consp a
)) (prin1-to-string a
))
3476 ((eq (car a
) 'bigpos
) (math-format-bignum (cdr a
)))
3477 ((eq (car a
) 'bigneg
) (concat "-" (math-format-bignum (cdr a
))))
3478 ((and (eq (car a
) 'float
) (= calc-number-radix
10))
3479 (if (Math-integer-negp (nth 1 a
))
3480 (concat "-" (math-format-number (math-neg a
)))
3481 (let ((mant (nth 1 a
))
3483 (fmt (car calc-float-format
))
3484 (figs (nth 1 calc-float-format
))
3485 (point calc-point-char
)
3487 (if (and (eq fmt
'fix
)
3488 (or (and (< figs
0) (setq figs
(- figs
)))
3489 (> (+ exp
(math-numdigs mant
)) (- figs
))))
3491 (setq mant
(math-scale-rounding mant
(+ exp figs
))
3492 str
(if (integerp mant
)
3493 (int-to-string mant
)
3494 (math-format-bignum-decimal (cdr mant
))))
3495 (if (<= (length str
) figs
)
3496 (setq str
(concat (make-string (1+ (- figs
(length str
))) ?
0)
3499 (setq str
(concat (substring str
0 (- figs
)) point
3500 (substring str
(- figs
))))
3501 (setq str
(concat str point
)))
3502 (when calc-group-digits
3504 (setq str
(math-group-float str
))))
3506 (setq figs
(+ calc-internal-prec figs
)))
3508 (let ((adj (- figs
(math-numdigs mant
))))
3510 (setq mant
(math-scale-rounding mant adj
)
3512 (setq str
(if (integerp mant
)
3513 (int-to-string mant
)
3514 (math-format-bignum-decimal (cdr mant
))))
3515 (let* ((len (length str
))
3517 (if (and (eq fmt
'float
)
3518 (<= dpos
(+ calc-internal-prec calc-display-sci-high
))
3519 (>= dpos
(+ calc-display-sci-low
2)))
3523 (setq str
(concat "0" point str
)))
3524 ((and (<= exp
0) (> dpos
0))
3525 (setq str
(concat (substring str
0 dpos
) point
3526 (substring str dpos
))))
3528 (setq str
(concat str
(make-string exp ?
0) point
)))
3530 (setq str
(concat "0" point
3531 (make-string (- dpos
) ?
0) str
))))
3532 (when calc-group-digits
3534 (setq str
(math-group-float str
))))
3535 (let* ((eadj (+ exp len
))
3536 (scale (if (eq fmt
'eng
)
3537 (1+ (math-mod (+ eadj
300002) 3))
3539 (if (> scale
(length str
))
3540 (setq str
(concat str
(make-string (- scale
(length str
))
3542 (if (< scale
(length str
))
3543 (setq str
(concat (substring str
0 scale
) point
3544 (substring str scale
))))
3545 (when calc-group-digits
3547 (setq str
(math-group-float str
)))
3548 (setq str
(format (if (memq calc-language
'(math maple
))
3549 (if (and prec
(> prec
191))
3550 "(%s*10.^%d)" "%s*10.^%d")
3552 str
(- eadj scale
)))))))
3556 (math-format-number-fancy a prec
))))
3558 (defun math-format-bignum (a) ; [X L]
3559 (if (and (= calc-number-radix
10)
3560 (not calc-leading-zeros
)
3561 (not calc-group-digits
))
3562 (math-format-bignum-decimal a
)
3564 (math-format-bignum-fancy a
)))
3566 (defun math-format-bignum-decimal (a) ; [X L]
3569 (while (cdr (cdr a
))
3573 (number-to-string (* 2 math-bignum-digit-length
))
3575 (+ (* (nth 1 a
) math-bignum-digit-size
) (car a
))) s
)
3577 (concat (int-to-string
3578 (+ (* (or (nth 1 a
) 0) math-bignum-digit-size
) (car a
))) s
))
3583 ;;; Parse a simple number in string form. [N X] [Public]
3584 (defun math-read-number (s &optional decimal
)
3585 "Convert the string S into a Calc number."
3590 ;; Integers (most common case)
3591 ((string-match "\\` *\\([0-9]+\\) *\\'" s
)
3592 (let ((digs (math-match-substring s
1)))
3593 (if (and (memq calc-language calc-lang-c-type-hex
)
3595 (eq (aref digs
0) ?
0)
3597 (math-read-number (concat "8#" digs
))
3598 (if (<= (length digs
) (* 2 math-bignum-digit-length
))
3599 (string-to-number digs
)
3600 (cons 'bigpos
(math-read-bignum digs
))))))
3602 ;; Clean up the string if necessary
3603 ((string-match "\\`\\(.*\\)[ \t\n]+\\([^\001]*\\)\\'" s
)
3604 (math-read-number (concat (math-match-substring s
1)
3605 (math-match-substring s
2))))
3607 ;; Plus and minus signs
3608 ((string-match "^[-_+]\\(.*\\)$" s
)
3609 (let ((val (math-read-number (math-match-substring s
1))))
3610 (and val
(if (eq (aref s
0) ?
+) val
(math-neg val
)))))
3612 ;; Forms that require extensions module
3613 ((string-match "[^-+0-9eE.]" s
)
3615 (math-read-number-fancy s
))
3618 ((string-match "^\\([0-9]*\\)\\.\\([0-9]*\\)$" s
)
3619 (let ((int (math-match-substring s
1))
3620 (frac (math-match-substring s
2)))
3621 (let ((ilen (length int
))
3622 (flen (length frac
)))
3623 (let ((int (if (> ilen
0) (math-read-number int t
) 0))
3624 (frac (if (> flen
0) (math-read-number frac t
) 0)))
3625 (and int frac
(or (> ilen
0) (> flen
0))
3627 (math-add (math-scale-int int flen
) frac
)
3631 ((string-match "^\\(.*\\)[eE]\\([-+]?[0-9]+\\)$" s
)
3632 (let ((mant (math-match-substring s
1))
3633 (exp (math-match-substring s
2)))
3634 (let ((mant (if (> (length mant
) 0) (math-read-number mant t
) 1))
3635 (exp (if (<= (length exp
) (if (memq (aref exp
0) '(?
+ ?-
)) 8 7))
3636 (string-to-number exp
))))
3637 (and mant exp
(Math-realp mant
) (> exp -
4000000) (< exp
4000000)
3638 (let ((mant (math-float mant
)))
3639 (list 'float
(nth 1 mant
) (+ (nth 2 mant
) exp
)))))))
3644 ;;; Parse a very simple number, keeping all digits.
3645 (defun math-read-number-simple (s)
3646 "Convert the string S into a Calc number.
3647 S is assumed to be a simple number (integer or float without an exponent)
3648 and all digits are kept, regardless of Calc's current precision."
3652 ((string-match "^[0-9]+$" s
)
3653 (if (string-match "^\\(0+\\)" s
)
3654 (setq s
(substring s
(match-end 0))))
3655 (if (<= (length s
) (* 2 math-bignum-digit-length
))
3656 (string-to-number s
)
3657 (cons 'bigpos
(math-read-bignum s
))))
3659 ((string-match "^-[0-9]+$" s
)
3660 (if (<= (length s
) (1+ (* 2 math-bignum-digit-length
)))
3661 (string-to-number s
)
3662 (cons 'bigneg
(math-read-bignum (substring s
1)))))
3664 ((string-match "^\\(-?[0-9]*\\)\\.\\([0-9]*\\)$" s
)
3665 (let ((int (math-match-substring s
1))
3666 (frac (math-match-substring s
2)))
3667 (list 'float
(math-read-number-simple (concat int frac
))
3668 (- (length frac
)))))
3672 (defun math-match-substring (s n
)
3673 (if (match-beginning n
)
3674 (substring s
(match-beginning n
) (match-end n
))
3677 (defun math-read-bignum (s) ; [l X]
3678 (if (> (length s
) math-bignum-digit-length
)
3679 (cons (string-to-number (substring s
(- math-bignum-digit-length
)))
3680 (math-read-bignum (substring s
0 (- math-bignum-digit-length
))))
3681 (list (string-to-number s
))))
3683 (defconst math-standard-opers
3684 '( ( "_" calcFunc-subscr
1200 1201 )
3685 ( "%" calcFunc-percent
1100 -
1 )
3686 ( "u!" calcFunc-lnot -
1 1000 )
3687 ( "mod" mod
400 400 185 )
3688 ( "+/-" sdev
300 300 185 )
3689 ( "!!" calcFunc-dfact
210 -
1 )
3690 ( "!" calcFunc-fact
210 -
1 )
3693 ( "u+" ident -
1 197 )
3697 ( "\\" calcFunc-idiv
190 191 )
3701 ( "<" calcFunc-lt
160 161 )
3702 ( ">" calcFunc-gt
160 161 )
3703 ( "<=" calcFunc-leq
160 161 )
3704 ( ">=" calcFunc-geq
160 161 )
3705 ( "=" calcFunc-eq
160 161 )
3706 ( "==" calcFunc-eq
160 161 )
3707 ( "!=" calcFunc-neq
160 161 )
3708 ( "&&" calcFunc-land
110 111 )
3709 ( "||" calcFunc-lor
100 101 )
3710 ( "?" (math-read-if) 91 90 )
3711 ( "!!!" calcFunc-pnot -
1 85 )
3712 ( "&&&" calcFunc-pand
80 81 )
3713 ( "|||" calcFunc-por
75 76 )
3714 ( ":=" calcFunc-assign
51 50 )
3715 ( "::" calcFunc-condition
45 46 )
3716 ( "=>" calcFunc-evalto
40 41 )
3717 ( "=>" calcFunc-evalto
40 -
1 )))
3719 (defun math-standard-ops ()
3720 (if calc-multiplication-has-precedence
3725 math-standard-opers
))
3730 math-standard-opers
))))
3732 (defvar math-expr-opers
(math-standard-ops))
3734 (defun math-standard-ops-p ()
3735 (let ((meo (caar math-expr-opers
)))
3737 (string= meo
"*"))))
3739 (defun math-expr-ops ()
3740 (if (math-standard-ops-p)
3745 (defun calc-grab-region (top bot arg
)
3746 "Parse the region as a vector of numbers and push it on the Calculator stack."
3747 (interactive "r\nP")
3749 (calc-do-grab-region top bot arg
))
3752 (defun calc-grab-rectangle (top bot arg
)
3753 "Parse a rectangle as a matrix of numbers and push it on the Calculator stack."
3754 (interactive "r\nP")
3756 (calc-do-grab-rectangle top bot arg
))
3758 (defun calc-grab-sum-down (top bot arg
)
3759 "Parse a rectangle as a matrix of numbers and sum its columns."
3760 (interactive "r\nP")
3762 (calc-do-grab-rectangle top bot arg
'calcFunc-reduced
))
3764 (defun calc-grab-sum-across (top bot arg
)
3765 "Parse a rectangle as a matrix of numbers and sum its rows."
3766 (interactive "r\nP")
3768 (calc-do-grab-rectangle top bot arg
'calcFunc-reducea
))
3772 (defun calc-embedded (arg &optional end obeg oend
)
3773 "Start Calc Embedded mode on the formula surrounding point."
3776 (calc-do-embedded arg end obeg oend
))
3779 (defun calc-embedded-activate (&optional arg cbuf
)
3780 "Scan the current editing buffer for all embedded := and => formulas.
3781 Also looks for the equivalent TeX words, \\gets and \\evalto."
3783 (calc-do-embedded-activate arg cbuf
))
3785 (defun calc-user-invocation ()
3787 (unless calc-invocation-macro
3788 (error "Use `Z I' inside Calc to define a `C-x * Z' keyboard macro"))
3789 (execute-kbd-macro calc-invocation-macro nil
))
3791 ;;; User-programmability.
3794 (defmacro defmath
(func args
&rest body
) ; [Public]
3795 "Define Calc function.
3797 Like `defun' except that code in the body of the definition can
3798 make use of the full range of Calc data types and the usual
3799 arithmetic operations are converted to their Calc equivalents.
3801 The prefix `calcFunc-' is added to the specified name to get the
3802 actual Lisp function name.
3804 See Info node `(calc)Defining Functions'."
3805 (declare (doc-string 3))
3807 (math-do-defmath func args body
))
3809 ;;; Functions needed for Lucid Emacs support.
3811 (defun calc-read-key (&optional optkey
)
3812 (cond ((featurep 'xemacs
)
3813 (let ((event (next-command-event)))
3814 (let ((key (event-to-character event t t
)))
3815 (or key optkey
(error "Expected a plain keystroke"))
3818 (let ((key (read-event)))
3821 (defun calc-unread-command (&optional input
)
3822 (if (featurep 'xemacs
)
3823 (setq unread-command-event
3824 (if (integerp input
) (character-to-event input
)
3825 (or input last-command-event
)))
3826 (push (or input last-command-event
) unread-command-events
)))
3828 (defun calc-clear-unread-commands ()
3829 (if (featurep 'xemacs
)
3830 (setq unread-command-event nil
)
3831 (setq unread-command-events nil
)))
3833 (defcalcmodevar math-2-word-size
3834 (math-read-number-simple "4294967296")
3835 "Two to the power of `calc-word-size'.")
3837 (defcalcmodevar math-half-2-word-size
3838 (math-read-number-simple "2147483648")
3839 "One-half of two to the power of `calc-word-size'.")
3841 (when calc-always-load-extensions
3843 (calc-load-everything))
3846 (run-hooks 'calc-load-hook
)
3854 ;;; calc.el ends here