1 ;;; calc.el --- the GNU Emacs calculator
3 ;; Copyright (C) 1990, 1991, 1992, 1993, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 ;; Author: David Gillespie <daveg@synaptics.com>
7 ;; Maintainer: Jay Belanger <jay.p.belanger@gmail.com>
8 ;; Keywords: convenience, extensions
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
30 ;; Calc is split into many files. This file is the main entry point.
31 ;; This file includes autoload commands for various other basic Calc
32 ;; facilities. The more advanced features are based in calc-ext, which
33 ;; in turn contains autoloads for the rest of the Calc files. This
34 ;; odd set of interactions is designed to make Calc's loading time
35 ;; be as short as possible when only simple calculations are needed.
37 ;; Original author's address:
38 ;; Dave Gillespie, daveg@synaptics.com, uunet!synaptx!daveg.
39 ;; Synaptics, Inc., 2698 Orchard Parkway, San Jose, CA 95134.
41 ;; The old address daveg@csvax.cs.caltech.edu will continue to
42 ;; work for the foreseeable future.
44 ;; Bug reports and suggestions are always welcome! (Type M-x
45 ;; report-calc-bug to send them).
47 ;; All functions, macros, and Lisp variables defined here begin with one
48 ;; of the prefixes "math", "Math", or "calc", with the exceptions of
49 ;; "full-calc", "full-calc-keypad", "another-calc", "quick-calc",
50 ;; "report-calc-bug", and "defmath". User-accessible variables begin
55 ;; Fix rewrite mechanism to do less gratuitous rearrangement of terms.
56 ;; Implement a pattern-based "refers" predicate.
58 ;; Make it possible to Undo a selection command.
59 ;; Figure out how to allow selecting rows of matrices.
60 ;; If cursor was in selection before, move it after j n, j p, j L, etc.
61 ;; Consider reimplementing calc-delete-selection using rewrites.
63 ;; Implement line-breaking in non-flat compositions (is this desirable?).
64 ;; Implement matrix formatting with multi-line components.
66 ;; Have "Z R" define a user command based on a set of rewrite rules.
67 ;; Support "incf" and "decf" in defmath definitions.
68 ;; Have defmath generate calls to calc-binary-op or calc-unary-op.
69 ;; Make some way to define algebraic functions using keyboard macros.
71 ;; Allow calc-word-size=0 => Common Lisp-style signed bitwise arithmetic.
72 ;; Consider digamma function (and thus arb. prec. Euler's gamma constant).
73 ;; May as well make continued-fractions stuff available to the user.
75 ;; How about matrix eigenvalues, SVD, pseudo-inverse, etc.?
76 ;; Should cache matrix inverses as well as decompositions.
77 ;; If dividing by a non-square matrix, use least-squares automatically.
78 ;; Consider supporting matrix exponentials.
80 ;; Have ninteg detect and work around singularities at the endpoints.
81 ;; Use an adaptive subdivision algorithm for ninteg.
82 ;; Provide nsum and nprod to go along with ninteg.
84 ;; Handle TeX-mode parsing of \matrix{ ... } where ... contains braces.
85 ;; Support AmS-TeX's \{d,t,}frac, \{d,t,}binom notations.
86 ;; Format and parse sums and products in Eqn and Math modes.
88 ;; Get math-read-big-expr to read sums, products, etc.
89 ;; Change calc-grab-region to use math-read-big-expr.
90 ;; Have a way to define functions using := in Embedded Mode.
92 ;; Support polar plotting with GNUPLOT.
93 ;; Make a calc-graph-histogram function.
95 ;; Replace hokey formulas for complex functions with formulas designed
96 ;; to minimize roundoff while maintaining the proper branch cuts.
97 ;; Test accuracy of advanced math functions over whole complex plane.
98 ;; Extend Bessel functions to provide arbitrary precision.
99 ;; Extend advanced math functions to handle error forms and intervals.
100 ;; Provide a better implementation for math-sin-cos-raw.
101 ;; Provide a better implementation for math-hypot.
102 ;; Provide a better implementation for math-make-frac.
103 ;; Provide a better implementation for calcFunc-prfac.
104 ;; Provide a better implementation for calcFunc-factor.
106 ;; Provide more examples in the tutorial section of the manual.
107 ;; Cover in the tutorial: simplification modes, declarations,
108 ;; bitwise stuff, selections, matrix mapping, financial functions.
109 ;; Provide more Lisp programming examples in the manual.
110 ;; Finish the Internals section of the manual (and bring it up to date).
112 ;; Tim suggests adding spreadsheet-like features.
113 ;; Implement language modes for Gnuplot, Lisp, Ada, APL, ...?
115 ;; For atan series, if x > tan(pi/12) (about 0.268) reduce using the identity
116 ;; atan(x) = atan((x * sqrt(3) - 1) / (sqrt(3) + x)) + pi/6.
118 ;; A better integration algorithm:
119 ;; Use breadth-first instead of depth-first search, as follows:
120 ;; The integral cache allows unfinished integrals in symbolic notation
121 ;; on the righthand side. An entry with no unfinished integrals on the
122 ;; RHS is "complete"; references to it elsewhere are replaced by the
123 ;; integrated value. More than one cache entry for the same integral
124 ;; may exist, though if one becomes complete, the others may be deleted.
125 ;; The integrator works by using every applicable rule (such as
126 ;; substitution, parts, linearity, etc.) to generate possible righthand
127 ;; sides, all of which are entered into the cache. Now, as long as the
128 ;; target integral is not complete (and the time limit has not run out)
129 ;; choose an incomplete integral from the cache and, for every integral
130 ;; appearing in its RHS's, add those integrals to the cache using the
131 ;; same substitition, parts, etc. rules. The cache should be organized
132 ;; as a priority queue, choosing the "simplest" incomplete integral at
133 ;; each step, or choosing randomly among equally simple integrals.
134 ;; Simplicity equals small size, and few steps removed from the original
135 ;; target integral. Note that when the integrator finishes, incomplete
136 ;; integrals can be left in the cache, so the algorithm can start where
137 ;; it left off if another similar integral is later requested.
138 ;; Breadth-first search would avoid the nagging problem of, e.g., whether
139 ;; to use parts or substitution first, and which decomposition is best.
140 ;; All are tried, and any path that diverges will quickly be put on the
141 ;; back burner by the priority queue.
142 ;; Note: Probably a good idea to call math-simplify-extended before
143 ;; measuring a formula's simplicity.
145 ;; From: "Robert J. Chassell" <bob@rattlesnake.com>
146 ;; Subject: Re: fix for `Cannot open load file: calc-alg-3'
147 ;; To: walters@debian.org
148 ;; Date: Sat, 24 Nov 2001 21:44:21 +0000 (UTC)
150 ;; Could you add logistic curve fitting to the current list?
152 ;; (I guess the key binding for a logistic curve would have to be `s'
153 ;; since a logistic curve is an `s' curve; both `l' and `L' are already
154 ;; taken for logarithms.)
156 ;; Here is the current list for curve fitting;
159 ;; Linear or multilinear. a + b x + c y + d z.
162 ;; Polynomials. a + b x + c x^2 + d x^3.
165 ;; Exponential. a exp(b x) exp(c y).
168 ;; Base-10 exponential. a 10^(b x) 10^(c y).
171 ;; Exponential (alternate notation). exp(a + b x + c y).
174 ;; Base-10 exponential (alternate). 10^(a + b x + c y).
177 ;; Logarithmic. a + b ln(x) + c ln(y).
180 ;; Base-10 logarithmic. a + b log10(x) + c log10(y).
183 ;; General exponential. a b^x c^y.
186 ;; Power law. a x^b y^c.
189 ;; Quadratic. a + b (x-c)^2 + d (x-e)^2.
192 ;; Gaussian. (a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2).
195 ;; Logistic curves are used a great deal in ecology, and in predicting
196 ;; human actions, such as use of different kinds of energy in a country
197 ;; (wood, coal, oil, natural gas, etc.) or the number of scientific
198 ;; papers a person publishes, or the number of movies made.
200 ;; (The less information on which to base the curve, the higher the error
201 ;; rate. Theodore Modis ran some Monte Carlo simulations and produced
202 ;; what may be useful set of confidence levels for different amounts of
203 ;; initial information.)
209 ;; Declare functions which are defined elsewhere.
210 (declare-function calc-set-language
"calc-lang" (lang &optional option no-refresh
))
211 (declare-function calc-edit-finish
"calc-yank" (&optional keep
))
212 (declare-function calc-edit-cancel
"calc-yank" ())
213 (declare-function calc-do-quick-calc
"calc-aent" ())
214 (declare-function calc-do-calc-eval
"calc-aent" (str separator args
))
215 (declare-function calc-do-keypad
"calc-keypd" (&optional full-display interactive
))
216 (declare-function calcFunc-unixtime
"calc-forms" (date &optional zone
))
217 (declare-function math-parse-date
"calc-forms" (math-pd-str))
218 (declare-function math-lessp
"calc-ext" (a b
))
219 (declare-function calc-embedded-finish-command
"calc-embed" ())
220 (declare-function calc-embedded-select-buffer
"calc-embed" ())
221 (declare-function calc-embedded-mode-line-change
"calc-embed" ())
222 (declare-function calc-push-list-in-macro
"calc-prog" (vals m sels
))
223 (declare-function calc-replace-selections
"calc-sel" (n vals m
))
224 (declare-function calc-record-list
"calc-misc" (vals &optional prefix
))
225 (declare-function calc-normalize-fancy
"calc-ext" (val))
226 (declare-function calc-do-handle-whys
"calc-misc" ())
227 (declare-function calc-top-selected
"calc-sel" (&optional n m
))
228 (declare-function calc-sel-error
"calc-sel" ())
229 (declare-function calc-pop-stack-in-macro
"calc-prog" (n mm
))
230 (declare-function calc-embedded-stack-change
"calc-embed" ())
231 (declare-function calc-refresh-evaltos
"calc-ext" (&optional which-var
))
232 (declare-function calc-do-refresh
"calc-misc" ())
233 (declare-function calc-binary-op-fancy
"calc-ext" (name func arg ident unary
))
234 (declare-function calc-unary-op-fancy
"calc-ext" (name func arg
))
235 (declare-function calc-delete-selection
"calc-sel" (n))
236 (declare-function calc-alg-digit-entry
"calc-aent" ())
237 (declare-function calc-alg-entry
"calc-aent" (&optional initial prompt
))
238 (declare-function calc-dots
"calc-incom" ())
239 (declare-function calc-temp-minibuffer-message
"calc-misc" (m))
240 (declare-function math-read-radix-digit
"calc-misc" (dig))
241 (declare-function calc-digit-dots
"calc-incom" ())
242 (declare-function math-normalize-fancy
"calc-ext" (a))
243 (declare-function math-normalize-nonstandard
"calc-ext" ())
244 (declare-function math-recompile-eval-rules
"calc-alg" ())
245 (declare-function math-apply-rewrites
"calc-rewr" (expr rules
&optional heads math-apply-rw-ruleset
))
246 (declare-function calc-record-why
"calc-misc" (&rest stuff
))
247 (declare-function math-dimension-error
"calc-vec" ())
248 (declare-function calc-incomplete-error
"calc-incom" (a))
249 (declare-function math-float-fancy
"calc-arith" (a))
250 (declare-function math-neg-fancy
"calc-arith" (a))
251 (declare-function math-zerop
"calc-misc" (a))
252 (declare-function calc-add-fractions
"calc-frac" (a b
))
253 (declare-function math-add-objects-fancy
"calc-arith" (a b
))
254 (declare-function math-add-symb-fancy
"calc-arith" (a b
))
255 (declare-function math-mul-zero
"calc-arith" (a b
))
256 (declare-function calc-mul-fractions
"calc-frac" (a b
))
257 (declare-function math-mul-objects-fancy
"calc-arith" (a b
))
258 (declare-function math-mul-symb-fancy
"calc-arith" (a b
))
259 (declare-function math-reject-arg
"calc-misc" (&optional a p option
))
260 (declare-function math-div-by-zero
"calc-arith" (a b
))
261 (declare-function math-div-zero
"calc-arith" (a b
))
262 (declare-function math-make-frac
"calc-frac" (num den
))
263 (declare-function calc-div-fractions
"calc-frac" (a b
))
264 (declare-function math-div-objects-fancy
"calc-arith" (a b
))
265 (declare-function math-div-symb-fancy
"calc-arith" (a b
))
266 (declare-function math-compose-expr
"calccomp" (a prec
))
267 (declare-function math-comp-width
"calccomp" (c))
268 (declare-function math-composition-to-string
"calccomp" (c &optional width
))
269 (declare-function math-stack-value-offset-fancy
"calccomp" ())
270 (declare-function math-format-flat-expr-fancy
"calc-ext" (a prec
))
271 (declare-function math-adjust-fraction
"calc-ext" (a))
272 (declare-function math-format-binary
"calc-bin" (a))
273 (declare-function math-format-radix
"calc-bin" (a))
274 (declare-function math-group-float
"calc-ext" (str))
275 (declare-function math-mod
"calc-misc" (a b
))
276 (declare-function math-format-number-fancy
"calc-ext" (a prec
))
277 (declare-function math-format-bignum-fancy
"calc-ext" (a))
278 (declare-function math-read-number-fancy
"calc-ext" (s))
279 (declare-function calc-do-grab-region
"calc-yank" (top bot arg
))
280 (declare-function calc-do-grab-rectangle
"calc-yank" (top bot arg
&optional reduce
))
281 (declare-function calc-do-embedded
"calc-embed" (calc-embed-arg end obeg oend
))
282 (declare-function calc-do-embedded-activate
"calc-embed" (calc-embed-arg cbuf
))
283 (declare-function math-do-defmath
"calc-prog" (func args body
))
284 (declare-function calc-load-everything
"calc-ext" ())
291 :group
'applications
)
294 (defcustom calc-settings-file
295 (convert-standard-filename "~/.calc.el")
296 "*File in which to record permanent settings."
300 (defcustom calc-language-alist
301 '((latex-mode . latex
)
303 (plain-tex-mode . tex
)
306 (pascal-mode . pascal
)
309 (fortran-mode . fortran
)
311 (texinfo-mode . calc-normal-language
))
312 "*Alist of major modes with appropriate Calc languages."
314 :type
'(alist :key-type
(symbol :tag
"Major mode")
315 :value-type
(symbol :tag
"Calc language")))
317 (defcustom calc-embedded-announce-formula
318 "%Embed\n\\(% .*\n\\)*"
319 "*A regular expression which is sure to be followed by a calc-embedded formula."
323 (defcustom calc-embedded-announce-formula-alist
324 '((c++-mode .
"//Embed\n\\(// .*\n\\)*")
325 (c-mode .
"/\\*Embed\\*/\n\\(/\\* .*\\*/\n\\)*")
326 (f90-mode .
"!Embed\n\\(! .*\n\\)*")
327 (fortran-mode .
"C Embed\n\\(C .*\n\\)*")
328 (html-helper-mode .
"<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
329 (html-mode .
"<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
330 (nroff-mode .
"\\\\\"Embed\n\\(\\\\\" .*\n\\)*")
331 (pascal-mode .
"{Embed}\n\\({.*}\n\\)*")
332 (sgml-mode .
"<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
333 (xml-mode .
"<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
334 (texinfo-mode .
"@c Embed\n\\(@c .*\n\\)*"))
335 "*Alist of major modes with appropriate values for `calc-embedded-announce-formula'."
337 :type
'(alist :key-type
(symbol :tag
"Major mode")
338 :value-type
(regexp :tag
"Regexp to announce formula")))
340 (defcustom calc-embedded-open-formula
341 "\\`\\|^\n\\|\\$\\$?\\|\\\\\\[\\|^\\\\begin[^{].*\n\\|^\\\\begin{.*[^x]}.*\n\\|^@.*\n\\|^\\.EQ.*\n\\|\\\\(\\|^%\n\\|^\\.\\\\\"\n"
342 "*A regular expression for the opening delimiter of a formula used by calc-embedded."
346 (defcustom calc-embedded-close-formula
347 "\\'\\|\n$\\|\\$\\$?\\|\\\\]\\|^\\\\end[^{].*\n\\|^\\\\end{.*[^x]}.*\n\\|^@.*\n\\|^\\.EN.*\n\\|\\\\)\\|\n%\n\\|^\\.\\\\\"\n"
348 "*A regular expression for the closing delimiter of a formula used by calc-embedded."
352 (defcustom calc-embedded-open-close-formula-alist
354 "*Alist of major modes with pairs of formula delimiters used by calc-embedded."
356 :type
'(alist :key-type
(symbol :tag
"Major mode")
357 :value-type
(list (regexp :tag
"Opening formula delimiter")
358 (regexp :tag
"Closing formula delimiter"))))
360 (defcustom calc-embedded-open-word
362 "*A regular expression for the opening delimiter of a formula used by calc-embedded-word."
366 (defcustom calc-embedded-close-word
368 "*A regular expression for the closing delimiter of a formula used by calc-embedded-word."
372 (defcustom calc-embedded-open-close-word-alist
374 "*Alist of major modes with pairs of word delimiters used by calc-embedded."
376 :type
'(alist :key-type
(symbol :tag
"Major mode")
377 :value-type
(list (regexp :tag
"Opening word delimiter")
378 (regexp :tag
"Closing word delimiter"))))
380 (defcustom calc-embedded-open-plain
382 "*A string which is the opening delimiter for a \"plain\" formula.
383 If calc-show-plain mode is enabled, this is inserted at the front of
388 (defcustom calc-embedded-close-plain
390 "*A string which is the closing delimiter for a \"plain\" formula.
391 See calc-embedded-open-plain."
395 (defcustom calc-embedded-open-close-plain-alist
396 '((c++-mode
"// %% " " %%\n")
397 (c-mode "/* %% " " %% */\n")
398 (f90-mode "! %% " " %%\n")
399 (fortran-mode "C %% " " %%\n")
400 (html-helper-mode "<!-- %% " " %% -->\n")
401 (html-mode "<!-- %% " " %% -->\n")
402 (nroff-mode "\\\" %% " " %%\n")
403 (pascal-mode "{%% " " %%}\n")
404 (sgml-mode "<!-- %% " " %% -->\n")
405 (xml-mode "<!-- %% " " %% -->\n")
406 (texinfo-mode "@c %% " " %%\n"))
407 "*Alist of major modes with pairs of delimiters for \"plain\" formulas."
409 :type
'(alist :key-type
(symbol :tag
"Major mode")
410 :value-type
(list (string :tag
"Opening \"plain\" delimiter")
411 (string :tag
"Closing \"plain\" delimiter"))))
413 (defcustom calc-embedded-open-new-formula
415 "*A string which is inserted at front of formula by calc-embedded-new-formula."
419 (defcustom calc-embedded-close-new-formula
421 "*A string which is inserted at end of formula by calc-embedded-new-formula."
425 (defcustom calc-embedded-open-close-new-formula-alist
427 "*Alist of major modes with pairs of new formula delimiters used by calc-embedded."
429 :type
'(alist :key-type
(symbol :tag
"Major mode")
430 :value-type
(list (string :tag
"Opening new formula delimiter")
431 (string :tag
"Closing new formula delimiter"))))
433 (defcustom calc-embedded-open-mode
435 "*A string which should precede calc-embedded mode annotations.
436 This is not required to be present for user-written mode annotations."
440 (defcustom calc-embedded-close-mode
442 "*A string which should follow calc-embedded mode annotations.
443 This is not required to be present for user-written mode annotations."
447 (defcustom calc-embedded-open-close-mode-alist
448 '((c++-mode
"// " "\n")
449 (c-mode "/* " " */\n")
451 (fortran-mode "C " "\n")
452 (html-helper-mode "<!-- " " -->\n")
453 (html-mode "<!-- " " -->\n")
454 (nroff-mode "\\\" " "\n")
455 (pascal-mode "{ " " }\n")
456 (sgml-mode "<!-- " " -->\n")
457 (xml-mode "<!-- " " -->\n")
458 (texinfo-mode "@c " "\n"))
459 "*Alist of major modes with pairs of strings to delimit annotations."
461 :type
'(alist :key-type
(symbol :tag
"Major mode")
462 :value-type
(list (string :tag
"Opening annotation delimiter")
463 (string :tag
"Closing annotation delimiter"))))
465 (defcustom calc-gnuplot-name
467 "*Name of GNUPLOT program, for calc-graph features."
471 (defcustom calc-gnuplot-plot-command
473 "*Name of command for displaying GNUPLOT output; %s = file name to print."
475 :type
'(choice (string) (sexp)))
477 (defcustom calc-gnuplot-print-command
479 "*Name of command for printing GNUPLOT output; %s = file name to print."
481 :type
'(choice (string) (sexp)))
483 (defcustom calc-multiplication-has-precedence
485 "*If non-nil, multiplication has precedence over division
490 (defvar calc-bug-address
"jay.p.belanger@gmail.com"
491 "Address of the maintainer of Calc, for use by `report-calc-bug'.")
493 (defvar calc-scan-for-dels t
494 "If t, scan keymaps to find all DEL-like keys.
495 if nil, only DEL itself is mapped to calc-pop.")
497 (defvar calc-stack
'((top-of-stack 1 nil
))
499 Entries are 3-lists: Formula, Height (in lines), Selection (or nil).")
501 (defvar calc-stack-top
1
502 "Index into `calc-stack' of \"top\" of stack.
503 This is 1 unless `calc-truncate-stack' has been used.")
505 (defvar calc-display-sci-high
0
506 "Floating-point numbers with this positive exponent or higher above the
507 current precision are displayed in scientific notation in calc-mode.")
509 (defvar calc-display-sci-low -
3
510 "Floating-point numbers with this negative exponent or lower are displayed
511 scientific notation in calc-mode.")
513 (defvar calc-other-modes nil
514 "List of used-defined strings to append to Calculator mode line.")
516 (defvar calc-Y-help-msgs nil
517 "List of strings for Y prefix help.")
519 (defvar calc-loaded-settings-file nil
520 "t if `calc-settings-file' has been loaded yet.")
523 (defvar calc-mode-var-list
'()
524 "List of variables used in customizing GNU Calc.")
526 (defmacro defcalcmodevar
(var defval
&optional doc
)
528 (defvar ,var
,defval
,doc
)
529 (add-to-list 'calc-mode-var-list
(list (quote ,var
) ,defval
))))
531 (defun calc-mode-var-list-restore-default-values ()
532 (mapcar (function (lambda (v) (set (car v
) (nth 1 v
))))
535 (defun calc-mode-var-list-restore-saved-values ()
536 (let ((newvarlist '()))
539 (file (substitute-in-file-name calc-settings-file
)))
541 (file-regular-p file
)
542 (set-buffer (find-file-noselect file
))
543 (goto-char (point-min))
544 (search-forward ";;; Mode settings stored by Calc" nil t
)
548 (search-forward "\n;;; End of mode settings" nil t
)))
550 (calc-mode-var-list-restore-default-values)
551 (eval-region pos
(point))
552 (let ((varlist calc-mode-var-list
))
554 (let ((var (car varlist
)))
556 (cons (list (car var
) (symbol-value (car var
)))
558 (setq varlist
(cdr varlist
)))))))
560 (mapcar (function (lambda (v) (set (car v
) (nth 1 v
))))
562 (calc-mode-var-list-restore-default-values))))
564 (defcalcmodevar calc-always-load-extensions nil
565 "If non-nil, load the calc-ext module automatically when calc is loaded.")
567 (defcalcmodevar calc-line-numbering t
568 "If non-nil, display line numbers in Calculator stack.")
570 (defcalcmodevar calc-line-breaking t
571 "If non-nil, break long values across multiple lines in Calculator stack.")
573 (defcalcmodevar calc-display-just nil
574 "If nil, stack display is left-justified.
575 If `right', stack display is right-justified.
576 If `center', stack display is centered.")
578 (defcalcmodevar calc-display-origin nil
579 "Horizontal origin of displayed stack entries.
580 In left-justified mode, this is effectively indentation. (Default 0).
581 In right-justified mode, this is effectively window width.
582 In centered mode, center of stack entry is placed here.")
584 (defcalcmodevar calc-number-radix
10
585 "Radix for entry and display of numbers in calc-mode, 2-36.")
587 (defcalcmodevar calc-leading-zeros nil
588 "If non-nil, leading zeros are provided to pad integers to calc-word-size.")
590 (defcalcmodevar calc-group-digits nil
591 "If non-nil, group digits in large displayed integers by inserting spaces.
592 If an integer, group that many digits at a time.
593 If t, use 4 for binary and hex, 3 otherwise.")
595 (defcalcmodevar calc-group-char
","
596 "The character (in the form of a string) to be used for grouping digits.
597 This is used only when calc-group-digits mode is on.")
599 (defcalcmodevar calc-point-char
"."
600 "The character (in the form of a string) to be used as a decimal point.")
602 (defcalcmodevar calc-frac-format
'(":" nil
)
603 "Format of displayed fractions; a string of one or two of \":\" or \"/\".")
605 (defcalcmodevar calc-prefer-frac nil
606 "If non-nil, prefer fractional over floating-point results.")
608 (defcalcmodevar calc-hms-format
"%s@ %s' %s\""
609 "Format of displayed hours-minutes-seconds angles, a format string.
610 String must contain three %s marks for hours, minutes, seconds respectively.")
612 (defcalcmodevar calc-date-format
'((H ":" mm C SS pp
" ")
613 Www
" " Mmm
" " D
", " YYYY
)
614 "Format of displayed date forms.")
616 (defcalcmodevar calc-float-format
'(float 0)
617 "Format to use for display of floating-point numbers in calc-mode.
618 Must be a list of one of the following forms:
619 (float 0) Floating point format, display full precision.
620 (float N) N > 0: Floating point format, at most N significant figures.
621 (float -N) -N < 0: Floating point format, calc-internal-prec - N figs.
622 (fix N) N >= 0: Fixed point format, N places after decimal point.
623 (sci 0) Scientific notation, full precision.
624 (sci N) N > 0: Scientific notation, N significant figures.
625 (sci -N) -N < 0: Scientific notation, calc-internal-prec - N figs.
626 (eng 0) Engineering notation, full precision.
627 (eng N) N > 0: Engineering notation, N significant figures.
628 (eng -N) -N < 0: Engineering notation, calc-internal-prec - N figs.")
630 (defcalcmodevar calc-full-float-format
'(float 0)
631 "Format to use when full precision must be displayed.")
633 (defcalcmodevar calc-complex-format nil
634 "Format to use for display of complex numbers in calc-mode. Must be one of:
639 (defcalcmodevar calc-complex-mode
'cplx
640 "Preferred form, either `cplx' or `polar', for complex numbers.")
642 (defcalcmodevar calc-infinite-mode nil
643 "If nil, 1 / 0 is left unsimplified.
644 If 0, 1 / 0 is changed to inf (zeros are considered positive).
645 Otherwise, 1 / 0 is changed to uinf (undirected infinity).")
647 (defcalcmodevar calc-display-strings nil
648 "If non-nil, display vectors of byte-sized integers as strings.")
650 (defcalcmodevar calc-matrix-just
'center
651 "If nil, vector elements are left-justified.
652 If `right', vector elements are right-justified.
653 If `center', vector elements are centered.")
655 (defcalcmodevar calc-break-vectors nil
656 "If non-nil, display vectors one element per line.")
658 (defcalcmodevar calc-full-vectors t
659 "If non-nil, display long vectors in full. If nil, use abbreviated form.")
661 (defcalcmodevar calc-full-trail-vectors t
662 "If non-nil, display long vectors in full in the trail.")
664 (defcalcmodevar calc-vector-commas
","
665 "If non-nil, separate elements of displayed vectors with this string.")
667 (defcalcmodevar calc-vector-brackets
"[]"
668 "If non-nil, surround displayed vectors with these characters.")
670 (defcalcmodevar calc-matrix-brackets
'(R O
)
671 "A list of code-letter symbols that control \"big\" matrix display.
672 If `R' is present, display inner brackets for matrices.
673 If `O' is present, display outer brackets for matrices (above/below).
674 If `C' is present, display outer brackets for matrices (centered).")
676 (defcalcmodevar calc-language nil
677 "Language or format for entry and display of stack values. Must be one of:
678 nil Use standard Calc notation.
679 flat Use standard Calc notation, one-line format.
680 big Display formulas in 2-d notation (enter w/std notation).
681 unform Use unformatted display: add(a, mul(b,c)).
682 c Use C language notation.
683 pascal Use Pascal language notation.
684 fortran Use Fortran language notation.
685 tex Use TeX notation.
686 latex Use LaTeX notation.
687 eqn Use eqn notation.
688 yacas Use Yacas notation.
689 maxima Use Maxima notation.
690 giac Use Giac notation.
691 math Use Mathematica(tm) notation.
692 maple Use Maple notation.")
694 (defcalcmodevar calc-language-option nil
695 "Numeric prefix argument for the command that set `calc-language'.")
697 (defcalcmodevar calc-left-label
""
698 "Label to display at left of formula.")
700 (defcalcmodevar calc-right-label
""
701 "Label to display at right of formula.")
703 (defcalcmodevar calc-word-size
32
704 "Minimum number of bits per word, if any, for binary operations in calc-mode.")
706 (defcalcmodevar calc-previous-modulo nil
707 "Most recently used value of M in a modulo form.")
709 (defcalcmodevar calc-simplify-mode nil
710 "Type of simplification applied to results.
711 If `none', results are not simplified when pushed on the stack.
712 If `num', functions are simplified only when args are constant.
713 If nil, only fast simplifications are applied.
714 If `binary', `math-clip' is applied if appropriate.
715 If `alg', `math-simplify' is applied.
716 If `ext', `math-simplify-extended' is applied.
717 If `units', `math-simplify-units' is applied.")
719 (defcalcmodevar calc-auto-recompute t
720 "If non-nil, recompute evalto's automatically when necessary.")
722 (defcalcmodevar calc-display-raw nil
723 "If non-nil, display shows unformatted Lisp exprs. (For debugging)")
725 (defcalcmodevar calc-internal-prec
12
726 "Number of digits of internal precision for calc-mode calculations.")
728 (defcalcmodevar calc-angle-mode
'deg
729 "If deg, angles are in degrees; if rad, angles are in radians.
730 If hms, angles are in degrees-minutes-seconds.")
732 (defcalcmodevar calc-algebraic-mode nil
733 "If non-nil, numeric entry accepts whole algebraic expressions.
734 If nil, algebraic expressions must be preceded by \"'\".")
736 (defcalcmodevar calc-incomplete-algebraic-mode nil
737 "Like calc-algebraic-mode except only affects ( and [ keys.")
739 (defcalcmodevar calc-symbolic-mode nil
740 "If non-nil, inexact numeric computations like sqrt(2) are postponed.
741 If nil, computations on numbers always yield numbers where possible.")
743 (defcalcmodevar calc-matrix-mode nil
744 "If `matrix', variables are assumed to be matrix-valued.
745 If a number, variables are assumed to be NxN matrices.
746 If `sqmatrix', variables are assumed to be square matrices of an unspecified size.
747 If `scalar', variables are assumed to be scalar-valued.
748 If nil, symbolic math routines make no assumptions about variables.")
750 (defcalcmodevar calc-shift-prefix nil
751 "If non-nil, shifted letter keys are prefix keys rather than normal meanings.")
753 (defcalcmodevar calc-window-height
7
754 "Initial height of Calculator window.")
756 (defcalcmodevar calc-display-trail t
757 "If non-nil, M-x calc creates a window to display Calculator trail.")
759 (defcalcmodevar calc-show-selections t
760 "If non-nil, selected sub-formulas are shown by obscuring rest of formula.
761 If nil, selected sub-formulas are highlighted by obscuring the sub-formulas.")
763 (defcalcmodevar calc-use-selections t
764 "If non-nil, commands operate only on selected portions of formulas.
765 If nil, selections displayed but ignored.")
767 (defcalcmodevar calc-assoc-selections t
768 "If non-nil, selection hides deep structure of associative formulas.")
770 (defcalcmodevar calc-display-working-message
'lots
771 "If non-nil, display \"Working...\" for potentially slow Calculator commands.")
773 (defcalcmodevar calc-auto-why
'maybe
774 "If non-nil, automatically execute a \"why\" command to explain odd results.")
776 (defcalcmodevar calc-timing nil
777 "If non-nil, display timing information on each slow command.")
779 (defcalcmodevar calc-mode-save-mode
'local
)
781 (defcalcmodevar calc-standard-date-formats
783 "<H:mm:SSpp >Www Mmm D, YYYY"
784 "D Mmm YYYY<, h:mm:SS>"
785 "Www Mmm BD< hh:mm:ss> YYYY"
793 (defcalcmodevar calc-autorange-units nil
)
795 (defcalcmodevar calc-was-keypad-mode nil
)
797 (defcalcmodevar calc-full-mode nil
)
799 (defcalcmodevar calc-user-parse-tables nil
)
801 (defcalcmodevar calc-gnuplot-default-device
"default")
803 (defcalcmodevar calc-gnuplot-default-output
"STDOUT")
805 (defcalcmodevar calc-gnuplot-print-device
"postscript")
807 (defcalcmodevar calc-gnuplot-print-output
"auto")
809 (defcalcmodevar calc-gnuplot-geometry nil
)
811 (defcalcmodevar calc-graph-default-resolution
15)
813 (defcalcmodevar calc-graph-default-resolution-3d
5)
815 (defcalcmodevar calc-invocation-macro nil
)
817 (defcalcmodevar calc-show-banner t
818 "*If non-nil, show a friendly greeting above the stack.")
820 (defconst calc-local-var-list
'(calc-stack
824 calc-always-load-extensions
835 calc-incomplete-algebraic-mode
851 calc-standard-date-formats
853 calc-full-float-format
857 calc-full-trail-vectors
871 calc-assoc-selections
875 (defvar calc-mode-hook nil
876 "Hook run when entering calc-mode.")
878 (defvar calc-trail-mode-hook nil
879 "Hook run when entering calc-trail-mode.")
881 (defvar calc-start-hook nil
882 "Hook run when calc is started.")
884 (defvar calc-end-hook nil
885 "Hook run when calc is quit.")
887 (defvar calc-load-hook nil
888 "Hook run when calc.el is loaded.")
890 (defvar calc-window-hook nil
891 "Hook called to create the Calc window.")
893 (defvar calc-trail-window-hook nil
894 "Hook called to create the Calc trail window.")
896 (defvar calc-embedded-new-buffer-hook nil
897 "Hook run when starting embedded mode in a new buffer.")
899 (defvar calc-embedded-new-formula-hook nil
900 "Hook run when starting embedded mode in a new formula.")
902 (defvar calc-embedded-mode-hook nil
903 "Hook run when starting embedded mode.")
905 ;; Set up the autoloading linkage.
906 (let ((name (and (fboundp 'calc-dispatch
)
907 (eq (car-safe (symbol-function 'calc-dispatch
)) 'autoload
)
908 (nth 1 (symbol-function 'calc-dispatch
))))
911 ;; If Calc files exist on the load-path, we're all set.
912 (while (and p
(not (file-exists-p
913 (expand-file-name "calc-misc.elc" (car p
)))))
917 ;; If Calc is autoloaded using a path name, look there for Calc files.
918 ;; This works for both relative ("calc/calc.elc") and absolute paths.
919 (and name
(file-name-directory name
)
921 (name2 (concat (file-name-directory name
)
923 (while (and p2
(not (file-exists-p
924 (expand-file-name name2
(car p2
)))))
927 (setq load-path
(nconc load-path
932 name
(car p2
))))))))))))
934 ;; The following modes use specially-formatted data.
935 (put 'calc-mode
'mode-class
'special
)
936 (put 'calc-trail-mode
'mode-class
'special
)
938 ;; Define "inexact-result" as an e-lisp error symbol.
939 (put 'inexact-result
'error-conditions
'(error inexact-result calc-error
))
940 (put 'inexact-result
'error-message
"Calc internal error (inexact-result)")
942 ;; Define "math-overflow" and "math-underflow" as e-lisp error symbols.
943 (put 'math-overflow
'error-conditions
'(error math-overflow calc-error
))
944 (put 'math-overflow
'error-message
"Floating-point overflow occurred")
945 (put 'math-underflow
'error-conditions
'(error math-underflow calc-error
))
946 (put 'math-underflow
'error-message
"Floating-point underflow occurred")
948 (defconst calc-version
"2.1")
949 (defvar calc-trail-pointer nil
) ; "Current" entry in trail buffer.
950 (defvar calc-trail-overlay nil
) ; Value of overlay-arrow-string.
951 (defvar calc-undo-list nil
) ; List of previous operations for undo.
952 (defvar calc-redo-list nil
) ; List of recent undo operations.
953 (defvar calc-main-buffer nil
) ; Pointer to Calculator buffer.
954 (defvar calc-trail-buffer nil
) ; Pointer to Calc Trail buffer.
955 (defvar calc-why nil
) ; Explanations of most recent errors.
956 (defvar calc-next-why nil
)
957 (defvar calc-inverse-flag nil
958 "If non-nil, next operation is Inverse.")
959 (defvar calc-hyperbolic-flag nil
960 "If non-nil, next operation is Hyperbolic.")
961 (defvar calc-keep-args-flag nil
962 "If non-nil, next operation should not remove its arguments from stack.")
963 (defvar calc-function-open
"("
964 "Open-parenthesis string for function call notation.")
965 (defvar calc-function-close
")"
966 "Close-parenthesis string for function call notation.")
967 (defvar calc-language-output-filter nil
968 "Function through which to pass strings after formatting.")
969 (defvar calc-language-input-filter nil
970 "Function through which to pass strings before parsing.")
971 (defvar calc-radix-formatter nil
972 "Formatting function used for non-decimal numbers.")
973 (defvar calc-lang-slash-idiv nil
974 "A list of languages in which / might represent integer division.")
975 (defvar calc-lang-allow-underscores nil
976 "A list of languages which allow underscores in variable names.")
977 (defvar calc-lang-allow-percentsigns nil
978 "A list of languages which allow percent signs in variable names.")
979 (defvar calc-lang-c-type-hex nil
980 "Languages in which octal and hex numbers are written with leading 0 and 0x,")
981 (defvar calc-lang-brackets-are-subscripts nil
982 "Languages in which subscripts are indicated by brackets.")
983 (defvar calc-lang-parens-are-subscripts nil
984 "Languages in which subscripts are indicated by parentheses.")
986 (defvar calc-last-kill nil
) ; Last number killed in calc-mode.
987 (defvar calc-dollar-values nil
) ; Values to be used for '$'.
988 (defvar calc-dollar-used nil
) ; Highest order of '$' that occurred.
989 (defvar calc-hashes-used nil
) ; Highest order of '#' that occurred.
990 (defvar calc-quick-prev-results nil
) ; Previous results from Quick Calc.
991 (defvar calc-said-hello nil
) ; Has welcome message been said yet?
992 (defvar calc-executing-macro nil
) ; Kbd macro executing from "K" key.
993 (defvar calc-any-selections nil
) ; Nil means no selections present.
994 (defvar calc-help-phase
0) ; Count of consecutive "?" keystrokes.
995 (defvar calc-full-help-flag nil
) ; Executing calc-full-help?
996 (defvar calc-refresh-count
0) ; Count of calc-refresh calls.
997 (defvar calc-display-dirty nil
)
998 (defvar calc-prepared-composition nil
)
999 (defvar calc-selection-cache-default-entry nil
)
1000 (defvar calc-embedded-info nil
)
1001 (defvar calc-embedded-active nil
)
1002 (defvar calc-standalone-flag nil
)
1003 (defvar var-EvalRules nil
)
1004 (defvar math-eval-rules-cache-tag t
)
1005 (defvar math-radix-explicit-format t
)
1006 (defvar math-expr-function-mapping nil
)
1007 (defvar math-expr-variable-mapping nil
)
1008 (defvar math-read-expr-quotes nil
)
1009 (defvar math-working-step nil
)
1010 (defvar math-working-step-2 nil
)
1011 (defvar var-i
'(special-const (math-imaginary 1)))
1012 (defvar var-pi
'(special-const (math-pi)))
1013 (defvar var-e
'(special-const (math-e)))
1014 (defvar var-phi
'(special-const (math-phi)))
1015 (defvar var-gamma
'(special-const (math-gamma-const)))
1016 (defvar var-Modes
'(special-const (math-get-modes-vec)))
1018 (mapc (lambda (v) (or (boundp v
) (set v nil
)))
1019 calc-local-var-list
)
1021 (defvar calc-mode-map
1022 (let ((map (make-keymap)))
1023 (suppress-keymap map t
)
1024 (define-key map
"+" 'calc-plus
)
1025 (define-key map
"-" 'calc-minus
)
1026 (define-key map
"*" 'calc-times
)
1027 (define-key map
"/" 'calc-divide
)
1028 (define-key map
"%" 'calc-mod
)
1029 (define-key map
"&" 'calc-inv
)
1030 (define-key map
"^" 'calc-power
)
1031 (define-key map
"\M-%" 'calc-percent
)
1032 (define-key map
"e" 'calcDigit-start
)
1033 (define-key map
"i" 'calc-info
)
1034 (define-key map
"n" 'calc-change-sign
)
1035 (define-key map
"q" 'calc-quit
)
1036 (define-key map
"Y" 'nil
)
1037 (define-key map
"Y?" 'calc-shift-Y-prefix-help
)
1038 (define-key map
"?" 'calc-help
)
1039 (define-key map
" " 'calc-enter
)
1040 (define-key map
"'" 'calc-algebraic-entry
)
1041 (define-key map
"$" 'calc-auto-algebraic-entry
)
1042 (define-key map
"\"" 'calc-auto-algebraic-entry
)
1043 (define-key map
"\t" 'calc-roll-down
)
1044 (define-key map
"\M-\t" 'calc-roll-up
)
1045 (define-key map
"\C-m" 'calc-enter
)
1046 (define-key map
"\M-\C-m" 'calc-last-args-stub
)
1047 (define-key map
"\C-j" 'calc-over
)
1049 (mapc (lambda (x) (define-key map
(char-to-string x
) 'undefined
))
1051 (mapc (lambda (x) (define-key map
(char-to-string x
) 'calc-missing-key
))
1052 (concat "ABCDEFGHIJKLMNPQRSTUVXZabcdfghjkmoprstuvwxyz"
1053 ":\\|!()[]<>{},;=~`\C-k\M-k\C-w\M-w\C-y\C-_"))
1054 (mapc (lambda (x) (define-key map
(char-to-string x
) 'calcDigit-start
))
1058 (defvar calc-digit-map
1059 (let ((map (make-keymap)))
1060 (if (featurep 'xemacs
)
1061 (map-keymap (function
1063 (define-key map keys
1064 (if (eq bind
'undefined
)
1065 'undefined
'calcDigit-nondigit
))))
1067 (let ((cmap (nth 1 calc-mode-map
))
1072 (if (eq (aref cmap i
) 'undefined
)
1073 'undefined
'calcDigit-nondigit
))
1075 (mapc (lambda (x) (define-key map
(char-to-string x
) 'calcDigit-key
))
1076 "_0123456789.e+-:n#@oh'\"mspM")
1077 (mapc (lambda (x) (define-key map
(char-to-string x
) 'calcDigit-letter
))
1078 "abcdfgijklqrtuvwxyzABCDEFGHIJKLNOPQRSTUVWXYZ")
1079 (define-key map
"'" 'calcDigit-algebraic
)
1080 (define-key map
"`" 'calcDigit-edit
)
1081 (define-key map
"\C-g" 'abort-recursive-edit
)
1087 (define-key calc-digit-map x
'calcDigit-backspace
)
1088 (define-key calc-mode-map x
'calc-pop
)
1089 (define-key calc-mode-map
1091 (if (featurep 'xemacs
)
1092 (if (= (length x
) 1)
1093 (vector (if (consp (aref x
0))
1094 (cons 'meta
(aref x
0))
1095 (list 'meta
(aref x
0))))
1101 (if calc-scan-for-dels
1102 (append (where-is-internal 'delete-backward-char global-map
)
1103 (where-is-internal 'backward-delete-char global-map
)
1104 (where-is-internal 'backward-delete-char-untabify global-map
)
1108 (defvar calc-dispatch-map
1109 (let ((map (make-keymap)))
1111 (define-key map
(char-to-string (car x
)) (cdr x
))
1112 (when (string-match "abcdefhijklnopqrstuwxyz"
1113 (char-to-string (car x
)))
1114 (define-key map
(char-to-string (- (car x
) ?a -
1)) (cdr x
)))
1115 (define-key map
(format "\e%c" (car x
)) (cdr x
)))
1116 '( ( ?a . calc-embedded-activate
)
1117 ( ?b . calc-big-or-small
)
1119 ( ?d . calc-embedded-duplicate
)
1120 ( ?e . calc-embedded
)
1121 ( ?f . calc-embedded-new-formula
)
1122 ( ?g . calc-grab-region
)
1123 ( ?h . calc-dispatch-help
)
1125 ( ?j . calc-embedded-select
)
1126 ( ?k . calc-keypad
)
1127 ( ?l . calc-load-everything
)
1128 ( ?m . read-kbd-macro
)
1129 ( ?n . calc-embedded-next
)
1130 ( ?o . calc-other-window
)
1131 ( ?p . calc-embedded-previous
)
1133 ( ?r . calc-grab-rectangle
)
1134 ( ?s . calc-info-summary
)
1135 ( ?t . calc-tutorial
)
1136 ( ?u . calc-embedded-update-formula
)
1137 ( ?w . calc-embedded-word
)
1139 ( ?y . calc-copy-to-buffer
)
1140 ( ?z . calc-user-invocation
)
1141 ( ?
\' . calc-embedded-new-formula
)
1142 ( ?\
` . calc-embedded-edit
)
1143 ( ?
: . calc-grab-sum-down
)
1144 ( ?_ . calc-grab-sum-across
)
1146 ( ?? . calc-dispatch-help
)
1147 ( ?
# . calc-same-interface
)
1148 ( ?
& . calc-same-interface
)
1149 ( ?
\\ . calc-same-interface
)
1150 ( ?
= . calc-same-interface
)
1151 ( ?
* . calc-same-interface
)
1152 ( ?
/ . calc-same-interface
)
1153 ( ?
+ . calc-same-interface
)
1154 ( ?- . calc-same-interface
) ))
1157 ;;;; (Autoloads here)
1159 (lambda (x) (dolist (func (cdr x
)) (autoload func
(car x
))))
1162 ("calc-aent" calc-alg-digit-entry calc-alg-entry
1163 calc-check-user-syntax calc-do-alg-entry calc-do-calc-eval
1164 calc-do-quick-calc calc-match-user-syntax math-build-parse-table
1165 math-find-user-tokens math-read-expr-list math-read-exprs math-read-if
1166 math-read-token math-remove-dashes math-read-preprocess-string
)
1168 ("calc-embed" calc-do-embedded-activate
)
1171 calc-do-handle-whys calc-do-refresh calc-num-prefix-name
1172 calc-record-list calc-record-why calc-report-bug calc-roll-down-stack
1173 calc-roll-up-stack calc-temp-minibuffer-message calcFunc-floor
1174 calcFunc-inv calcFunc-trunc math-concat math-constp math-div2
1175 math-div2-bignum math-do-working math-evenp math-fixnatnump
1176 math-fixnump math-floor math-imod math-ipow math-looks-negp math-mod
1177 math-negp math-posp math-pow math-read-radix-digit math-reject-arg
1178 math-trunc math-zerop
)))
1181 (lambda (x) (dolist (cmd (cdr x
)) (autoload cmd
(car x
) nil t
)))
1184 ("calc-aent" calc-algebraic-entry calc-auto-algebraic-entry
1185 calcDigit-algebraic calcDigit-edit
)
1187 ("calc-misc" another-calc calc-big-or-small calc-dispatch-help
1188 calc-help calc-info calc-info-goto-node calc-info-summary calc-inv
1190 calc-missing-key calc-mod calc-other-window calc-over calc-percent
1191 calc-pop-above calc-power calc-roll-down calc-roll-up
1192 calc-shift-Y-prefix-help calc-tutorial calcDigit-letter
1196 ;;;###autoload (define-key ctl-x-map "*" 'calc-dispatch)
1199 (defun calc-dispatch (&optional arg
)
1200 "Invoke the GNU Emacs Calculator. See `calc-dispatch-help' for details."
1202 ; (sit-for echo-keystrokes)
1203 (condition-case err
; look for other keys bound to calc-dispatch
1204 (let ((keys (this-command-keys)))
1205 (unless (or (not (stringp keys
))
1206 (string-match "\\`\C-u\\|\\`\e[-0-9#]\\|`[\M--\M-0-\M-9]" keys
)
1207 (eq (lookup-key calc-dispatch-map keys
) 'calc-same-interface
))
1208 (when (and (string-match "\\`[\C-@-\C-_]" keys
)
1210 (lookup-key calc-dispatch-map
(substring keys
0 1))))
1211 (define-key calc-dispatch-map
(substring keys
0 1) nil
))
1212 (define-key calc-dispatch-map keys
'calc-same-interface
)))
1214 (calc-do-dispatch arg
))
1216 (defvar calc-dispatch-help nil
)
1217 (defun calc-do-dispatch (arg)
1218 (let ((key (calc-read-key-sequence
1219 (if calc-dispatch-help
1220 "Calc options: Calc, Keypad, Quick, Embed; eXit; Info, Tutorial; Grab; ?=more"
1221 (format "%s (Type ? for a list of Calc options)"
1222 (key-description (this-command-keys))))
1223 calc-dispatch-map
)))
1224 (setq key
(lookup-key calc-dispatch-map key
))
1228 (or (commandp key
) (require 'calc-ext
))
1229 (call-interactively key
))
1232 (defun calc-read-key-sequence (prompt map
)
1233 (let ((prompt2 (format "%s " (key-description (this-command-keys))))
1234 (glob (current-global-map))
1235 (loc (current-local-map)))
1236 (or (input-pending-p) (message "%s" prompt
))
1237 (let ((key (calc-read-key t
)))
1238 (calc-unread-command (cdr key
))
1241 (use-global-map map
)
1243 (read-key-sequence nil
))
1244 (use-global-map glob
)
1245 (use-local-map loc
)))))
1247 (defvar calc-alg-map
) ; Defined in calc-ext.el
1249 (defun calc-version ()
1250 "Return version of this version of Calc."
1252 (message "Calc version %s" calc-version
))
1255 "Calculator major mode.
1257 This is an RPN calculator featuring arbitrary-precision integer, rational,
1258 floating-point, complex, matrix, and symbolic arithmetic.
1260 RPN calculation: 2 RET 3 + produces 5.
1261 Algebraic style: ' 2+3 RET produces 5.
1263 Basic operators are +, -, *, /, ^, & (reciprocal), % (modulo), n (change-sign).
1265 Press ? repeatedly for more complete help. Press `h i' to read the
1266 Calc manual on-line, `h s' to read the summary, or `h t' for the tutorial.
1268 Notations: 3.14e6 3.14 * 10^6
1269 _23 negative number -23 (or type `23 n')
1270 17:3 the fraction 17/3
1271 5:2:3 the fraction 5 and 2/3
1272 16#12C the integer 12C base 16 = 300 base 10
1273 8#177:100 the fraction 177:100 base 8 = 127:64 base 10
1274 (2, 4) complex number 2 + 4i
1275 (2; 4) polar complex number (r; theta)
1276 [1, 2, 3] vector ([[1, 2], [3, 4]] is a matrix)
1277 [1 .. 4) semi-open interval, 1 <= x < 4
1278 2 +/- 3 (p key) number with mean 2, standard deviation 3
1279 2 mod 3 (M key) number 2 computed modulo 3
1280 <1 jan 91> Date form (enter using ' key)
1287 (lambda (v) (set-default v
(symbol-value v
)))) calc-local-var-list
)
1288 (kill-all-local-variables)
1289 (use-local-map (if (eq calc-algebraic-mode
'total
)
1290 (progn (require 'calc-ext
) calc-alg-map
) calc-mode-map
))
1291 (mapc (function (lambda (v) (make-local-variable v
))) calc-local-var-list
)
1292 (make-local-variable 'overlay-arrow-position
)
1293 (make-local-variable 'overlay-arrow-string
)
1294 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
1295 (setq truncate-lines t
)
1296 (setq buffer-read-only t
)
1297 (setq major-mode
'calc-mode
)
1298 (setq mode-name
"Calculator")
1299 (setq calc-stack-top
(length (or (memq (assq 'top-of-stack calc-stack
)
1301 (setq calc-stack
(list (list 'top-of-stack
1303 (setq calc-stack-top
(- (length calc-stack
) calc-stack-top -
1))
1304 (or calc-loaded-settings-file
1305 (null calc-settings-file
)
1306 (equal calc-settings-file user-init-file
)
1308 (setq calc-loaded-settings-file t
)
1309 (load (file-name-sans-extension calc-settings-file
) t
))) ; t = missing-ok
1310 (let ((p command-line-args
))
1312 (and (equal (car p
) "-f")
1313 (string-match "calc" (nth 1 p
))
1314 (string-match "full" (nth 1 p
))
1315 (setq calc-standalone-flag t
))
1317 (require 'calc-menu
)
1318 (run-mode-hooks 'calc-mode-hook
)
1320 (calc-set-mode-line)
1321 (calc-check-defines))
1323 (defvar calc-check-defines
'calc-check-defines
) ; suitable for run-hooks
1324 (defun calc-check-defines ()
1325 (if (symbol-plist 'calc-define
)
1326 (let ((plist (copy-sequence (symbol-plist 'calc-define
))))
1327 (while (and plist
(null (nth 1 plist
)))
1328 (setq plist
(cdr (cdr plist
))))
1332 (require 'calc-macs
)
1333 (set-buffer "*Calculator*")
1335 (put 'calc-define
(car plist
) nil
)
1336 (eval (nth 1 plist
))
1337 (setq plist
(cdr (cdr plist
))))
1338 ;; See if this has added any more calc-define properties.
1339 (calc-check-defines))
1340 (setplist 'calc-define nil
)))))
1342 (defun calc-trail-mode (&optional buf
)
1344 This mode is used by the *Calc Trail* buffer, which records all results
1345 obtained by the GNU Emacs Calculator.
1347 Calculator commands beginning with the `t' key are used to manipulate
1350 This buffer uses the same key map as the *Calculator* buffer; calculator
1351 commands given here will actually operate on the *Calculator* stack."
1354 (use-local-map calc-mode-map
)
1355 (setq major-mode
'calc-trail-mode
)
1356 (setq mode-name
"Calc Trail")
1357 (setq truncate-lines t
)
1358 (setq buffer-read-only t
)
1359 (make-local-variable 'overlay-arrow-position
)
1360 (make-local-variable 'overlay-arrow-string
)
1362 (set (make-local-variable 'calc-main-buffer
) buf
))
1363 (when (= (buffer-size) 0)
1364 (let ((buffer-read-only nil
))
1365 (insert (propertize (concat "Emacs Calculator Trail\n")
1366 'font-lock-face
'italic
))))
1367 (run-mode-hooks 'calc-trail-mode-hook
))
1369 (defun calc-create-buffer ()
1370 (set-buffer (get-buffer-create "*Calculator*"))
1371 (or (eq major-mode
'calc-mode
)
1373 (setq max-lisp-eval-depth
(max max-lisp-eval-depth
1000))
1374 (when calc-always-load-extensions
1375 (require 'calc-ext
))
1378 (calc-set-language calc-language calc-language-option t
)))
1381 (defun calc (&optional arg full-display interactive
)
1382 "The Emacs Calculator. Full documentation is listed under \"calc-mode\"."
1383 (interactive "P\ni\np")
1387 (if (= (prefix-numeric-value arg
) -
1)
1388 (calc-grab-region (region-beginning) (region-end) nil
)
1389 (when (= (prefix-numeric-value arg
) -
2)
1391 (when (get-buffer-window "*Calc Keypad*")
1393 (set-buffer (window-buffer (selected-window))))
1394 (if (eq major-mode
'calc-mode
)
1396 (let ((oldbuf (current-buffer)))
1397 (calc-create-buffer)
1398 (setq calc-was-keypad-mode nil
)
1399 (if (or (eq full-display t
)
1400 (and (null full-display
) calc-full-mode
))
1401 (switch-to-buffer (current-buffer) t
)
1402 (if (get-buffer-window (current-buffer))
1403 (select-window (get-buffer-window (current-buffer)))
1404 (if calc-window-hook
1405 (run-hooks 'calc-window-hook
)
1406 (let ((w (get-largest-window)))
1407 (if (and pop-up-windows
1408 (> (window-height w
)
1409 (+ window-min-height calc-window-height
2)))
1411 (setq w
(split-window w
1412 (- (window-height w
)
1413 calc-window-height
2)
1415 (set-window-buffer w
(current-buffer))
1417 (pop-to-buffer (current-buffer)))))))
1419 (set-buffer (calc-trail-buffer))
1420 (and calc-display-trail
1421 (= (window-width) (frame-width))
1422 (calc-trail-display 1 t
)))
1423 (message "Welcome to the GNU Emacs Calculator! Press `?' or `h' for help, `q' to quit")
1424 (run-hooks 'calc-start-hook
)
1425 (and (windowp full-display
)
1426 (window-point full-display
)
1427 (select-window full-display
))
1428 (calc-check-defines)
1429 (when (and calc-said-hello interactive
)
1432 (setq calc-said-hello t
)))))
1435 (defun full-calc (&optional interactive
)
1436 "Invoke the Calculator and give it a full-sized window."
1438 (calc nil t interactive
))
1440 (defun calc-same-interface (arg)
1441 "Invoke the Calculator using the most recent interface (calc or calc-keypad)."
1443 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1444 (> (recursion-depth) 0))
1445 (exit-recursive-edit)
1446 (if (eq major-mode
'calc-edit-mode
)
1447 (calc-edit-finish arg
)
1448 (if calc-was-keypad-mode
1450 (calc arg calc-full-mode t
)))))
1452 (defun calc-quit (&optional non-fatal interactive
)
1453 (interactive "i\np")
1454 (and calc-standalone-flag
(not non-fatal
)
1455 (save-buffers-kill-emacs nil
))
1456 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1457 (> (recursion-depth) 0))
1458 (exit-recursive-edit))
1459 (if (eq major-mode
'calc-edit-mode
)
1461 (if (and interactive
1463 (eq (current-buffer) (aref calc-embedded-info
0)))
1465 (unless (eq major-mode
'calc-mode
)
1466 (calc-create-buffer))
1467 (run-hooks 'calc-end-hook
)
1468 (setq calc-undo-list nil calc-redo-list nil
)
1469 (mapc (function (lambda (v) (set-default v
(symbol-value v
))))
1470 calc-local-var-list
)
1471 (let ((buf (current-buffer))
1472 (win (get-buffer-window (current-buffer)))
1473 (kbuf (get-buffer "*Calc Keypad*")))
1474 (delete-windows-on (calc-trail-buffer))
1476 (< (window-height win
) (1- (frame-height)))
1477 (= (window-width win
) (frame-width)) ; avoid calc-keypad
1478 (not (get-buffer-window "*Calc Keypad*")))
1479 (setq calc-window-height
(- (window-height win
) 2)))
1481 (delete-windows-on buf
)
1482 (delete-windows-on kbuf
))
1484 (bury-buffer calc-trail-buffer
)
1485 (and kbuf
(bury-buffer kbuf
))))))
1488 (defun quick-calc ()
1489 "Do a quick calculation in the minibuffer without invoking full Calculator."
1491 (calc-do-quick-calc))
1494 (defun calc-eval (str &optional separator
&rest args
)
1495 "Do a quick calculation and return the result as a string.
1496 Return value will either be the formatted result in string form,
1497 or a list containing a character position and an error message in string form."
1498 (calc-do-calc-eval str separator args
))
1501 (defun calc-keypad (&optional interactive
)
1502 "Invoke the Calculator in \"visual keypad\" mode.
1503 This is most useful in the X window system.
1504 In this mode, click on the Calc \"buttons\" using the left mouse button.
1505 Or, position the cursor manually and do M-x calc-keypad-press."
1508 (calc-do-keypad calc-full-mode interactive
))
1511 (defun full-calc-keypad (&optional interactive
)
1512 "Invoke the Calculator in full-screen \"visual keypad\" mode.
1513 See calc-keypad for details."
1516 (calc-do-keypad t interactive
))
1519 (defvar calc-aborted-prefix nil
)
1520 (defvar calc-start-time nil
)
1521 (defvar calc-command-flags
)
1522 (defvar calc-final-point-line
)
1523 (defvar calc-final-point-column
)
1524 ;;; Note that modifications to this function may break calc-pass-errors.
1525 (defun calc-do (do-body &optional do-slow
)
1526 (calc-check-defines)
1527 (let* ((calc-command-flags nil
)
1528 (calc-start-time (and calc-timing
(not calc-start-time
)
1530 (current-time-string)))
1531 (gc-cons-threshold (max gc-cons-threshold
1532 (if calc-timing
2000000 100000)))
1533 calc-final-point-line calc-final-point-column
)
1534 (setq calc-aborted-prefix
"")
1538 (if calc-embedded-info
1539 (calc-embedded-select-buffer)
1540 (calc-select-buffer))
1541 (and (eq calc-algebraic-mode
'total
)
1543 (use-local-map calc-alg-map
))
1544 (when (and do-slow calc-display-working-message
)
1545 (message "Working...")
1546 (calc-set-command-flag 'clear-message
))
1548 (setq calc-aborted-prefix nil
)
1549 (when (memq 'renum-stack calc-command-flags
)
1550 (calc-renumber-stack))
1551 (when (memq 'clear-message calc-command-flags
)
1554 (if (and (eq (car err
) 'error
)
1555 (stringp (nth 1 err
))
1556 (string-match "max-specpdl-size\\|max-lisp-eval-depth"
1558 (error "Computation got stuck or ran too long. Type `M' to increase the limit")
1559 (setq calc-aborted-prefix nil
)
1560 (signal (car err
) (cdr err
)))))
1561 (when calc-aborted-prefix
1562 (calc-record "<Aborted>" calc-aborted-prefix
))
1563 (and calc-start-time
1564 (let* ((calc-internal-prec 12)
1565 (calc-date-format nil
)
1566 (end-time (current-time-string))
1567 (time (if (equal calc-start-time end-time
)
1570 (calcFunc-unixtime (math-parse-date end-time
) 0)
1571 (calcFunc-unixtime (math-parse-date calc-start-time
)
1573 (if (math-lessp 1 time
)
1574 (calc-record time
"(t)"))))
1575 (or (memq 'no-align calc-command-flags
)
1576 (eq major-mode
'calc-trail-mode
)
1577 (calc-align-stack-window))
1578 (and (memq 'position-point calc-command-flags
)
1579 (if (eq major-mode
'calc-mode
)
1581 (goto-line calc-final-point-line
)
1582 (move-to-column calc-final-point-column
))
1583 (save-current-buffer
1584 (calc-select-buffer)
1585 (goto-line calc-final-point-line
)
1586 (move-to-column calc-final-point-column
))))
1587 (unless (memq 'keep-flags calc-command-flags
)
1589 (calc-select-buffer)
1590 (setq calc-inverse-flag nil
1591 calc-hyperbolic-flag nil
1592 calc-keep-args-flag nil
)))
1593 (when (memq 'do-edit calc-command-flags
)
1594 (switch-to-buffer (get-buffer-create "*Calc Edit*")))
1595 (calc-set-mode-line)
1596 (when calc-embedded-info
1597 (calc-embedded-finish-command))))
1598 (identity nil
)) ; allow a GC after timing is done
1601 (defun calc-set-command-flag (f)
1602 (unless (memq f calc-command-flags
)
1603 (setq calc-command-flags
(cons f calc-command-flags
))))
1605 (defun calc-select-buffer ()
1606 (or (eq major-mode
'calc-mode
)
1607 (if calc-main-buffer
1608 (set-buffer calc-main-buffer
)
1609 (let ((buf (get-buffer "*Calculator*")))
1612 (error "Calculator buffer not available"))))))
1614 (defun calc-cursor-stack-index (&optional index
)
1615 (goto-char (point-max))
1616 (forward-line (- (calc-substack-height (or index
1)))))
1618 (defun calc-stack-size ()
1619 (- (length calc-stack
) calc-stack-top
))
1621 (defun calc-substack-height (n)
1624 (setq n
(+ n calc-stack-top
))
1625 (while (and (> n
0) stack
)
1626 (setq sum
(+ sum
(nth 1 (car stack
)))
1631 (defun calc-set-mode-line ()
1633 (calc-select-buffer)
1634 (let* ((fmt (car calc-float-format
))
1635 (figs (nth 1 calc-float-format
))
1637 (format "Calc%s%s: %d %s %-14s"
1638 (if calc-embedded-info
"Embed" "")
1639 (if (and (> (length (buffer-name)) 12)
1640 (equal (substring (buffer-name) 0 12)
1642 (substring (buffer-name) 12)
1645 (capitalize (symbol-name calc-angle-mode
))
1648 ;; Input-related modes
1649 (if (eq calc-algebraic-mode
'total
) "Alg* "
1650 (if calc-algebraic-mode
"Alg "
1651 (if calc-incomplete-algebraic-mode
"Alg[( " "")))
1653 ;; Computational modes
1654 (if calc-symbolic-mode
"Symb " "")
1655 (cond ((eq calc-matrix-mode
'matrix
) "Matrix ")
1656 ((integerp calc-matrix-mode
)
1657 (format "Matrix%d " calc-matrix-mode
))
1658 ((eq calc-matrix-mode
'sqmatrix
) "SqMatrix ")
1659 ((eq calc-matrix-mode
'scalar
) "Scalar ")
1661 (if (eq calc-complex-mode
'polar
) "Polar " "")
1662 (if calc-prefer-frac
"Frac " "")
1663 (cond ((null calc-infinite-mode
) "")
1664 ((eq calc-infinite-mode
1) "+Inf ")
1666 (cond ((eq calc-simplify-mode
'none
) "NoSimp ")
1667 ((eq calc-simplify-mode
'num
) "NumSimp ")
1668 ((eq calc-simplify-mode
'binary
)
1669 (format "BinSimp%d " calc-word-size
))
1670 ((eq calc-simplify-mode
'alg
) "AlgSimp ")
1671 ((eq calc-simplify-mode
'ext
) "ExtSimp ")
1672 ((eq calc-simplify-mode
'units
) "UnitSimp ")
1676 (cond ((= calc-number-radix
10) "")
1677 ((= calc-number-radix
2) "Bin ")
1678 ((= calc-number-radix
8) "Oct ")
1679 ((= calc-number-radix
16) "Hex ")
1680 (t (format "Radix%d " calc-number-radix
)))
1681 (if calc-leading-zeros
"Zero " "")
1682 (cond ((null calc-language
) "")
1683 ((get calc-language
'math-lang-name
)
1684 (concat (get calc-language
'math-lang-name
) " "))
1686 (capitalize (symbol-name calc-language
))
1688 (cond ((eq fmt
'float
)
1689 (if (zerop figs
) "" (format "Norm%d " figs
)))
1690 ((eq fmt
'fix
) (format "Fix%d " figs
))
1692 (if (zerop figs
) "Sci " (format "Sci%d " figs
)))
1694 (if (zerop figs
) "Eng " (format "Eng%d " figs
))))
1695 (cond ((not calc-display-just
)
1696 (if calc-display-origin
1697 (format "Left%d " calc-display-origin
) ""))
1698 ((eq calc-display-just
'right
)
1699 (if calc-display-origin
1700 (format "Right%d " calc-display-origin
)
1703 (if calc-display-origin
1704 (format "Center%d " calc-display-origin
)
1706 (cond ((integerp calc-line-breaking
)
1707 (format "Wid%d " calc-line-breaking
))
1708 (calc-line-breaking "")
1711 ;; Miscellaneous other modes/indicators
1712 (if calc-assoc-selections
"" "Break ")
1713 (cond ((eq calc-mode-save-mode
'save
) "Save ")
1714 ((not calc-embedded-info
) "")
1715 ((eq calc-mode-save-mode
'local
) "Local ")
1716 ((eq calc-mode-save-mode
'edit
) "LocEdit ")
1717 ((eq calc-mode-save-mode
'perm
) "LocPerm ")
1718 ((eq calc-mode-save-mode
'global
) "Global ")
1720 (if calc-auto-recompute
"" "Manual ")
1721 (if (and (fboundp 'calc-gnuplot-alive
)
1722 (calc-gnuplot-alive)) "Graph " "")
1723 (if (and calc-embedded-info
1724 (> (calc-stack-size) 0)
1725 (calc-top 1 'sel
)) "Sel " "")
1726 (if calc-display-dirty
"Dirty " "")
1727 (if calc-inverse-flag
"Inv " "")
1728 (if calc-hyperbolic-flag
"Hyp " "")
1729 (if calc-keep-args-flag
"Keep " "")
1730 (if (/= calc-stack-top
1) "Narrow " "")
1731 (apply 'concat calc-other-modes
)))))
1732 (if (equal new-mode-string mode-line-buffer-identification
)
1734 (setq mode-line-buffer-identification new-mode-string
)
1735 (set-buffer-modified-p (buffer-modified-p))
1736 (and calc-embedded-info
(calc-embedded-mode-line-change))))))
1738 (defun calc-align-stack-window ()
1739 (if (eq major-mode
'calc-mode
)
1741 (let ((win (get-buffer-window (current-buffer))))
1744 (calc-cursor-stack-index 0)
1745 (vertical-motion (- 2 (window-height win
)))
1746 (set-window-start win
(point)))))
1747 (calc-cursor-stack-index 0)
1748 (if (looking-at " *\\.$")
1749 (goto-char (1- (match-end 0)))))
1751 (calc-select-buffer)
1752 (calc-align-stack-window))))
1754 (defun calc-check-stack (n)
1755 (if (> n
(calc-stack-size))
1756 (error "Too few elements on stack"))
1758 (error "Invalid argument")))
1760 (defun calc-push-list (vals &optional m sels
)
1762 (if calc-executing-macro
1763 (calc-push-list-in-macro vals m sels
)
1765 (calc-select-buffer)
1766 (let* ((val (car vals
))
1767 (entry (list val
1 (car sels
)))
1768 (mm (+ (or m
1) calc-stack-top
)))
1769 (calc-cursor-stack-index (1- (or m
1)))
1771 (setcdr (nthcdr (- mm
2) calc-stack
)
1772 (cons entry
(nthcdr (1- mm
) calc-stack
)))
1773 (setq calc-stack
(cons entry calc-stack
)))
1774 (let ((buffer-read-only nil
))
1775 (insert (math-format-stack-value entry
) "\n"))
1776 (calc-record-undo (list 'push mm
))
1777 (calc-set-command-flag 'renum-stack
))))
1778 (setq vals
(cdr vals
)
1781 (defun calc-pop-push-list (n vals
&optional m sels
)
1782 (if (and calc-any-selections
(null sels
))
1783 (calc-replace-selections n vals m
)
1784 (calc-pop-stack n m sels
)
1785 (calc-push-list vals m sels
)))
1787 (defun calc-pop-push-record-list (n prefix vals
&optional m sels
)
1788 (or (and (consp vals
)
1789 (or (integerp (car vals
))
1790 (consp (car vals
))))
1791 (and vals
(setq vals
(list vals
)
1792 sels
(and sels
(list sels
)))))
1793 (calc-check-stack (+ n
(or m
1) -
1))
1796 (calc-record-list vals prefix
)
1797 (calc-record (car vals
) prefix
)))
1798 (calc-pop-push-list n vals m sels
))
1800 (defun calc-enter-result (n prefix vals
&optional m
)
1801 (setq calc-aborted-prefix prefix
)
1802 (if (and (consp vals
)
1803 (or (integerp (car vals
))
1804 (consp (car vals
))))
1805 (setq vals
(mapcar 'calc-normalize vals
))
1806 (setq vals
(calc-normalize vals
)))
1807 (or (and (consp vals
)
1808 (or (integerp (car vals
))
1809 (consp (car vals
))))
1810 (setq vals
(list vals
)))
1811 (if (equal vals
'((nil)))
1813 (calc-pop-push-record-list n prefix vals m
)
1816 (defun calc-normalize (val)
1817 (if (memq calc-simplify-mode
'(nil none num
))
1818 (math-normalize val
)
1820 (calc-normalize-fancy val
)))
1822 (defun calc-handle-whys ()
1824 (calc-do-handle-whys)))
1827 (defun calc-pop-stack (&optional n m sel-ok
) ; pop N objs at level M of stack.
1830 (or calc-keep-args-flag
1831 (let ((mm (+ m calc-stack-top
)))
1832 (if (and calc-any-selections
(not sel-ok
)
1833 (calc-top-selected n m
))
1835 (if calc-executing-macro
1836 (calc-pop-stack-in-macro n mm
)
1837 (calc-record-undo (list 'pop mm
(calc-top-list n m
'full
)))
1839 (calc-select-buffer)
1840 (let ((buffer-read-only nil
))
1843 (calc-cursor-stack-index (1- m
))
1844 (let ((bot (point)))
1845 (calc-cursor-stack-index (+ n m -
1))
1846 (delete-region (point) bot
))
1847 (setcdr (nthcdr (- mm
2) calc-stack
)
1848 (nthcdr (+ n mm -
1) calc-stack
)))
1849 (calc-cursor-stack-index n
)
1850 (setq calc-stack
(nthcdr n calc-stack
))
1851 (delete-region (point) (point-max))))
1852 (calc-set-command-flag 'renum-stack
))))))
1855 (defun calc-get-stack-element (x)
1856 (cond ((eq sel-mode
'entry
)
1860 ((or (null (nth 2 x
))
1862 (not calc-use-selections
))
1868 ;; Get the Nth element of the stack (N=1 is the top element).
1869 (defun calc-top (&optional n sel-mode
)
1871 (calc-check-stack n
)
1872 (calc-get-stack-element (nth (+ n calc-stack-top -
1) calc-stack
)))
1874 (defun calc-top-n (&optional n sel-mode
) ; in case precision has changed
1875 (math-check-complete (calc-normalize (calc-top n sel-mode
))))
1877 (defun calc-top-list (&optional n m sel-mode
)
1880 (calc-check-stack (+ n m -
1))
1882 (let ((top (copy-sequence (nthcdr (+ m calc-stack-top -
1)
1884 (setcdr (nthcdr (1- n
) top
) nil
)
1885 (nreverse (mapcar 'calc-get-stack-element top
)))))
1887 (defun calc-top-list-n (&optional n m sel-mode
)
1888 (mapcar 'math-check-complete
1889 (mapcar 'calc-normalize
(calc-top-list n m sel-mode
))))
1892 (defun calc-renumber-stack ()
1893 (if calc-line-numbering
1895 (calc-cursor-stack-index 0)
1897 (buffer-read-only nil
)
1898 (stack (nthcdr calc-stack-top calc-stack
)))
1899 (if (re-search-forward "^[0-9]+[:*]" nil t
)
1902 (while (re-search-forward "^[0-9]+[:*]" nil t
)
1903 (let ((buffer-read-only nil
))
1907 (calc-cursor-stack-index 0)))
1908 (while (re-search-backward "^[0-9]+[:*]" nil t
)
1911 (insert (format "%03d%s" (% lnum
1000)
1912 (if (and (nth 2 (car stack
))
1913 calc-use-selections
) "*" ":")))
1914 (let ((prefix (int-to-string lnum
)))
1915 (insert prefix
(if (and (nth 2 (car stack
))
1916 calc-use-selections
) "*" ":")
1917 (make-string (- 3 (length prefix
)) 32))))
1919 (setq lnum
(1+ lnum
)
1920 stack
(cdr stack
))))))
1921 (and calc-embedded-info
(calc-embedded-stack-change)))
1923 (defvar calc-any-evaltos nil
)
1924 (defun calc-refresh (&optional align
)
1926 (and (eq major-mode
'calc-mode
)
1927 (not calc-executing-macro
)
1928 (let* ((buffer-read-only nil
)
1929 (save-point (point))
1930 (save-mark (condition-case err
(mark) (error nil
)))
1931 (save-aligned (looking-at "\\.$"))
1933 (calc-any-evaltos nil
))
1934 (setq calc-any-selections nil
)
1936 (when calc-show-banner
1937 (insert (propertize "--- Emacs Calculator Mode ---\n"
1938 'font-lock-face
'italic
)))
1940 (goto-char (point-min))
1941 (when calc-show-banner
1943 (insert (math-format-stack-value (car thing
)) "\n")
1944 (setq thing
(cdr thing
)))
1945 (calc-renumber-stack)
1946 (if calc-display-dirty
1947 (calc-wrapper (setq calc-display-dirty nil
)))
1948 (and calc-any-evaltos calc-auto-recompute
1949 (calc-wrapper (calc-refresh-evaltos)))
1950 (if (or align save-aligned
)
1951 (calc-align-stack-window)
1952 (goto-char save-point
))
1953 (if save-mark
(set-mark save-mark
))))
1954 (and calc-embedded-info
(not (eq major-mode
'calc-mode
))
1956 (set-buffer (aref calc-embedded-info
1))
1957 (calc-refresh align
)))
1958 (setq calc-refresh-count
(1+ calc-refresh-count
)))
1960 ;;;; The Calc Trail buffer.
1962 (defun calc-check-trail-aligned ()
1964 (let ((win (get-buffer-window (current-buffer))))
1966 (pos-visible-in-window-p (1- (point-max)) win
)))))
1968 (defun calc-trail-buffer ()
1969 (and (or (null calc-trail-buffer
)
1970 (null (buffer-name calc-trail-buffer
)))
1972 (setq calc-trail-buffer
(get-buffer-create "*Calc Trail*"))
1973 (let ((buf (or (and (not (eq major-mode
'calc-mode
))
1974 (get-buffer "*Calculator*"))
1976 (set-buffer calc-trail-buffer
)
1977 (or (eq major-mode
'calc-trail-mode
)
1978 (calc-trail-mode buf
)))))
1979 (or (and calc-trail-pointer
1980 (eq (marker-buffer calc-trail-pointer
) calc-trail-buffer
))
1982 (set-buffer calc-trail-buffer
)
1984 (setq calc-trail-pointer
(point-marker))))
1987 (defun calc-record (val &optional prefix
)
1988 (setq calc-aborted-prefix nil
)
1989 (or calc-executing-macro
1990 (let* ((mainbuf (current-buffer))
1991 (buf (calc-trail-buffer))
1992 (calc-display-raw nil
)
1993 (calc-can-abbrev-vectors t
)
1997 (math-showing-full-precision
1998 (math-format-flat-expr val
0)))
2002 (let ((aligned (calc-check-trail-aligned))
2003 (buffer-read-only nil
))
2004 (goto-char (point-max))
2005 (cond ((null prefix
) (insert " "))
2006 ((and (> (length prefix
) 4)
2007 (string-match " " prefix
4))
2008 (insert (substring prefix
0 4) " "))
2009 (t (insert (format "%4s " prefix
))))
2011 (let ((win (get-buffer-window buf
)))
2012 (if (and aligned win
(not (memq 'hold-trail calc-command-flags
)))
2014 (goto-char (1- (point-max))))))))
2018 (defun calc-trail-display (flag &optional no-refresh interactive
)
2019 (interactive "P\ni\np")
2020 (let ((win (get-buffer-window (calc-trail-buffer))))
2021 (if (setq calc-display-trail
2022 (not (if flag
(memq flag
'(nil 0)) win
)))
2025 (if calc-trail-window-hook
2026 (run-hooks 'calc-trail-window-hook
)
2027 (let ((w (split-window nil
(/ (* (window-width) 2) 3) t
)))
2028 (set-window-buffer w calc-trail-buffer
)))
2030 (setq overlay-arrow-string calc-trail-overlay
2031 overlay-arrow-position calc-trail-pointer
)
2043 (calc-refresh))))))))
2046 (defun calc-trail-here ()
2048 (if (eq major-mode
'calc-trail-mode
)
2055 (if (or (bobp) (eobp))
2056 (setq overlay-arrow-position nil
) ; trail is empty
2057 (set-marker calc-trail-pointer
(point) (current-buffer))
2058 (setq calc-trail-overlay
(concat (buffer-substring (point)
2061 overlay-arrow-string calc-trail-overlay
2062 overlay-arrow-position calc-trail-pointer
)
2064 (let ((win (get-buffer-window (current-buffer))))
2067 (forward-line (/ (window-height win
) 2))
2068 (forward-line (- 1 (window-height win
)))
2069 (set-window-start win
(point))
2070 (set-window-point win
(+ calc-trail-pointer
4))
2071 (set-buffer calc-main-buffer
)
2072 (setq overlay-arrow-string calc-trail-overlay
2073 overlay-arrow-position calc-trail-pointer
))))))
2074 (error "Not in Calc Trail buffer")))
2081 (defun calc-record-undo (rec)
2082 (or calc-executing-macro
2083 (if (memq 'undo calc-command-flags
)
2084 (setq calc-undo-list
(cons (cons rec
(car calc-undo-list
))
2085 (cdr calc-undo-list
)))
2086 (setq calc-undo-list
(cons (list rec
) calc-undo-list
)
2088 (calc-set-command-flag 'undo
))))
2093 ;;; Arithmetic commands.
2095 (defun calc-binary-op (name func arg
&optional ident unary func2
)
2096 (setq calc-aborted-prefix name
)
2098 (calc-enter-result 2 name
(cons (or func2 func
)
2099 (mapcar 'math-check-complete
2100 (calc-top-list 2))))
2102 (calc-binary-op-fancy name func arg ident unary
)))
2104 (defun calc-unary-op (name func arg
&optional func2
)
2105 (setq calc-aborted-prefix name
)
2107 (calc-enter-result 1 name
(list (or func2 func
)
2108 (math-check-complete (calc-top 1))))
2110 (calc-unary-op-fancy name func arg
)))
2113 (defun calc-plus (arg)
2116 (calc-binary-op "+" 'calcFunc-add arg
0 nil
'+)))
2118 (defun calc-minus (arg)
2121 (calc-binary-op "-" 'calcFunc-sub arg
0 'neg
'-
)))
2123 (defun calc-times (arg)
2126 (calc-binary-op "*" 'calcFunc-mul arg
1 nil
'*)))
2128 (defun calc-divide (arg)
2131 (calc-binary-op "/" 'calcFunc-div arg
0 'calcFunc-inv
'/)))
2133 (defun calc-left-divide (arg)
2136 (calc-binary-op "ldiv" 'calcFunc-ldiv arg
0 nil nil
)))
2138 (defun calc-change-sign (arg)
2141 (calc-unary-op "chs" 'neg arg
)))
2145 ;;; Stack management commands.
2147 (defun calc-enter (n)
2151 (calc-push-list (calc-top-list 1 (- n
))))
2153 (calc-push-list (calc-top-list (calc-stack-size))))
2155 (calc-push-list (calc-top-list n
))))))
2161 (let* ((nn (prefix-numeric-value n
))
2162 (top (and (null n
) (calc-top 1))))
2163 (cond ((and (null n
)
2164 (eq (car-safe top
) 'incomplete
)
2165 (> (length top
) (if (eq (nth 1 top
) 'intv
) 3 2)))
2166 (calc-pop-push-list 1 (let ((tt (copy-sequence top
)))
2167 (setcdr (nthcdr (- (length tt
) 2) tt
) nil
)
2170 (if (and calc-any-selections
2171 (calc-top-selected 1 (- nn
)))
2172 (calc-delete-selection (- nn
))
2173 (calc-pop-stack 1 (- nn
) t
)))
2175 (calc-pop-stack (calc-stack-size) 1 t
))
2177 (if (and calc-any-selections
2179 (calc-top-selected 1 1))
2180 (calc-delete-selection 1)
2181 (calc-pop-stack nn
)))))))
2186 ;;;; Reading a number using the minibuffer.
2187 (defvar calc-buffer
)
2188 (defvar calc-prev-char
)
2189 (defvar calc-prev-prev-char
)
2190 (defvar calc-digit-value
)
2191 (defun calcDigit-start ()
2194 (if (or calc-algebraic-mode
2195 (and (> calc-number-radix
14) (eq last-command-char ?e
)))
2196 (calc-alg-digit-entry)
2197 (calc-unread-command)
2198 (setq calc-aborted-prefix nil
)
2199 (let* ((calc-digit-value nil
)
2200 (calc-prev-char nil
)
2201 (calc-prev-prev-char nil
)
2202 (calc-buffer (current-buffer))
2203 (buf (if (featurep 'xemacs
)
2205 (catch 'execute-kbd-macro
2207 (read-from-minibuffer
2208 "Calc: " "" calc-digit-map
)))
2209 (error "XEmacs requires RET after %s"
2210 "digit entry in kbd macro"))
2211 (let ((old-esc (lookup-key global-map
"\e")))
2214 (define-key global-map
"\e" nil
)
2215 (read-from-minibuffer "Calc: " "" calc-digit-map
))
2216 (define-key global-map
"\e" old-esc
))))))
2217 (or calc-digit-value
(setq calc-digit-value
(math-read-number buf
)))
2218 (if (stringp calc-digit-value
)
2219 (calc-alg-entry calc-digit-value
)
2220 (if calc-digit-value
2221 (calc-push-list (list (calc-record (calc-normalize
2222 calc-digit-value
))))))
2223 (if (eq calc-prev-char
'dots
)
2228 (defsubst calc-minibuffer-size
()
2229 (- (point-max) (minibuffer-prompt-end)))
2231 (defun calcDigit-nondigit ()
2233 ;; Exercise for the reader: Figure out why this is a good precaution!
2234 (or (boundp 'calc-buffer
)
2235 (use-local-map minibuffer-local-map
))
2236 (let ((str (minibuffer-contents)))
2237 (setq calc-digit-value
(save-excursion
2238 (set-buffer calc-buffer
)
2239 (math-read-number str
))))
2240 (if (and (null calc-digit-value
) (> (calc-minibuffer-size) 0))
2243 (calc-temp-minibuffer-message " [Bad format]"))
2244 (or (memq last-command-char
'(32 13))
2245 (progn (setq prefix-arg current-prefix-arg
)
2246 (calc-unread-command (if (and (eq last-command-char
27)
2247 (>= last-input-char
128))
2253 (defun calc-minibuffer-contains (rex)
2255 (goto-char (minibuffer-prompt-end))
2258 (defun calcDigit-key ()
2260 (goto-char (point-max))
2261 (if (or (and (memq last-command-char
'(?
+ ?-
))
2263 (/= (preceding-char) ?e
))
2264 (and (memq last-command-char
'(?m ?s
))
2265 (not (calc-minibuffer-contains "[-+]?[0-9]+\\.?0*[@oh].*"))
2266 (not (calc-minibuffer-contains "[-+]?\\(1[1-9]\\|[2-9][0-9]\\)#.*"))))
2267 (calcDigit-nondigit)
2268 (if (calc-minibuffer-contains "\\([-+]?\\|.* \\)\\'")
2269 (cond ((memq last-command-char
'(?. ?
@)) (insert "0"))
2270 ((and (memq last-command-char
'(?o ?h ?m
))
2271 (not (calc-minibuffer-contains ".*#.*"))) (insert "0"))
2272 ((memq last-command-char
'(?
: ?e
)) (insert "1"))
2273 ((eq last-command-char ?
#)
2274 (insert (int-to-string calc-number-radix
)))))
2275 (if (and (calc-minibuffer-contains "\\([-+]?[0-9]+#\\|[^:]*:\\)\\'")
2276 (eq last-command-char ?
:))
2278 (if (and (calc-minibuffer-contains "[-+]?[0-9]+#\\'")
2279 (eq last-command-char ?.
))
2281 (if (and (calc-minibuffer-contains "[-+]?0*\\([2-9]\\|1[0-4]\\)#\\'")
2282 (eq last-command-char ?e
))
2284 (if (or (and (memq last-command-char
'(?h ?o ?m ?s ?p
))
2285 (calc-minibuffer-contains ".*#.*"))
2286 (and (eq last-command-char ?e
)
2287 (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2288 (and (eq last-command-char ?n
)
2289 (calc-minibuffer-contains "[-+]?\\(2[4-9]\\|[3-9][0-9]\\)#.*")))
2290 (setq last-command-char
(upcase last-command-char
)))
2292 ((memq last-command-char
'(?_ ?n
))
2293 (goto-char (minibuffer-prompt-end))
2294 (if (and (search-forward " +/- " nil t
)
2295 (not (search-forward "e" nil t
)))
2297 (and (not (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2298 (search-forward "e" nil t
))
2299 (if (looking-at "+")
2301 (if (looking-at "-")
2304 (goto-char (point-max)))
2305 ((eq last-command-char ?p
)
2306 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2307 (calc-minibuffer-contains ".*mod.*")
2308 (calc-minibuffer-contains ".*#.*")
2309 (calc-minibuffer-contains ".*[-+e:]\\'"))
2311 (if (not (calc-minibuffer-contains ".* \\'"))
2314 ((and (eq last-command-char ?M
)
2315 (not (calc-minibuffer-contains
2316 "[-+]?\\(2[3-9]\\|[3-9][0-9]\\)#.*")))
2317 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2318 (calc-minibuffer-contains ".*mod *[^ ]+")
2319 (calc-minibuffer-contains ".*[-+e:]\\'"))
2321 (if (calc-minibuffer-contains ".*mod \\'")
2322 (if calc-previous-modulo
2323 (insert (math-format-flat-expr calc-previous-modulo
0))
2325 (if (not (calc-minibuffer-contains ".* \\'"))
2329 (insert (char-to-string last-command-char
))
2330 (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]*\\)?\\)?\\'")
2331 (let ((radix (string-to-number
2333 (match-beginning 2) (match-end 2)))))
2336 (or (memq last-command-char
'(?
# ?
: ?. ?e ?
+ ?-
))
2337 (let ((dig (math-read-radix-digit
2338 (upcase last-command-char
))))
2341 (calc-minibuffer-contains
2342 "[-+]?\\(.*\\+/- *\\|.*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]?\\'"))
2343 (if (and (memq last-command-char
'(?
@ ?o ?h ?
\' ?m
))
2344 (string-match " " calc-hms-format
))
2346 (if (and (eq this-command last-command
)
2347 (eq last-command-char ?.
))
2351 (delete-backward-char 1)
2353 (calc-temp-minibuffer-message " [Bad format]"))))))
2354 (setq calc-prev-prev-char calc-prev-char
2355 calc-prev-char last-command-char
))
2358 (defun calcDigit-backspace ()
2360 (goto-char (point-max))
2361 (cond ((calc-minibuffer-contains ".* \\+/- \\'")
2362 (backward-delete-char 5))
2363 ((calc-minibuffer-contains ".* mod \\'")
2364 (backward-delete-char 5))
2365 ((calc-minibuffer-contains ".* \\'")
2366 (backward-delete-char 2))
2367 ((eq last-command
'calcDigit-start
)
2369 (t (backward-delete-char 1)))
2370 (if (= (calc-minibuffer-size) 0)
2372 (setq last-command-char
13)
2373 (calcDigit-nondigit))))
2378 (defconst math-bignum-digit-length
2379 (truncate (/ (log10 (/ most-positive-fixnum
2)) 2))
2380 "The length of a \"digit\" in Calc bignums.
2381 If a big integer is of the form (bigpos N0 N1 ...), this is the
2382 length of the allowable Emacs integers N0, N1,...
2383 The value of 2*10^(2*MATH-BIGNUM-DIGIT-LENGTH) must be less than the
2384 largest Emacs integer.")
2386 (defconst math-bignum-digit-size
2387 (expt 10 math-bignum-digit-length
)
2388 "An upper bound for the size of the \"digit\"s in Calc bignums.")
2390 (defconst math-small-integer-size
2391 (expt math-bignum-digit-size
2)
2392 "An upper bound for the size of \"small integer\"s in Calc.")
2395 ;;;; Arithmetic routines.
2397 ;;; An object as manipulated by one of these routines may take any of the
2398 ;;; following forms:
2400 ;;; integer An integer. For normalized numbers, this format
2401 ;;; is used only for
2402 ;;; negative math-small-integer-size + 1 to
2403 ;;; math-small-integer-size - 1
2405 ;;; (bigpos N0 N1 N2 ...) A big positive integer,
2406 ;;; N0 + N1*math-bignum-digit-size
2407 ;;; + N2*(math-bignum-digit-size)^2 ...
2408 ;;; (bigneg N0 N1 N2 ...) A big negative integer,
2409 ;;; - N0 - N1*math-bignum-digit-size ...
2410 ;;; Each digit N is in the range
2411 ;;; 0 ... math-bignum-digit-size -1.
2412 ;;; Normalized, always at least three N present,
2413 ;;; and the most significant N is nonzero.
2415 ;;; (frac NUM DEN) A fraction. NUM and DEN are small or big integers.
2416 ;;; Normalized, DEN > 1.
2418 ;;; (float NUM EXP) A floating-point number, NUM * 10^EXP;
2419 ;;; NUM is a small or big integer, EXP is a small int.
2420 ;;; Normalized, NUM is not a multiple of 10, and
2421 ;;; abs(NUM) < 10^calc-internal-prec.
2422 ;;; Normalized zero is stored as (float 0 0).
2424 ;;; (cplx REAL IMAG) A complex number; REAL and IMAG are any of above.
2425 ;;; Normalized, IMAG is nonzero.
2427 ;;; (polar R THETA) Polar complex number. Normalized, R > 0 and THETA
2428 ;;; is neither zero nor 180 degrees (pi radians).
2430 ;;; (vec A B C ...) Vector of objects A, B, C, ... A matrix is a
2431 ;;; vector of vectors.
2433 ;;; (hms H M S) Angle in hours-minutes-seconds form. All three
2434 ;;; components have the same sign; H and M must be
2435 ;;; numerically integers; M and S are expected to
2436 ;;; lie in the range [0,60).
2438 ;;; (date N) A date or date/time object. N is an integer to
2439 ;;; store a date only, or a fraction or float to
2440 ;;; store a date and time.
2442 ;;; (sdev X SIGMA) Error form, X +/- SIGMA. When normalized,
2443 ;;; SIGMA > 0. X is any complex number and SIGMA
2444 ;;; is real numbers; or these may be symbolic
2445 ;;; expressions where SIGMA is assumed real.
2447 ;;; (intv MASK LO HI) Interval form. MASK is 0=(), 1=(], 2=[), or 3=[].
2448 ;;; LO and HI are any real numbers, or symbolic
2449 ;;; expressions which are assumed real, and LO < HI.
2450 ;;; For [LO..HI], if LO = HI normalization produces LO,
2451 ;;; and if LO > HI normalization produces [LO..LO).
2452 ;;; For other intervals, if LO > HI normalization
2453 ;;; sets HI equal to LO.
2455 ;;; (mod N M) Number modulo M. When normalized, 0 <= N < M.
2456 ;;; N and M are real numbers.
2458 ;;; (var V S) Symbolic variable. V is a Lisp symbol which
2459 ;;; represents the variable's visible name. S is
2460 ;;; the symbol which actually stores the variable's
2461 ;;; value: (var pi var-pi).
2463 ;;; In general, combining rational numbers in a calculation always produces
2464 ;;; a rational result, but if either argument is a float, result is a float.
2466 ;;; In the following comments, [x y z] means result is x, args must be y, z,
2467 ;;; respectively, where the code letters are:
2469 ;;; O Normalized object (vector or number)
2470 ;;; V Normalized vector
2471 ;;; N Normalized number of any type
2472 ;;; N Normalized complex number
2473 ;;; R Normalized real number (float or rational)
2474 ;;; F Normalized floating-point number
2475 ;;; T Normalized rational number
2476 ;;; I Normalized integer
2477 ;;; B Normalized big integer
2478 ;;; S Normalized small integer
2479 ;;; D Digit (small integer, 0..999)
2480 ;;; L Normalized bignum digit list (without "bigpos" or "bigneg" symbol)
2481 ;;; or normalized vector element list (without "vec")
2482 ;;; P Predicate (truth value)
2483 ;;; X Any Lisp object
2486 ;;; Lower-case letters signify possibly un-normalized values.
2487 ;;; "L.D" means a cons of an L and a D.
2488 ;;; [N N; n n] means result will be normalized if argument is.
2489 ;;; Also, [Public] marks routines intended to be called from outside.
2490 ;;; [This notation has been neglected in many recent routines.]
2492 (defvar math-eval-rules-cache
)
2493 (defvar math-eval-rules-cache-other
)
2494 ;;; Reduce an object to canonical (normalized) form. [O o; Z Z] [Public]
2496 (defvar math-normalize-a
)
2497 (defun math-normalize (math-normalize-a)
2499 ((not (consp math-normalize-a
))
2500 (if (integerp math-normalize-a
)
2501 (if (or (>= math-normalize-a math-small-integer-size
)
2502 (<= math-normalize-a
(- math-small-integer-size
)))
2503 (math-bignum math-normalize-a
)
2506 ((eq (car math-normalize-a
) 'bigpos
)
2507 (if (eq (nth (1- (length math-normalize-a
)) math-normalize-a
) 0)
2508 (let* ((last (setq math-normalize-a
2509 (copy-sequence math-normalize-a
))) (digs math-normalize-a
))
2510 (while (setq digs
(cdr digs
))
2511 (or (eq (car digs
) 0) (setq last digs
)))
2513 (if (cdr (cdr (cdr math-normalize-a
)))
2516 ((cdr (cdr math-normalize-a
)) (+ (nth 1 math-normalize-a
)
2517 (* (nth 2 math-normalize-a
)
2518 math-bignum-digit-size
)))
2519 ((cdr math-normalize-a
) (nth 1 math-normalize-a
))
2521 ((eq (car math-normalize-a
) 'bigneg
)
2522 (if (eq (nth (1- (length math-normalize-a
)) math-normalize-a
) 0)
2523 (let* ((last (setq math-normalize-a
(copy-sequence math-normalize-a
)))
2524 (digs math-normalize-a
))
2525 (while (setq digs
(cdr digs
))
2526 (or (eq (car digs
) 0) (setq last digs
)))
2528 (if (cdr (cdr (cdr math-normalize-a
)))
2531 ((cdr (cdr math-normalize-a
)) (- (+ (nth 1 math-normalize-a
)
2532 (* (nth 2 math-normalize-a
)
2533 math-bignum-digit-size
))))
2534 ((cdr math-normalize-a
) (- (nth 1 math-normalize-a
)))
2536 ((eq (car math-normalize-a
) 'float
)
2537 (math-make-float (math-normalize (nth 1 math-normalize-a
))
2538 (nth 2 math-normalize-a
)))
2539 ((or (memq (car math-normalize-a
)
2540 '(frac cplx polar hms date mod sdev intv vec var quote
2541 special-const calcFunc-if calcFunc-lambda
2542 calcFunc-quote calcFunc-condition
2544 (integerp (car math-normalize-a
))
2545 (and (consp (car math-normalize-a
))
2546 (not (eq (car (car math-normalize-a
)) 'lambda
))))
2548 (math-normalize-fancy math-normalize-a
))
2550 (or (and calc-simplify-mode
2552 (math-normalize-nonstandard))
2553 (let ((args (mapcar 'math-normalize
(cdr math-normalize-a
))))
2554 (or (condition-case err
2556 (assq (car math-normalize-a
) '( ( + . math-add
)
2563 ( | . math-concat
) ))))
2564 (or (and var-EvalRules
2566 (or (eq var-EvalRules math-eval-rules-cache-tag
)
2569 (math-recompile-eval-rules)))
2570 (and (or math-eval-rules-cache-other
2571 (assq (car math-normalize-a
)
2572 math-eval-rules-cache
))
2573 (math-apply-rewrites
2574 (cons (car math-normalize-a
) args
)
2575 (cdr math-eval-rules-cache
)
2576 nil math-eval-rules-cache
))))
2578 (apply (cdr func
) args
)
2579 (and (or (consp (car math-normalize-a
))
2580 (fboundp (car math-normalize-a
))
2581 (and (not (featurep 'calc-ext
))
2583 (fboundp (car math-normalize-a
))))
2584 (apply (car math-normalize-a
) args
)))))
2585 (wrong-number-of-arguments
2586 (calc-record-why "*Wrong number of arguments"
2587 (cons (car math-normalize-a
) args
))
2589 (wrong-type-argument
2591 (calc-record-why "Wrong type of argument"
2592 (cons (car math-normalize-a
) args
)))
2595 (calc-record-why "*Argument out of range"
2596 (cons (car math-normalize-a
) args
))
2599 (calc-record-why "No exact representation for result"
2600 (cons (car math-normalize-a
) args
))
2603 (calc-record-why "*Floating-point overflow occurred"
2604 (cons (car math-normalize-a
) args
))
2607 (calc-record-why "*Floating-point underflow occurred"
2608 (cons (car math-normalize-a
) args
))
2611 (if (eq (nth 1 err
) 'var-EvalRules
)
2613 (setq var-EvalRules nil
)
2614 (math-normalize (cons (car math-normalize-a
) args
)))
2615 (calc-record-why "*Variable is void" (nth 1 err
)))))
2616 (if (consp (car math-normalize-a
))
2617 (math-dimension-error)
2618 (cons (car math-normalize-a
) args
))))))))
2622 ;;; True if A is a floating-point real or complex number. [P x] [Public]
2623 (defun math-floatp (a)
2624 (cond ((eq (car-safe a
) 'float
) t
)
2625 ((memq (car-safe a
) '(cplx polar mod sdev intv
))
2626 (or (math-floatp (nth 1 a
))
2627 (math-floatp (nth 2 a
))
2628 (and (eq (car a
) 'intv
) (math-floatp (nth 3 a
)))))
2629 ((eq (car-safe a
) 'date
)
2630 (math-floatp (nth 1 a
)))))
2634 ;;; Verify that A is a complete object and return A. [x x] [Public]
2635 (defun math-check-complete (a)
2636 (cond ((integerp a
) a
)
2637 ((eq (car-safe a
) 'incomplete
)
2638 (calc-incomplete-error a
))
2640 (t (error "Invalid data object encountered"))))
2644 ;;; Coerce integer A to be a bignum. [B S]
2645 (defun math-bignum (a)
2647 (cons 'bigpos
(math-bignum-big a
))
2648 (cons 'bigneg
(math-bignum-big (- a
)))))
2650 (defun math-bignum-big (a) ; [L s]
2653 (cons (% a math-bignum-digit-size
)
2654 (math-bignum-big (/ a math-bignum-digit-size
)))))
2657 ;;; Build a normalized floating-point number. [F I S]
2658 (defun math-make-float (mant exp
)
2661 (let* ((ldiff (- calc-internal-prec
(math-numdigs mant
))))
2663 (setq mant
(math-scale-rounding mant ldiff
)
2664 exp
(- exp ldiff
))))
2666 (let ((digs (cdr mant
)))
2667 (if (= (%
(car digs
) 10) 0)
2669 (while (= (car digs
) 0)
2670 (setq digs
(cdr digs
)
2671 exp
(+ exp math-bignum-digit-length
)))
2672 (while (= (%
(car digs
) 10) 0)
2673 (setq digs
(math-div10-bignum digs
)
2675 (setq mant
(math-normalize (cons (car mant
) digs
))))))
2676 (while (= (% mant
10) 0)
2677 (setq mant
(/ mant
10)
2679 (if (and (<= exp -
4000000)
2680 (<= (+ exp
(math-numdigs mant
) -
1) -
4000000))
2681 (signal 'math-underflow nil
)
2682 (if (and (>= exp
3000000)
2683 (>= (+ exp
(math-numdigs mant
) -
1) 4000000))
2684 (signal 'math-overflow nil
)
2685 (list 'float mant exp
)))))
2687 (defun math-div10-bignum (a) ; [l l]
2689 (cons (+ (/ (car a
) 10) (* (%
(nth 1 a
) 10)
2690 (expt 10 (1- math-bignum-digit-length
))))
2691 (math-div10-bignum (cdr a
)))
2692 (list (/ (car a
) 10))))
2694 ;;; Coerce A to be a float. [F N; V V] [Public]
2695 (defun math-float (a)
2696 (cond ((Math-integerp a
) (math-make-float a
0))
2697 ((eq (car a
) 'frac
) (math-div (math-float (nth 1 a
)) (nth 2 a
)))
2698 ((eq (car a
) 'float
) a
)
2699 ((memq (car a
) '(cplx polar vec hms date sdev mod
))
2700 (cons (car a
) (mapcar 'math-float
(cdr a
))))
2701 (t (math-float-fancy a
))))
2705 (cond ((not (consp a
)) (- a
))
2706 ((eq (car a
) 'bigpos
) (cons 'bigneg
(cdr a
)))
2707 ((eq (car a
) 'bigneg
) (cons 'bigpos
(cdr a
)))
2708 ((memq (car a
) '(frac float
))
2709 (list (car a
) (Math-integer-neg (nth 1 a
)) (nth 2 a
)))
2710 ((memq (car a
) '(cplx vec hms date calcFunc-idn
))
2711 (cons (car a
) (mapcar 'math-neg
(cdr a
))))
2712 (t (math-neg-fancy a
))))
2715 ;;; Compute the number of decimal digits in integer A. [S I]
2716 (defun math-numdigs (a)
2719 (let* ((len (1- (length a
)))
2721 (+ (* (1- len
) math-bignum-digit-length
) (math-numdigs top
)))
2723 (cond ((>= a
100) (+ (math-numdigs (/ a
1000)) 3))
2729 (t (math-numdigs (- a
))))))
2731 ;;; Multiply (with truncation toward 0) the integer A by 10^N. [I i S]
2732 (defun math-scale-int (a n
)
2734 ((> n
0) (math-scale-left a n
))
2735 (t (math-normalize (math-scale-right a
(- n
))))))
2737 (defun math-scale-left (a n
) ; [I I S]
2741 (cons (car a
) (math-scale-left-bignum (cdr a
) n
))
2742 (if (>= n math-bignum-digit-length
)
2743 (if (or (>= a math-bignum-digit-size
)
2744 (<= a
(- math-bignum-digit-size
)))
2745 (math-scale-left (math-bignum a
) n
)
2746 (math-scale-left (* a math-bignum-digit-size
)
2747 (- n math-bignum-digit-length
)))
2748 (let ((sz (expt 10 (- (* 2 math-bignum-digit-length
) n
))))
2749 (if (or (>= a sz
) (<= a
(- sz
)))
2750 (math-scale-left (math-bignum a
) n
)
2751 (* a
(expt 10 n
))))))))
2753 (defun math-scale-left-bignum (a n
)
2754 (if (>= n math-bignum-digit-length
)
2755 (while (>= (setq a
(cons 0 a
)
2756 n
(- n math-bignum-digit-length
))
2757 math-bignum-digit-length
)))
2759 (math-mul-bignum-digit a
(expt 10 n
) 0)
2762 (defun math-scale-right (a n
) ; [i i S]
2766 (cons (car a
) (math-scale-right-bignum (cdr a
) n
))
2770 (- (math-scale-right (- a
) n
)))
2771 (if (>= n math-bignum-digit-length
)
2772 (while (and (> (setq a
(/ a math-bignum-digit-size
)) 0)
2773 (>= (setq n
(- n math-bignum-digit-length
))
2774 math-bignum-digit-length
))))
2779 (defun math-scale-right-bignum (a n
) ; [L L S; l l S]
2780 (if (>= n math-bignum-digit-length
)
2781 (setq a
(nthcdr (/ n math-bignum-digit-length
) a
)
2782 n
(% n math-bignum-digit-length
)))
2784 (cdr (math-mul-bignum-digit a
(expt 10 (- math-bignum-digit-length n
)) 0))
2787 ;;; Multiply (with rounding) the integer A by 10^N. [I i S]
2788 (defun math-scale-rounding (a n
)
2790 (math-scale-left a n
))
2794 (let ((val (if (< n
(- math-bignum-digit-length
))
2795 (math-scale-right-bignum
2797 (- (- math-bignum-digit-length
) n
))
2799 (math-mul-bignum-digit
2801 (expt 10 (+ math-bignum-digit-length n
)) 0)
2802 (cdr a
))))) ; n = -math-bignum-digit-length
2803 (if (and val
(>= (car val
) (/ math-bignum-digit-size
2)))
2805 (if (eq (car (cdr val
)) (1- math-bignum-digit-size
))
2806 (math-add-bignum (cdr val
) '(1))
2807 (cons (1+ (car (cdr val
))) (cdr (cdr val
))))
2812 (- (math-scale-rounding (- a
) n
))
2815 (/ (+ (math-scale-right a
(- -
1 n
)) 5) 10))))))
2818 ;;; Compute the sum of A and B. [O O O] [Public]
2819 (defun math-add (a b
)
2821 (and (not (or (consp a
) (consp b
)))
2824 (if (or (<= a
(- math-small-integer-size
)) (>= a math-small-integer-size
))
2827 (and (Math-zerop a
) (not (eq (car-safe a
) 'mod
))
2828 (if (and (math-floatp a
) (Math-ratp b
)) (math-float b
) b
))
2829 (and (Math-zerop b
) (not (eq (car-safe b
) 'mod
))
2830 (if (and (math-floatp b
) (Math-ratp a
)) (math-float a
) a
))
2831 (and (Math-objvecp a
) (Math-objvecp b
)
2833 (and (Math-integerp a
) (Math-integerp b
)
2835 (or (consp a
) (setq a
(math-bignum a
)))
2836 (or (consp b
) (setq b
(math-bignum b
)))
2837 (if (eq (car a
) 'bigneg
)
2838 (if (eq (car b
) 'bigneg
)
2839 (cons 'bigneg
(math-add-bignum (cdr a
) (cdr b
)))
2841 (let ((diff (math-sub-bignum (cdr b
) (cdr a
))))
2843 (cons 'bigneg
(math-sub-bignum (cdr a
) (cdr b
)))
2844 (cons 'bigpos diff
)))))
2845 (if (eq (car b
) 'bigneg
)
2847 (let ((diff (math-sub-bignum (cdr a
) (cdr b
))))
2849 (cons 'bigneg
(math-sub-bignum (cdr b
) (cdr a
)))
2850 (cons 'bigpos diff
))))
2851 (cons 'bigpos
(math-add-bignum (cdr a
) (cdr b
)))))))
2852 (and (Math-ratp a
) (Math-ratp b
)
2854 (calc-add-fractions a b
))
2855 (and (Math-realp a
) (Math-realp b
)
2857 (or (and (consp a
) (eq (car a
) 'float
))
2858 (setq a
(math-float a
)))
2859 (or (and (consp b
) (eq (car b
) 'float
))
2860 (setq b
(math-float b
)))
2861 (math-add-float a b
)))
2862 (and (require 'calc-ext
)
2863 (math-add-objects-fancy a b
))))
2864 (and (require 'calc-ext
)
2865 (math-add-symb-fancy a b
))))
2867 (defun math-add-bignum (a b
) ; [L L L; l l l]
2870 (let* ((a (copy-sequence a
)) (aa a
) (carry nil
) sum
)
2873 (if (< (setq sum
(+ (car aa
) (car b
)))
2874 (1- math-bignum-digit-size
))
2876 (setcar aa
(1+ sum
))
2878 (setcar aa
(- sum
(1- math-bignum-digit-size
))))
2879 (if (< (setq sum
(+ (car aa
) (car b
))) math-bignum-digit-size
)
2881 (setcar aa
(- sum math-bignum-digit-size
))
2887 (nconc a
(math-add-bignum b
'(1)))
2888 (while (eq (car aa
) (1- math-bignum-digit-size
))
2893 (setcar aa
(1+ (car aa
)))
2902 (defun math-sub-bignum (a b
) ; [l l l]
2905 (let* ((a (copy-sequence a
)) (aa a
) (borrow nil
) sum diff
)
2908 (if (>= (setq diff
(- (car aa
) (car b
))) 1)
2910 (setcar aa
(1- diff
))
2912 (setcar aa
(+ diff
(1- math-bignum-digit-size
))))
2913 (if (>= (setq diff
(- (car aa
) (car b
))) 0)
2915 (setcar aa
(+ diff math-bignum-digit-size
))
2921 (while (eq (car aa
) 0)
2922 (setcar aa
(1- math-bignum-digit-size
))
2926 (setcar aa
(1- (car aa
)))
2929 (while (eq (car b
) 0)
2934 (while (eq (car b
) 0)
2940 (defun math-add-float (a b
) ; [F F F]
2941 (let ((ediff (- (nth 2 a
) (nth 2 b
))))
2943 (if (>= ediff
(+ calc-internal-prec calc-internal-prec
))
2945 (math-make-float (math-add (nth 1 b
)
2948 (math-scale-left (nth 1 a
) ediff
)))
2950 (if (>= (setq ediff
(- ediff
))
2951 (+ calc-internal-prec calc-internal-prec
))
2953 (math-make-float (math-add (nth 1 a
)
2954 (math-scale-left (nth 1 b
) ediff
))
2957 ;;; Compute the difference of A and B. [O O O] [Public]
2958 (defun math-sub (a b
)
2959 (if (or (consp a
) (consp b
))
2960 (math-add a
(math-neg b
))
2962 (if (or (<= a
(- math-small-integer-size
)) (>= a math-small-integer-size
))
2966 (defun math-sub-float (a b
) ; [F F F]
2967 (let ((ediff (- (nth 2 a
) (nth 2 b
))))
2969 (if (>= ediff
(+ calc-internal-prec calc-internal-prec
))
2971 (math-make-float (math-add (Math-integer-neg (nth 1 b
))
2974 (math-scale-left (nth 1 a
) ediff
)))
2976 (if (>= (setq ediff
(- ediff
))
2977 (+ calc-internal-prec calc-internal-prec
))
2979 (math-make-float (math-add (nth 1 a
)
2981 (math-scale-left (nth 1 b
) ediff
)))
2985 ;;; Compute the product of A and B. [O O O] [Public]
2986 (defun math-mul (a b
)
2988 (and (not (consp a
)) (not (consp b
))
2989 (< a math-bignum-digit-size
) (> a
(- math-bignum-digit-size
))
2990 (< b math-bignum-digit-size
) (> b
(- math-bignum-digit-size
))
2992 (and (Math-zerop a
) (not (eq (car-safe b
) 'mod
))
2993 (if (Math-scalarp b
)
2994 (if (and (math-floatp b
) (Math-ratp a
)) (math-float a
) a
)
2996 (math-mul-zero a b
)))
2997 (and (Math-zerop b
) (not (eq (car-safe a
) 'mod
))
2998 (if (Math-scalarp a
)
2999 (if (and (math-floatp a
) (Math-ratp b
)) (math-float b
) b
)
3001 (math-mul-zero b a
)))
3002 (and (Math-objvecp a
) (Math-objvecp b
)
3004 (and (Math-integerp a
) (Math-integerp b
)
3006 (or (consp a
) (setq a
(math-bignum a
)))
3007 (or (consp b
) (setq b
(math-bignum b
)))
3009 (cons (if (eq (car a
) (car b
)) 'bigpos
'bigneg
)
3012 (math-mul-bignum (cdr a
) (cdr b
))
3013 (math-mul-bignum-digit (cdr a
) (nth 1 b
) 0))
3014 (math-mul-bignum-digit (cdr b
) (nth 1 a
) 0))))))
3015 (and (Math-ratp a
) (Math-ratp b
)
3017 (calc-mul-fractions a b
))
3018 (and (Math-realp a
) (Math-realp b
)
3020 (or (and (consp a
) (eq (car a
) 'float
))
3021 (setq a
(math-float a
)))
3022 (or (and (consp b
) (eq (car b
) 'float
))
3023 (setq b
(math-float b
)))
3024 (math-make-float (math-mul (nth 1 a
) (nth 1 b
))
3025 (+ (nth 2 a
) (nth 2 b
)))))
3026 (and (require 'calc-ext
)
3027 (math-mul-objects-fancy a b
))))
3028 (and (require 'calc-ext
)
3029 (math-mul-symb-fancy a b
))))
3031 (defun math-infinitep (a &optional undir
)
3032 (while (and (consp a
) (memq (car a
) '(* / neg
)))
3033 (if (or (not (eq (car a
) '*)) (math-infinitep (nth 1 a
)))
3035 (setq a
(nth 2 a
))))
3038 (memq (nth 2 a
) '(var-inf var-uinf var-nan
))
3039 (if (and undir
(eq (nth 2 a
) 'var-inf
))
3040 '(var uinf var-uinf
)
3043 ;;; Multiply digit lists A and B. [L L L; l l l]
3044 (defun math-mul-bignum (a b
)
3046 (let* ((sum (if (<= (car b
) 1)
3050 (math-mul-bignum-digit a
(car b
) 0)))
3051 (sump sum
) c d aa ss prod
)
3052 (while (setq b
(cdr b
))
3053 (setq ss
(setq sump
(or (cdr sump
) (setcdr sump
(list 0))))
3058 (setcar ss
(%
(setq prod
(+ (+ (car ss
) (* (car aa
) d
))
3059 c
)) math-bignum-digit-size
))
3061 (setq c
(/ prod math-bignum-digit-size
)
3062 ss
(or (cdr ss
) (setcdr ss
(list 0)))))
3063 (if (>= prod math-bignum-digit-size
)
3065 (setcar (cdr ss
) (+ (/ prod math-bignum-digit-size
) (car (cdr ss
))))
3066 (setcdr ss
(list (/ prod math-bignum-digit-size
))))))
3069 ;;; Multiply digit list A by digit D. [L L D D; l l D D]
3070 (defun math-mul-bignum-digit (a d c
)
3074 (let* ((a (copy-sequence a
)) (aa a
) prod
)
3077 (%
(setq prod
(+ (* (car aa
) d
) c
))
3078 math-bignum-digit-size
))
3081 c
(/ prod math-bignum-digit-size
)))
3082 (if (>= prod math-bignum-digit-size
)
3083 (setcdr aa
(list (/ prod math-bignum-digit-size
))))
3089 ;;; Compute the integer (quotient . remainder) of A and B, which may be
3090 ;;; small or big integers. Type and consistency of truncation is undefined
3091 ;;; if A or B is negative. B must be nonzero. [I.I I I] [Public]
3092 (defun math-idivmod (a b
)
3094 (math-reject-arg a
"*Division by zero"))
3095 (if (or (consp a
) (consp b
))
3096 (if (and (natnump b
) (< b math-bignum-digit-size
))
3097 (let ((res (math-div-bignum-digit (cdr a
) b
)))
3099 (math-normalize (cons (car a
) (car res
)))
3101 (or (consp a
) (setq a
(math-bignum a
)))
3102 (or (consp b
) (setq b
(math-bignum b
)))
3103 (let ((res (math-div-bignum (cdr a
) (cdr b
))))
3105 (math-normalize (cons (if (eq (car a
) (car b
)) 'bigpos
'bigneg
)
3107 (math-normalize (cons (car a
) (cdr res
))))))
3108 (cons (/ a b
) (% a b
))))
3110 (defun math-quotient (a b
) ; [I I I] [Public]
3111 (if (and (not (consp a
)) (not (consp b
)))
3113 (math-reject-arg a
"*Division by zero")
3115 (if (and (natnump b
) (< b math-bignum-digit-size
))
3117 (math-reject-arg a
"*Division by zero")
3118 (math-normalize (cons (car a
)
3119 (car (math-div-bignum-digit (cdr a
) b
)))))
3120 (or (consp a
) (setq a
(math-bignum a
)))
3121 (or (consp b
) (setq b
(math-bignum b
)))
3122 (let* ((alen (1- (length a
)))
3123 (blen (1- (length b
)))
3124 (d (/ math-bignum-digit-size
(1+ (nth (1- blen
) (cdr b
)))))
3125 (res (math-div-bignum-big (math-mul-bignum-digit (cdr a
) d
0)
3126 (math-mul-bignum-digit (cdr b
) d
0)
3128 (math-normalize (cons (if (eq (car a
) (car b
)) 'bigpos
'bigneg
)
3132 ;;; Divide a bignum digit list by another. [l.l l L]
3133 ;;; The following division algorithm is borrowed from Knuth vol. II, sec. 4.3.1
3134 (defun math-div-bignum (a b
)
3136 (let* ((alen (length a
))
3138 (d (/ math-bignum-digit-size
(1+ (nth (1- blen
) b
))))
3139 (res (math-div-bignum-big (math-mul-bignum-digit a d
0)
3140 (math-mul-bignum-digit b d
0)
3145 (car (math-div-bignum-digit (cdr res
) d
)))))
3146 (let ((res (math-div-bignum-digit a
(car b
))))
3147 (cons (car res
) (list (cdr res
))))))
3149 ;;; Divide a bignum digit list by a digit. [l.D l D]
3150 (defun math-div-bignum-digit (a b
)
3152 (let* ((res (math-div-bignum-digit (cdr a
) b
))
3153 (num (+ (* (cdr res
) math-bignum-digit-size
) (car a
))))
3155 (cons (/ num b
) (car res
))
3159 (defun math-div-bignum-big (a b alen blen
) ; [l.l l L]
3162 (let* ((res (math-div-bignum-big (cdr a
) b
(1- alen
) blen
))
3163 (num (cons (car a
) (cdr res
)))
3164 (res2 (math-div-bignum-part num b blen
)))
3166 (cons (car res2
) (car res
))
3169 (defun math-div-bignum-part (a b blen
) ; a < b*math-bignum-digit-size [D.l l L]
3170 (let* ((num (+ (* (or (nth blen a
) 0) math-bignum-digit-size
)
3171 (or (nth (1- blen
) a
) 0)))
3172 (den (nth (1- blen
) b
))
3173 (guess (min (/ num den
) (1- math-bignum-digit-size
))))
3174 (math-div-bignum-try a b
(math-mul-bignum-digit b guess
0) guess
)))
3176 (defun math-div-bignum-try (a b c guess
) ; [D.l l l D]
3177 (let ((rem (math-sub-bignum a c
)))
3179 (math-div-bignum-try a b
(math-sub-bignum c b
) (1- guess
))
3183 ;;; Compute the quotient of A and B. [O O N] [Public]
3184 (defun math-div (a b
)
3188 (math-div-by-zero a b
))
3189 (and (Math-zerop a
) (not (eq (car-safe b
) 'mod
))
3190 (if (Math-scalarp b
)
3191 (if (and (math-floatp b
) (Math-ratp a
)) (math-float a
) a
)
3193 (math-div-zero a b
)))
3194 (and (Math-objvecp a
) (Math-objvecp b
)
3196 (and (Math-integerp a
) (Math-integerp b
)
3197 (let ((q (math-idivmod a b
)))
3200 (if calc-prefer-frac
3203 (math-make-frac a b
))
3204 (math-div-float (math-make-float a
0)
3205 (math-make-float b
0))))))
3206 (and (Math-ratp a
) (Math-ratp b
)
3208 (calc-div-fractions a b
))
3209 (and (Math-realp a
) (Math-realp b
)
3211 (or (and (consp a
) (eq (car a
) 'float
))
3212 (setq a
(math-float a
)))
3213 (or (and (consp b
) (eq (car b
) 'float
))
3214 (setq b
(math-float b
)))
3215 (math-div-float a b
)))
3216 (and (require 'calc-ext
)
3217 (math-div-objects-fancy a b
))))
3218 (and (require 'calc-ext
)
3219 (math-div-symb-fancy a b
))))
3221 (defun math-div-float (a b
) ; [F F F]
3222 (let ((ldiff (max (- (1+ calc-internal-prec
)
3223 (- (math-numdigs (nth 1 a
)) (math-numdigs (nth 1 b
))))
3225 (math-make-float (math-quotient (math-scale-int (nth 1 a
) ldiff
) (nth 1 b
))
3226 (- (- (nth 2 a
) (nth 2 b
)) ldiff
))))
3231 (defvar calc-selection-cache-entry
)
3232 ;;; Format the number A as a string. [X N; X Z] [Public]
3233 (defun math-format-stack-value (entry)
3234 (setq calc-selection-cache-entry calc-selection-cache-default-entry
)
3235 (let* ((a (car entry
))
3236 (math-comp-selected (nth 2 entry
))
3237 (c (cond ((null a
) "<nil>")
3238 ((eq calc-display-raw t
) (format "%s" a
))
3240 ((eq a
'top-of-stack
) (propertize "." 'font-lock-face
'bold
))
3241 (calc-prepared-composition
3242 calc-prepared-composition
)
3243 ((and (Math-scalarp a
)
3244 (memq calc-language
'(nil flat unform
))
3245 (null math-comp-selected
))
3246 (math-format-number a
))
3247 (t (require 'calc-ext
)
3248 (math-compose-expr a
0))))
3249 (off (math-stack-value-offset c
))
3251 (and math-comp-selected
(setq calc-any-selections t
))
3255 (setq c
(math-comp-concat (make-string off ?\s
) c
)))
3256 (or (equal calc-left-label
"")
3257 (setq c
(math-comp-concat (if (eq a
'top-of-stack
)
3258 (make-string (length calc-left-label
) ?\s
)
3261 (when calc-line-numbering
3262 (setq c
(math-comp-concat (if (eq calc-language
'big
)
3263 (if math-comp-selected
3268 (unless (or (equal calc-right-label
"")
3269 (eq a
'top-of-stack
))
3271 (setq c
(list 'horiz c
3272 (make-string (max (- w
(math-comp-width c
)
3273 (length calc-right-label
)) 0) ?\s
)
3276 (setq s
(if (stringp c
)
3277 (if calc-display-raw
3280 (math-composition-to-string c w
)))
3281 (when calc-language-output-filter
3282 (setq s
(funcall calc-language-output-filter s
)))
3283 (if (eq calc-language
'big
)
3284 (setq s
(concat s
"\n"))
3285 (when calc-line-numbering
3286 (setq s
(concat "1:" (substring s
2)))))
3287 (setcar (cdr entry
) (calc-count-lines s
))
3290 ;; The variables math-svo-c, math-svo-wid and math-svo-off are local
3291 ;; to math-stack-value-offset, but are used by math-stack-value-offset-fancy
3294 (defun math-stack-value-offset (math-svo-c)
3295 (let* ((num (if calc-line-numbering
4 0))
3296 (math-svo-wid (calc-window-width))
3298 (if calc-display-just
3301 (math-stack-value-offset-fancy))
3302 (setq math-svo-off
(or calc-display-origin
0))
3303 (when (integerp calc-line-breaking
)
3304 (setq math-svo-wid calc-line-breaking
)))
3305 (cons (max (- math-svo-off
(length calc-left-label
)) 0)
3306 (+ math-svo-wid num
))))
3308 (defun calc-count-lines (s)
3311 (while (setq pos
(string-match "\n" s pos
))
3316 (defun math-format-value (a &optional w
)
3317 (if (and (Math-scalarp a
)
3318 (memq calc-language
'(nil flat unform
)))
3319 (math-format-number a
)
3321 (let ((calc-line-breaking nil
))
3322 (math-composition-to-string (math-compose-expr a
0) w
))))
3324 (defun calc-window-width ()
3325 (if calc-embedded-info
3326 (let ((win (get-buffer-window (aref calc-embedded-info
0))))
3327 (1- (if win
(window-width win
) (frame-width))))
3328 (- (window-width (get-buffer-window (current-buffer)))
3329 (if calc-line-numbering
5 1))))
3331 (defun math-comp-concat (c1 c2
)
3332 (if (and (stringp c1
) (stringp c2
))
3334 (list 'horiz c1 c2
)))
3338 ;;; Format an expression as a one-line string suitable for re-reading.
3340 (defun math-format-flat-expr (a prec
)
3342 ((or (not (or (consp a
) (integerp a
)))
3343 (eq calc-display-raw t
))
3344 (let ((print-escape-newlines t
))
3345 (concat "'" (prin1-to-string a
))))
3347 (let ((calc-group-digits nil
)
3348 (calc-point-char ".")
3349 (calc-frac-format (if (> (length (car calc-frac-format
)) 1)
3350 '("::" nil
) '(":" nil
)))
3351 (calc-complex-format nil
)
3352 (calc-hms-format "%s@ %s' %s\"")
3353 (calc-language nil
))
3354 (math-format-number a
)))
3357 (math-format-flat-expr-fancy a prec
))))
3361 ;;; Format a number as a string.
3362 (defun math-format-number (a &optional prec
) ; [X N] [Public]
3364 ((eq calc-display-raw t
) (format "%s" a
))
3365 ((and (nth 1 calc-frac-format
) (Math-integerp a
))
3367 (math-format-number (math-adjust-fraction a
)))
3369 (if (not (or calc-group-digits calc-leading-zeros
))
3370 (if (= calc-number-radix
10)
3373 (concat "-" (math-format-number (- a
)))
3375 (if math-radix-explicit-format
3376 (if calc-radix-formatter
3377 (funcall calc-radix-formatter
3379 (if (= calc-number-radix
2)
3380 (math-format-binary a
)
3381 (math-format-radix a
)))
3382 (format "%d#%s" calc-number-radix
3383 (if (= calc-number-radix
2)
3384 (math-format-binary a
)
3385 (math-format-radix a
))))
3386 (math-format-radix a
))))
3387 (math-format-number (math-bignum a
))))
3389 ((not (consp a
)) (prin1-to-string a
))
3390 ((eq (car a
) 'bigpos
) (math-format-bignum (cdr a
)))
3391 ((eq (car a
) 'bigneg
) (concat "-" (math-format-bignum (cdr a
))))
3392 ((and (eq (car a
) 'float
) (= calc-number-radix
10))
3393 (if (Math-integer-negp (nth 1 a
))
3394 (concat "-" (math-format-number (math-neg a
)))
3395 (let ((mant (nth 1 a
))
3397 (fmt (car calc-float-format
))
3398 (figs (nth 1 calc-float-format
))
3399 (point calc-point-char
)
3401 (if (and (eq fmt
'fix
)
3402 (or (and (< figs
0) (setq figs
(- figs
)))
3403 (> (+ exp
(math-numdigs mant
)) (- figs
))))
3405 (setq mant
(math-scale-rounding mant
(+ exp figs
))
3406 str
(if (integerp mant
)
3407 (int-to-string mant
)
3408 (math-format-bignum-decimal (cdr mant
))))
3409 (if (<= (length str
) figs
)
3410 (setq str
(concat (make-string (1+ (- figs
(length str
))) ?
0)
3413 (setq str
(concat (substring str
0 (- figs
)) point
3414 (substring str
(- figs
))))
3415 (setq str
(concat str point
)))
3416 (when calc-group-digits
3418 (setq str
(math-group-float str
))))
3420 (setq figs
(+ calc-internal-prec figs
)))
3422 (let ((adj (- figs
(math-numdigs mant
))))
3424 (setq mant
(math-scale-rounding mant adj
)
3426 (setq str
(if (integerp mant
)
3427 (int-to-string mant
)
3428 (math-format-bignum-decimal (cdr mant
))))
3429 (let* ((len (length str
))
3431 (if (and (eq fmt
'float
)
3432 (<= dpos
(+ calc-internal-prec calc-display-sci-high
))
3433 (>= dpos
(+ calc-display-sci-low
2)))
3437 (setq str
(concat "0" point str
)))
3438 ((and (<= exp
0) (> dpos
0))
3439 (setq str
(concat (substring str
0 dpos
) point
3440 (substring str dpos
))))
3442 (setq str
(concat str
(make-string exp ?
0) point
)))
3444 (setq str
(concat "0" point
3445 (make-string (- dpos
) ?
0) str
))))
3446 (when calc-group-digits
3448 (setq str
(math-group-float str
))))
3449 (let* ((eadj (+ exp len
))
3450 (scale (if (eq fmt
'eng
)
3451 (1+ (math-mod (+ eadj
300002) 3))
3453 (if (> scale
(length str
))
3454 (setq str
(concat str
(make-string (- scale
(length str
))
3456 (if (< scale
(length str
))
3457 (setq str
(concat (substring str
0 scale
) point
3458 (substring str scale
))))
3459 (when calc-group-digits
3461 (setq str
(math-group-float str
)))
3462 (setq str
(format (if (memq calc-language
'(math maple
))
3463 (if (and prec
(> prec
191))
3464 "(%s*10.^%d)" "%s*10.^%d")
3466 str
(- eadj scale
)))))))
3470 (math-format-number-fancy a prec
))))
3472 (defun math-format-bignum (a) ; [X L]
3473 (if (and (= calc-number-radix
10)
3474 (not calc-leading-zeros
)
3475 (not calc-group-digits
))
3476 (math-format-bignum-decimal a
)
3478 (math-format-bignum-fancy a
)))
3480 (defun math-format-bignum-decimal (a) ; [X L]
3483 (while (cdr (cdr a
))
3487 (number-to-string (* 2 math-bignum-digit-length
))
3489 (+ (* (nth 1 a
) math-bignum-digit-size
) (car a
))) s
)
3491 (concat (int-to-string
3492 (+ (* (or (nth 1 a
) 0) math-bignum-digit-size
) (car a
))) s
))
3497 ;;; Parse a simple number in string form. [N X] [Public]
3498 (defun math-read-number (s)
3499 "Convert the string S into a Calc number."
3503 ;; Integers (most common case)
3504 ((string-match "\\` *\\([0-9]+\\) *\\'" s
)
3505 (let ((digs (math-match-substring s
1)))
3506 (if (and (eq calc-language
'c
)
3508 (eq (aref digs
0) ?
0))
3509 (math-read-number (concat "8#" digs
))
3510 (if (<= (length digs
) (* 2 math-bignum-digit-length
))
3511 (string-to-number digs
)
3512 (cons 'bigpos
(math-read-bignum digs
))))))
3514 ;; Clean up the string if necessary
3515 ((string-match "\\`\\(.*\\)[ \t\n]+\\([^\001]*\\)\\'" s
)
3516 (math-read-number (concat (math-match-substring s
1)
3517 (math-match-substring s
2))))
3519 ;; Plus and minus signs
3520 ((string-match "^[-_+]\\(.*\\)$" s
)
3521 (let ((val (math-read-number (math-match-substring s
1))))
3522 (and val
(if (eq (aref s
0) ?
+) val
(math-neg val
)))))
3524 ;; Forms that require extensions module
3525 ((string-match "[^-+0-9eE.]" s
)
3527 (math-read-number-fancy s
))
3530 ((string-match "^\\([0-9]*\\)\\.\\([0-9]*\\)$" s
)
3531 (let ((int (math-match-substring s
1))
3532 (frac (math-match-substring s
2)))
3533 (let ((ilen (length int
))
3534 (flen (length frac
)))
3535 (let ((int (if (> ilen
0) (math-read-number int
) 0))
3536 (frac (if (> flen
0) (math-read-number frac
) 0)))
3537 (and int frac
(or (> ilen
0) (> flen
0))
3539 (math-add (math-scale-int int flen
) frac
)
3543 ((string-match "^\\(.*\\)[eE]\\([-+]?[0-9]+\\)$" s
)
3544 (let ((mant (math-match-substring s
1))
3545 (exp (math-match-substring s
2)))
3546 (let ((mant (if (> (length mant
) 0) (math-read-number mant
) 1))
3547 (exp (if (<= (length exp
) (if (memq (aref exp
0) '(?
+ ?-
)) 8 7))
3548 (string-to-number exp
))))
3549 (and mant exp
(Math-realp mant
) (> exp -
4000000) (< exp
4000000)
3550 (let ((mant (math-float mant
)))
3551 (list 'float
(nth 1 mant
) (+ (nth 2 mant
) exp
)))))))
3556 ;;; Parse a very simple number, keeping all digits.
3557 (defun math-read-number-simple (s)
3558 "Convert the string S into a Calc number.
3559 S is assumed to be a simple number (integer or float without an exponent)
3560 and all digits are kept, regardless of Calc's current precision."
3563 ((string-match "^[0-9]+$" s
)
3564 (if (string-match "^\\(0+\\)" s
)
3565 (setq s
(substring s
(match-end 0))))
3566 (if (<= (length s
) (* 2 math-bignum-digit-length
))
3567 (string-to-number s
)
3568 (cons 'bigpos
(math-read-bignum s
))))
3570 ((string-match "^-[0-9]+$" s
)
3571 (if (<= (length s
) (1+ (* 2 math-bignum-digit-length
)))
3572 (string-to-number s
)
3573 (cons 'bigneg
(math-read-bignum (substring s
1)))))
3575 ((string-match "^\\(-?[0-9]*\\)\\.\\([0-9]*\\)$" s
)
3576 (let ((int (math-match-substring s
1))
3577 (frac (math-match-substring s
2)))
3578 (list 'float
(math-read-number-simple (concat int frac
))
3579 (- (length frac
)))))
3583 (defun math-match-substring (s n
)
3584 (if (match-beginning n
)
3585 (substring s
(match-beginning n
) (match-end n
))
3588 (defun math-read-bignum (s) ; [l X]
3589 (if (> (length s
) math-bignum-digit-length
)
3590 (cons (string-to-number (substring s
(- math-bignum-digit-length
)))
3591 (math-read-bignum (substring s
0 (- math-bignum-digit-length
))))
3592 (list (string-to-number s
))))
3594 (defconst math-standard-opers
3595 '( ( "_" calcFunc-subscr
1200 1201 )
3596 ( "%" calcFunc-percent
1100 -
1 )
3597 ( "u!" calcFunc-lnot -
1 1000 )
3598 ( "mod" mod
400 400 185 )
3599 ( "+/-" sdev
300 300 185 )
3600 ( "!!" calcFunc-dfact
210 -
1 )
3601 ( "!" calcFunc-fact
210 -
1 )
3604 ( "u+" ident -
1 197 )
3608 ( "\\" calcFunc-idiv
190 191 )
3612 ( "<" calcFunc-lt
160 161 )
3613 ( ">" calcFunc-gt
160 161 )
3614 ( "<=" calcFunc-leq
160 161 )
3615 ( ">=" calcFunc-geq
160 161 )
3616 ( "=" calcFunc-eq
160 161 )
3617 ( "==" calcFunc-eq
160 161 )
3618 ( "!=" calcFunc-neq
160 161 )
3619 ( "&&" calcFunc-land
110 111 )
3620 ( "||" calcFunc-lor
100 101 )
3621 ( "?" (math-read-if) 91 90 )
3622 ( "!!!" calcFunc-pnot -
1 85 )
3623 ( "&&&" calcFunc-pand
80 81 )
3624 ( "|||" calcFunc-por
75 76 )
3625 ( ":=" calcFunc-assign
51 50 )
3626 ( "::" calcFunc-condition
45 46 )
3627 ( "=>" calcFunc-evalto
40 41 )
3628 ( "=>" calcFunc-evalto
40 -
1 )))
3630 (defun math-standard-ops ()
3631 (if calc-multiplication-has-precedence
3636 math-standard-opers
))
3641 math-standard-opers
))))
3643 (defvar math-expr-opers
(math-standard-ops))
3645 (defun math-standard-ops-p ()
3646 (let ((meo (caar math-expr-opers
)))
3648 (string= meo
"*"))))
3650 (defun math-expr-ops ()
3651 (if (math-standard-ops-p)
3656 (defun calc-grab-region (top bot arg
)
3657 "Parse the region as a vector of numbers and push it on the Calculator stack."
3658 (interactive "r\nP")
3660 (calc-do-grab-region top bot arg
))
3663 (defun calc-grab-rectangle (top bot arg
)
3664 "Parse a rectangle as a matrix of numbers and push it on the Calculator stack."
3665 (interactive "r\nP")
3667 (calc-do-grab-rectangle top bot arg
))
3669 (defun calc-grab-sum-down (top bot arg
)
3670 "Parse a rectangle as a matrix of numbers and sum its columns."
3671 (interactive "r\nP")
3673 (calc-do-grab-rectangle top bot arg
'calcFunc-reduced
))
3675 (defun calc-grab-sum-across (top bot arg
)
3676 "Parse a rectangle as a matrix of numbers and sum its rows."
3677 (interactive "r\nP")
3679 (calc-do-grab-rectangle top bot arg
'calcFunc-reducea
))
3683 (defun calc-embedded (arg &optional end obeg oend
)
3684 "Start Calc Embedded mode on the formula surrounding point."
3687 (calc-do-embedded arg end obeg oend
))
3690 (defun calc-embedded-activate (&optional arg cbuf
)
3691 "Scan the current editing buffer for all embedded := and => formulas.
3692 Also looks for the equivalent TeX words, \\gets and \\evalto."
3694 (calc-do-embedded-activate arg cbuf
))
3696 (defun calc-user-invocation ()
3698 (unless calc-invocation-macro
3699 (error "Use `Z I' inside Calc to define a `C-x * Z' keyboard macro"))
3700 (execute-kbd-macro calc-invocation-macro nil
))
3702 ;;; User-programmability.
3705 (defmacro defmath
(func args
&rest body
) ; [Public]
3707 (math-do-defmath func args body
))
3709 ;;; Functions needed for Lucid Emacs support.
3711 (defun calc-read-key (&optional optkey
)
3712 (cond ((featurep 'xemacs
)
3713 (let ((event (next-command-event)))
3714 (let ((key (event-to-character event t t
)))
3715 (or key optkey
(error "Expected a plain keystroke"))
3718 (let ((key (read-event)))
3721 (defun calc-unread-command (&optional input
)
3722 (if (featurep 'xemacs
)
3723 (setq unread-command-event
3724 (if (integerp input
) (character-to-event input
)
3725 (or input last-command-event
)))
3726 (push (or input last-command-event
) unread-command-events
)))
3728 (defun calc-clear-unread-commands ()
3729 (if (featurep 'xemacs
)
3730 (setq unread-command-event nil
)
3731 (setq unread-command-events nil
)))
3733 (when calc-always-load-extensions
3735 (calc-load-everything))
3738 (run-hooks 'calc-load-hook
)
3742 ;;; arch-tag: 0c3b170c-4ce6-4eaf-8d9b-5834d1fe938f
3743 ;;; calc.el ends here