*** empty log message ***
[emacs.git] / lisp / calc / calc.el
blob290ac5c963c4f5ff6a0b71aa9afb2c805c697bd4
1 ;;; calc.el --- the GNU Emacs calculator
3 ;; Copyright (C) 1990, 1991, 1992, 1993, 2001, 2002 Free Software Foundation, Inc.
5 ;; Author: David Gillespie <daveg@synaptics.com>
6 ;; Maintainer: Colin Walters <walters@debian.org>
7 ;; Keywords: convenience, extensions
8 ;; Version: 2.02g
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY. No author or distributor
14 ;; accepts responsibility to anyone for the consequences of using it
15 ;; or for whether it serves any particular purpose or works at all,
16 ;; unless he says so in writing. Refer to the GNU Emacs General Public
17 ;; License for full details.
19 ;; Everyone is granted permission to copy, modify and redistribute
20 ;; GNU Emacs, but only under the conditions described in the
21 ;; GNU Emacs General Public License. A copy of this license is
22 ;; supposed to have been given to you along with GNU Emacs so you
23 ;; can know your rights and responsibilities. It should be in a
24 ;; file named COPYING. Among other things, the copyright notice
25 ;; and this notice must be preserved on all copies.
27 ;;; Commentary:
29 ;; Calc is split into many files. This file is the main entry point.
30 ;; This file includes autoload commands for various other basic Calc
31 ;; facilities. The more advanced features are based in calc-ext, which
32 ;; in turn contains autoloads for the rest of the Calc files. This
33 ;; odd set of interactions is designed to make Calc's loading time
34 ;; be as short as possible when only simple calculations are needed.
36 ;; Original author's address:
37 ;; Dave Gillespie, daveg@synaptics.com, uunet!synaptx!daveg.
38 ;; Synaptics, Inc., 2698 Orchard Parkway, San Jose, CA 95134.
40 ;; The old address daveg@csvax.cs.caltech.edu will continue to
41 ;; work for the foreseeable future.
43 ;; Bug reports and suggestions are always welcome! (Type M-x
44 ;; report-calc-bug to send them).
46 ;; All functions, macros, and Lisp variables defined here begin with one
47 ;; of the prefixes "math", "Math", or "calc", with the exceptions of
48 ;; "full-calc", "full-calc-keypad", "another-calc", "quick-calc",
49 ;; "report-calc-bug", and "defmath". User-accessible variables begin
50 ;; with "var-".
52 ;;; TODO:
54 ;; Fix rewrite mechanism to do less gratuitous rearrangement of terms.
55 ;; Implement a pattern-based "refers" predicate.
57 ;; Make it possible to Undo a selection command.
58 ;; Figure out how to allow selecting rows of matrices.
59 ;; If cursor was in selection before, move it after j n, j p, j L, etc.
60 ;; Consider reimplementing calc-delete-selection using rewrites.
62 ;; Implement line-breaking in non-flat compositions (is this desirable?).
63 ;; Implement matrix formatting with multi-line components.
65 ;; Have "Z R" define a user command based on a set of rewrite rules.
66 ;; Support "incf" and "decf" in defmath definitions.
67 ;; Have defmath generate calls to calc-binary-op or calc-unary-op.
68 ;; Make some way to define algebraic functions using keyboard macros.
70 ;; Allow calc-word-size=0 => Common Lisp-style signed bitwise arithmetic.
71 ;; Consider digamma function (and thus arb. prec. Euler's gamma constant).
72 ;; May as well make continued-fractions stuff available to the user.
74 ;; How about matrix eigenvalues, SVD, pseudo-inverse, etc.?
75 ;; Should cache matrix inverses as well as decompositions.
76 ;; If dividing by a non-square matrix, use least-squares automatically.
77 ;; Consider supporting matrix exponentials.
79 ;; Have ninteg detect and work around singularities at the endpoints.
80 ;; Use an adaptive subdivision algorithm for ninteg.
81 ;; Provide nsum and nprod to go along with ninteg.
83 ;; Handle TeX-mode parsing of \matrix{ ... } where ... contains braces.
84 ;; Support AmS-TeX's \{d,t,}frac, \{d,t,}binom notations.
85 ;; Format and parse sums and products in Eqn and Math modes.
87 ;; Get math-read-big-expr to read sums, products, etc.
88 ;; Change calc-grab-region to use math-read-big-expr.
89 ;; Have a way to define functions using := in Embedded Mode.
91 ;; Support polar plotting with GNUPLOT.
92 ;; Make a calc-graph-histogram function.
94 ;; Replace hokey formulas for complex functions with formulas designed
95 ;; to minimize roundoff while maintaining the proper branch cuts.
96 ;; Test accuracy of advanced math functions over whole complex plane.
97 ;; Extend Bessel functions to provide arbitrary precision.
98 ;; Extend advanced math functions to handle error forms and intervals.
99 ;; Provide a better implementation for math-sin-cos-raw.
100 ;; Provide a better implementation for math-hypot.
101 ;; Provide a better implementation for math-make-frac.
102 ;; Provide a better implementation for calcFunc-prfac.
103 ;; Provide a better implementation for calcFunc-factor.
105 ;; Provide more examples in the tutorial section of the manual.
106 ;; Cover in the tutorial: simplification modes, declarations,
107 ;; bitwise stuff, selections, matrix mapping, financial functions.
108 ;; Provide more Lisp programming examples in the manual.
109 ;; Finish the Internals section of the manual (and bring it up to date).
111 ;; Tim suggests adding spreadsheet-like features.
112 ;; Implement language modes for Gnuplot, Lisp, Ada, APL, ...?
114 ;; For atan series, if x > tan(pi/12) (about 0.268) reduce using the identity
115 ;; atan(x) = atan((x * sqrt(3) - 1) / (sqrt(3) + x)) + pi/6.
117 ;; A better integration algorithm:
118 ;; Use breadth-first instead of depth-first search, as follows:
119 ;; The integral cache allows unfinished integrals in symbolic notation
120 ;; on the righthand side. An entry with no unfinished integrals on the
121 ;; RHS is "complete"; references to it elsewhere are replaced by the
122 ;; integrated value. More than one cache entry for the same integral
123 ;; may exist, though if one becomes complete, the others may be deleted.
124 ;; The integrator works by using every applicable rule (such as
125 ;; substitution, parts, linearity, etc.) to generate possible righthand
126 ;; sides, all of which are entered into the cache. Now, as long as the
127 ;; target integral is not complete (and the time limit has not run out)
128 ;; choose an incomplete integral from the cache and, for every integral
129 ;; appearing in its RHS's, add those integrals to the cache using the
130 ;; same substitition, parts, etc. rules. The cache should be organized
131 ;; as a priority queue, choosing the "simplest" incomplete integral at
132 ;; each step, or choosing randomly among equally simple integrals.
133 ;; Simplicity equals small size, and few steps removed from the original
134 ;; target integral. Note that when the integrator finishes, incomplete
135 ;; integrals can be left in the cache, so the algorithm can start where
136 ;; it left off if another similar integral is later requested.
137 ;; Breadth-first search would avoid the nagging problem of, e.g., whether
138 ;; to use parts or substitution first, and which decomposition is best.
139 ;; All are tried, and any path that diverges will quickly be put on the
140 ;; back burner by the priority queue.
141 ;; Note: Probably a good idea to call math-simplify-extended before
142 ;; measuring a formula's simplicity.
144 ;; From: "Robert J. Chassell" <bob@rattlesnake.com>
145 ;; Subject: Re: fix for `Cannot open load file: calc-alg-3'
146 ;; To: walters@debian.org
147 ;; Date: Sat, 24 Nov 2001 21:44:21 +0000 (UTC)
149 ;; Could you add logistic curve fitting to the current list?
151 ;; (I guess the key binding for a logistic curve would have to be `s'
152 ;; since a logistic curve is an `s' curve; both `l' and `L' are already
153 ;; taken for logarithms.)
155 ;; Here is the current list for curve fitting;
157 ;; `1'
158 ;; Linear or multilinear. a + b x + c y + d z.
160 ;; `2-9'
161 ;; Polynomials. a + b x + c x^2 + d x^3.
163 ;; `e'
164 ;; Exponential. a exp(b x) exp(c y).
166 ;; `E'
167 ;; Base-10 exponential. a 10^(b x) 10^(c y).
169 ;; `x'
170 ;; Exponential (alternate notation). exp(a + b x + c y).
172 ;; `X'
173 ;; Base-10 exponential (alternate). 10^(a + b x + c y).
175 ;; `l'
176 ;; Logarithmic. a + b ln(x) + c ln(y).
178 ;; `L'
179 ;; Base-10 logarithmic. a + b log10(x) + c log10(y).
181 ;; `^'
182 ;; General exponential. a b^x c^y.
184 ;; `p'
185 ;; Power law. a x^b y^c.
187 ;; `q'
188 ;; Quadratic. a + b (x-c)^2 + d (x-e)^2.
190 ;; `g'
191 ;; Gaussian. (a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2).
194 ;; Logistic curves are used a great deal in ecology, and in predicting
195 ;; human actions, such as use of different kinds of energy in a country
196 ;; (wood, coal, oil, natural gas, etc.) or the number of scientific
197 ;; papers a person publishes, or the number of movies made.
199 ;; (The less information on which to base the curve, the higher the error
200 ;; rate. Theodore Modis ran some Monte Carlo simulations and produced
201 ;; what may be useful set of confidence levels for different amounts of
202 ;; initial information.)
204 ;;; Code:
206 (provide 'calc)
207 (require 'calc-macs)
209 ;;; The "###autoload" comment will be used by Emacs version 19 for
210 ;;; maintaining the loaddefs.el file automatically.
212 ;;;###autoload
213 (defvar calc-info-filename "calc.info"
214 "*File name in which to look for the Calculator's Info documentation.")
216 ;;;###autoload
217 (defvar calc-settings-file user-init-file
218 "*File in which to record permanent settings; default is `user-init-file'.")
220 ;;;###autoload
221 (defvar calc-autoload-directory nil
222 "Name of directory from which additional \".elc\" files for Calc should be
223 loaded. Should include a trailing \"/\".
224 If nil, use original installation directory.
225 This can safely be nil as long as the Calc files are on the load-path.")
227 ;;;###autoload
228 (defvar calc-gnuplot-name "gnuplot"
229 "*Name of GNUPLOT program, for calc-graph features.")
231 ;;;###autoload
232 (defvar calc-gnuplot-plot-command nil
233 "*Name of command for displaying GNUPLOT output; %s = file name to print.")
235 ;;;###autoload
236 (defvar calc-gnuplot-print-command "lp %s"
237 "*Name of command for printing GNUPLOT output; %s = file name to print.")
239 ;; Address of the author of Calc, for use by report-calc-bug.
240 (defvar calc-bug-address "walters@debian.org")
242 ;; If t, scan keymaps to find all DEL-like keys.
243 ;; if nil, only DEL itself is mapped to calc-pop.
244 (defvar calc-scan-for-dels t)
246 (defvar calc-extensions-loaded nil)
248 ;; Calculator stack.
249 ;; Entries are 3-lists: Formula, Height (in lines), Selection (or nil).
250 (defvar calc-stack '((top-of-stack 1 nil)))
252 ;; Index into calc-stack of "top" of stack.
253 ;; This is 1 unless calc-truncate-stack has been used.
254 ;;(defvar calc-stack-top 1)
256 ;; If non-nil, load the calc-ext module automatically when calc is loaded.
257 ;;(defvar calc-always-load-extensions nil)
259 ;; If non-nil, display line numbers in Calculator stack.
260 ;;(defvar calc-line-numbering t)
262 ;; If non-nil, break long values across multiple lines in Calculator stack.
263 ;;(defvar calc-line-breaking t)
265 ;; If nil, stack display is left-justified.
266 ;; If 'right, stack display is right-justified.
267 ;; If 'center, stack display is centered."
268 ;;(defvar calc-display-just nil)
270 ;; Horizontal origin of displayed stack entries.
271 ;; In left-justified mode, this is effectively indentation. (Default 0).
272 ;; In right-justified mode, this is effectively window width.
273 ;; In centered mode, center of stack entry is placed here.
274 ;;(defvar calc-display-origin nil)
276 ;; Radix for entry and display of numbers in calc-mode, 2-36.
277 ;;(defvar calc-number-radix 10)
279 ;; If non-nil, leading zeros are provided to pad integers to calc-word-size.
280 ;;(defvar calc-leading-zeros nil)
282 ;; If non-nil, group digits in large displayed integers by inserting spaces.
283 ;; If an integer, group that many digits at a time.
284 ;; If 't', use 4 for binary and hex, 3 otherwise.
285 ;;(defvar calc-group-digits nil)
287 ;; The character (in the form of a string) to be used for grouping digits.
288 ;; This is used only when calc-group-digits mode is on.
289 ;;(defvar calc-group-char ",")
291 ;; The character (in the form of a string) to be used as a decimal point.
292 ;;(defvar calc-point-char ".")
294 ;; Format of displayed fractions; a string of one or two of ":" or "/".
295 ;;(defvar calc-frac-format '(":" nil))
297 ;; If non-nil, prefer fractional over floating-point results.
298 ;;(defvar calc-prefer-frac nil)
300 ;; Format of displayed hours-minutes-seconds angles, a format string.
301 ;; String must contain three %s marks for hours, minutes, seconds respectively.
302 ;;(defvar calc-hms-format "%s@ %s' %s\"")
304 ;; Format of displayed date forms.
305 ;;(defvar calc-date-format '((H ":" mm ":" SS pp " ") Www " " Mmm " " D ", " YYYY))
307 ;; Format to use for display of floating-point numbers in calc-mode.
308 ;; Must be a list of one of the following forms:
309 ;; (float 0) Floating point format, display full precision.
310 ;; (float N) N > 0: Floating point format, at most N significant figures.
311 ;; (float -N) -N < 0: Floating point format, calc-internal-prec - N figs.
312 ;; (fix N) N >= 0: Fixed point format, N places after decimal point.
313 ;; (sci 0) Scientific notation, full precision.
314 ;; (sci N) N > 0: Scientific notation, N significant figures.
315 ;; (sci -N) -N < 0: Scientific notation, calc-internal-prec - N figs.
316 ;; (eng 0) Engineering notation, full precision.
317 ;; (eng N) N > 0: Engineering notation, N significant figures.
318 ;; (eng -N) -N < 0: Engineering notation, calc-internal-prec - N figs.
319 ;;(defvar calc-float-format '(float 0))
321 ;; Format to use when full precision must be displayed.
322 ;;(defvar calc-full-float-format '(float 0))
324 ;; Format to use for display of complex numbers in calc-mode. Must be one of:
325 ;; nil Use (x, y) form.
326 ;; i Use x + yi form.
327 ;; j Use x + yj form.
328 ;;(defvar calc-complex-format nil)
330 ;; Preferred form, either 'cplx or 'polar, for complex numbers.
331 ;;(defvar calc-complex-mode 'cplx)
333 ;; If nil, 1 / 0 is left unsimplified.
334 ;; If 0, 1 / 0 is changed to inf (zeros are considered positive).
335 ;; Otherwise, 1 / 0 is changed to uinf (undirected infinity).
336 ;;(defvar calc-infinite-mode nil)
338 ;; If non-nil, display vectors of byte-sized integers as strings.
339 ;;(defvar calc-display-strings nil)
341 ;; If nil, vector elements are left-justified.
342 ;; If 'right, vector elements are right-justified.
343 ;; If 'center, vector elements are centered."
344 ;;(defvar calc-matrix-just 'center)
346 ;; If non-nil, display vectors one element per line.
347 ;;(defvar calc-break-vectors nil)
349 ;; If non-nil, display long vectors in full. If nil, use abbreviated form.
350 ;;(defvar calc-full-vectors t)
352 ;; If non-nil, display long vectors in full in the trail.
353 ;;(defvar calc-full-trail-vectors t)
355 ;; If non-nil, separate elements of displayed vectors with this string.
356 ;;(defvar calc-vector-commas ",")
358 ;; If non-nil, surround displayed vectors with these characters.
359 ;;(defvar calc-vector-brackets "[]")
361 ;; A list of code-letter symbols that control "big" matrix display.
362 ;; If 'R is present, display inner brackets for matrices.
363 ;; If 'O is present, display outer brackets for matrices (above/below).
364 ;; If 'C is present, display outer brackets for matrices (centered).
365 ;;(defvar calc-matrix-brackets '(R O))
367 ;; Language or format for entry and display of stack values. Must be one of:
368 ;; nil Use standard Calc notation.
369 ;; flat Use standard Calc notation, one-line format.
370 ;; big Display formulas in 2-d notation (enter w/std notation).
371 ;; unform Use unformatted display: add(a, mul(b,c)).
372 ;; c Use C language notation.
373 ;; pascal Use Pascal language notation.
374 ;; fortran Use Fortran language notation.
375 ;; tex Use TeX notation.
376 ;; eqn Use eqn notation.
377 ;; math Use Mathematica(tm) notation.
378 ;; maple Use Maple notation.
379 ;;(defvar calc-language nil)
381 ;; Numeric prefix argument for the command that set calc-language.
382 ;;(defvar calc-language-option nil)
384 ;; Open-parenthesis string for function call notation.
385 ;;(defvar calc-function-open "(")
387 ;; Close-parenthesis string for function call notation.
388 ;;(defvar calc-function-close ")")
390 ;; Function through which to pass strings after formatting.
391 ;;(defvar calc-language-output-filter nil)
393 ;; Function through which to pass strings before parsing.
394 ;;(defvar calc-language-input-filter nil)
396 ;; Formatting function used for non-decimal numbers.
397 ;;(defvar calc-radix-formatter nil)
399 ;; Label to display at left of formula.
400 ;;(defvar calc-left-label "")
402 ;; Label to display at right of formula.
403 ;;(defvar calc-right-label "")
405 ;; Minimum number of bits per word, if any, for binary operations in calc-mode.
406 ;;(defvar calc-word-size 32)
408 ;; Most recently used value of M in a modulo form.
409 ;;(defvar calc-previous-modulo nil)
411 ;; Type of simplification applied to results.
412 ;; If 'none, results are not simplified when pushed on the stack.
413 ;; If 'num, functions are simplified only when args are constant.
414 ;; If nil, only fast simplifications are applied.
415 ;; If 'binary, math-clip is applied if appropriate.
416 ;; If 'alg, math-simplify is applied.
417 ;; If 'ext, math-simplify-extended is applied.
418 ;; If 'units, math-simplify-units is applied.
419 ;;(defvar calc-simplify-mode nil)
421 ;; If non-nil, recompute evalto's automatically when necessary.
422 ;;(defvar calc-auto-recompute t)
424 ;; If non-nil, display shows unformatted Lisp exprs. (For debugging)
425 ;;(defvar calc-display-raw nil)
427 ;; Number of digits of internal precision for calc-mode calculations.
428 ;;(defvar calc-internal-prec 12)
430 ;; If non-nil, next operation is Inverse.
431 ;;(defvar calc-inverse-flag nil)
433 ;; If non-nil, next operation is Hyperbolic.
434 ;;(defvar calc-hyperbolic-flag nil)
436 ;; If non-nil, next operation should not remove its arguments from stack.
437 ;;(defvar calc-keep-args-flag nil)
439 ;; If deg, angles are in degrees; if rad, angles are in radians.
440 ;; If hms, angles are in degrees-minutes-seconds.
441 ;;(defvar calc-angle-mode 'deg)
443 ;; If non-nil, numeric entry accepts whole algebraic expressions.
444 ;; If nil, algebraic expressions must be preceded by "'".
445 ;;(defvar calc-algebraic-mode nil)
447 ;; Like calc-algebraic-mode except only affects ( and [ keys.
448 ;;(defvar calc-incomplete-algebraic-mode nil)
450 ;; If non-nil, inexact numeric computations like sqrt(2) are postponed.
451 ;; If nil, computations on numbers always yield numbers where possible.
452 ;;(defvar calc-symbolic-mode nil)
454 ;; If 'matrix, variables are assumed to be matrix-valued.
455 ;; If a number, variables are assumed to be NxN matrices.
456 ;; If 'scalar, variables are assumed to be scalar-valued.
457 ;; If nil, symbolic math routines make no assumptions about variables.
458 ;;(defvar calc-matrix-mode nil)
460 ;; If non-nil, shifted letter keys are prefix keys rather than normal meanings.
461 ;;(defvar calc-shift-prefix nil)
463 ;; Initial height of Calculator window.
464 ;;(defvar calc-window-height 7)
466 ;; If non-nil, M-x calc creates a window to display Calculator trail.
467 ;;(defvar calc-display-trail t)
469 ;; If non-nil, selected sub-formulas are shown by obscuring rest of formula.
470 ;; If nil, selected sub-formulas are highlighted by obscuring the sub-formulas.
471 ;;(defvar calc-show-selections t)
473 ;; If non-nil, commands operate only on selected portions of formulas.
474 ;; If nil, selections displayed but ignored.
475 ;;(defvar calc-use-selections t)
477 ;; If non-nil, selection hides deep structure of associative formulas.
478 ;;(defvar calc-assoc-selections t)
480 ;; If non-nil, display "Working..." for potentially slow Calculator commands.
481 ;;(defvar calc-display-working-message 'lots)
483 ;; If non-nil, automatically execute a "why" command to explain odd results.
484 ;;(defvar calc-auto-why nil)
486 ;; If non-nil, display timing information on each slow command.
487 ;;(defvar calc-timing nil)
489 ;; Floating-point numbers with this positive exponent or higher above the
490 ;; current precision are displayed in scientific notation in calc-mode.
491 (defvar calc-display-sci-high 0)
493 ;; Floating-point numbers with this negative exponent or lower are displayed
494 ;; scientific notation in calc-mode.
495 (defvar calc-display-sci-low -3)
498 ;; List of used-defined strings to append to Calculator mode line.
499 (defvar calc-other-modes nil)
501 ;; List of strings for Y prefix help.
502 (defvar calc-Y-help-msgs nil)
504 ;; t if calc-settings-file has been loaded yet.
505 (defvar calc-loaded-settings-file nil)
509 (defconst calc-mode-var-list '((calc-always-load-extensions nil)
510 (calc-mode-save-mode local)
511 (calc-line-numbering t)
512 (calc-line-breaking t)
513 (calc-display-just nil)
514 (calc-display-origin nil)
515 (calc-left-label "")
516 (calc-right-label "")
517 (calc-number-radix 10)
518 (calc-leading-zeros nil)
519 (calc-group-digits nil)
520 (calc-group-char ",")
521 (calc-point-char ".")
522 (calc-frac-format (":" nil))
523 (calc-prefer-frac nil)
524 (calc-hms-format "%s@ %s' %s\"")
525 (calc-date-format ((H ":" mm C SS pp " ")
526 Www " " Mmm " " D ", " YYYY))
527 (calc-standard-date-formats
528 ("N"
529 "<H:mm:SSpp >Www Mmm D, YYYY"
530 "D Mmm YYYY<, h:mm:SS>"
531 "Www Mmm BD< hh:mm:ss> YYYY"
532 "M/D/Y< H:mm:SSpp>"
533 "D.M.Y< h:mm:SS>"
534 "M-D-Y< H:mm:SSpp>"
535 "D-M-Y< h:mm:SS>"
536 "j<, h:mm:SS>"
537 "YYddd< hh:mm:ss>"))
538 (calc-float-format (float 0))
539 (calc-full-float-format (float 0))
540 (calc-complex-format nil)
541 (calc-matrix-just center)
542 (calc-full-vectors t)
543 (calc-full-trail-vectors t)
544 (calc-break-vectors nil)
545 (calc-vector-commas ",")
546 (calc-vector-brackets "[]")
547 (calc-matrix-brackets (R O))
548 (calc-complex-mode cplx)
549 (calc-infinite-mode nil)
550 (calc-display-strings nil)
551 (calc-simplify-mode nil)
552 (calc-auto-recompute t)
553 (calc-word-size 32)
554 (calc-previous-modulo nil)
555 (calc-display-raw nil)
556 (calc-internal-prec 12)
557 (calc-angle-mode deg)
558 (calc-algebraic-mode nil)
559 (calc-incomplete-algebraic-mode nil)
560 (calc-symbolic-mode nil)
561 (calc-matrix-mode nil)
562 (calc-autorange-units nil)
563 (calc-shift-prefix nil)
564 (calc-window-height 7)
565 (calc-was-keypad-mode nil)
566 (calc-full-mode nil)
567 (calc-language nil)
568 (calc-language-option nil)
569 (calc-user-parse-tables nil)
570 (calc-show-selections t)
571 (calc-use-selections t)
572 (calc-assoc-selections t)
573 (calc-display-trail t)
574 (calc-display-working-message lots)
575 (calc-auto-why 'maybe)
576 (calc-timing nil)
577 (calc-gnuplot-default-device "default")
578 (calc-gnuplot-default-output "STDOUT")
579 (calc-gnuplot-print-device "postscript")
580 (calc-gnuplot-print-output "auto")
581 (calc-gnuplot-geometry nil)
582 (calc-graph-default-resolution 15)
583 (calc-graph-default-resolution-3d 5)
584 (calc-invocation-macro nil)))
586 (defconst calc-local-var-list '(calc-stack
587 calc-stack-top
588 calc-undo-list
589 calc-redo-list
590 calc-always-load-extensions
591 calc-mode-save-mode
592 calc-display-raw
593 calc-line-numbering
594 calc-line-breaking
595 calc-display-just
596 calc-display-origin
597 calc-left-label
598 calc-right-label
599 calc-auto-why
600 calc-algebraic-mode
601 calc-incomplete-algebraic-mode
602 calc-symbolic-mode
603 calc-matrix-mode
604 calc-inverse-flag
605 calc-hyperbolic-flag
606 calc-keep-args-flag
607 calc-angle-mode
608 calc-number-radix
609 calc-leading-zeros
610 calc-group-digits
611 calc-group-char
612 calc-point-char
613 calc-frac-format
614 calc-prefer-frac
615 calc-hms-format
616 calc-date-format
617 calc-standard-date-formats
618 calc-float-format
619 calc-full-float-format
620 calc-complex-format
621 calc-matrix-just
622 calc-full-vectors
623 calc-full-trail-vectors
624 calc-break-vectors
625 calc-vector-commas
626 calc-vector-brackets
627 calc-matrix-brackets
628 calc-complex-mode
629 calc-infinite-mode
630 calc-display-strings
631 calc-simplify-mode
632 calc-auto-recompute
633 calc-autorange-units
634 calc-show-plain
635 calc-show-selections
636 calc-use-selections
637 calc-assoc-selections
638 calc-word-size
639 calc-internal-prec))
642 (defun calc-init-base ()
644 ;; Verify that Calc is running on the right kind of system.
645 (setq calc-emacs-type-epoch (and (fboundp 'epoch::version) epoch::version)
646 calc-emacs-type-19 (not (or calc-emacs-type-epoch
647 (string-lessp emacs-version "19")))
648 calc-emacs-type-lucid (not (not (string-match "Lucid" emacs-version)))
649 calc-emacs-type-gnu19 (and calc-emacs-type-19
650 (not calc-emacs-type-lucid)))
652 ;; Set up the standard keystroke (M-#) to run the Calculator, if that key
653 ;; has not yet been bound to anything. For best results, the user should
654 ;; do this before Calc is even loaded, so that M-# can auto-load Calc.
655 (or (global-key-binding "\e#")
656 (global-set-key "\e#" 'calc-dispatch))
658 ;; Set up the autoloading linkage.
659 (let ((name (and (fboundp 'calc-dispatch)
660 (eq (car-safe (symbol-function 'calc-dispatch)) 'autoload)
661 (nth 1 (symbol-function 'calc-dispatch))))
662 (p load-path))
664 ;; If Calc files exist on the load-path, we're all set.
665 (while (and p (not (file-exists-p
666 (expand-file-name "calc-misc.elc" (car p)))))
667 (setq p (cdr p)))
668 (or p
670 ;; If Calc is autoloaded using a path name, look there for Calc files.
671 ;; This works for both relative ("calc/calc.elc") and absolute paths.
672 (and name (file-name-directory name)
673 (let ((p2 load-path)
674 (name2 (concat (file-name-directory name)
675 "calc-misc.elc")))
676 (while (and p2 (not (file-exists-p
677 (expand-file-name name2 (car p2)))))
678 (setq p2 (cdr p2)))
679 (if p2
680 (setq load-path (nconc load-path
681 (list
682 (directory-file-name
683 (file-name-directory
684 (expand-file-name
685 name (car p2))))))))))
687 ;; If calc-autoload-directory is given, use that (and hope it works!).
688 (and calc-autoload-directory
689 (not (equal calc-autoload-directory ""))
690 (setq load-path (nconc load-path
691 (list (directory-file-name
692 calc-autoload-directory)))))))
694 ;; The following modes use specially-formatted data.
695 (put 'calc-mode 'mode-class 'special)
696 (put 'calc-trail-mode 'mode-class 'special)
698 ;; Define "inexact-result" as an e-lisp error symbol.
699 (put 'inexact-result 'error-conditions '(error inexact-result calc-error))
700 (put 'inexact-result 'error-message "Calc internal error (inexact-result)")
702 ;; Define "math-overflow" and "math-underflow" as e-lisp error symbols.
703 (put 'math-overflow 'error-conditions '(error math-overflow calc-error))
704 (put 'math-overflow 'error-message "Floating-point overflow occurred")
705 (put 'math-underflow 'error-conditions '(error math-underflow calc-error))
706 (put 'math-underflow 'error-message "Floating-point underflow occurred")
708 (setq calc-version "2.02g"
709 calc-version-date "Mon Nov 19 2001"
710 calc-trail-pointer nil ; "Current" entry in trail buffer.
711 calc-trail-overlay nil ; Value of overlay-arrow-string.
712 calc-undo-list nil ; List of previous operations for undo.
713 calc-redo-list nil ; List of recent undo operations.
714 calc-main-buffer nil ; Pointer to Calculator buffer.
715 calc-trail-buffer nil ; Pointer to Calc Trail buffer.
716 calc-why nil ; Explanations of most recent errors.
717 calc-next-why nil
718 calc-inverse-flag nil
719 calc-hyperbolic-flag nil
720 calc-keep-args-flag nil
721 calc-function-open "("
722 calc-function-close ")"
723 calc-language-output-filter nil
724 calc-language-input-filter nil
725 calc-radix-formatter nil
726 calc-last-kill nil ; Last number killed in calc-mode.
727 calc-previous-alg-entry nil ; Previous algebraic entry.
728 calc-dollar-values nil ; Values to be used for '$'.
729 calc-dollar-used nil ; Highest order of '$' that occurred.
730 calc-hashes-used nil ; Highest order of '#' that occurred.
731 calc-quick-prev-results nil ; Previous results from Quick Calc.
732 calc-said-hello nil ; Has welcome message been said yet?
733 calc-executing-macro nil ; Kbd macro executing from "K" key.
734 calc-any-selections nil ; Nil means no selections present.
735 calc-help-phase 0 ; Count of consecutive "?" keystrokes.
736 calc-full-help-flag nil ; Executing calc-full-help?
737 calc-refresh-count 0 ; Count of calc-refresh calls.
738 calc-display-dirty nil
739 calc-prepared-composition nil
740 calc-selection-cache-default-entry nil
741 calc-embedded-info nil
742 calc-embedded-active nil
743 calc-standalone-flag nil
744 var-EvalRules nil
745 math-eval-rules-cache-tag t
746 math-radix-explicit-format t
747 math-expr-function-mapping nil
748 math-expr-variable-mapping nil
749 math-read-expr-quotes nil
750 math-working-step nil
751 math-working-step-2 nil
752 var-i '(special-const (math-imaginary 1))
753 var-pi '(special-const (math-pi))
754 var-e '(special-const (math-e))
755 var-phi '(special-const (math-phi))
756 var-gamma '(special-const (math-gamma-const))
757 var-Modes '(special-const (math-get-modes-vec)))
759 (mapcar (function (lambda (v) (or (boundp (car v)) (set (car v) (nth 1 v)))))
760 calc-mode-var-list)
761 (mapcar (function (lambda (v) (or (boundp v) (set v nil))))
762 calc-local-var-list)
764 (unless (boundp 'calc-mode-map)
765 (setq calc-mode-map (make-keymap))
766 (suppress-keymap calc-mode-map t)
767 (define-key calc-mode-map "+" 'calc-plus)
768 (define-key calc-mode-map "-" 'calc-minus)
769 (define-key calc-mode-map "*" 'calc-times)
770 (define-key calc-mode-map "/" 'calc-divide)
771 (define-key calc-mode-map "%" 'calc-mod)
772 (define-key calc-mode-map "&" 'calc-inv)
773 (define-key calc-mode-map "^" 'calc-power)
774 (define-key calc-mode-map "\M-%" 'calc-percent)
775 (define-key calc-mode-map "e" 'calcDigit-start)
776 (define-key calc-mode-map "i" 'calc-info)
777 (define-key calc-mode-map "n" 'calc-change-sign)
778 (define-key calc-mode-map "q" 'calc-quit)
779 (define-key calc-mode-map "Y" 'nil)
780 (define-key calc-mode-map "Y?" 'calc-shift-Y-prefix-help)
781 (define-key calc-mode-map "?" 'calc-help)
782 (define-key calc-mode-map " " 'calc-enter)
783 (define-key calc-mode-map "'" 'calc-algebraic-entry)
784 (define-key calc-mode-map "$" 'calc-auto-algebraic-entry)
785 (define-key calc-mode-map "\"" 'calc-auto-algebraic-entry)
786 (define-key calc-mode-map "\t" 'calc-roll-down)
787 (define-key calc-mode-map "\M-\t" 'calc-roll-up)
788 (define-key calc-mode-map "\C-m" 'calc-enter)
789 (define-key calc-mode-map "\M-\C-m" 'calc-last-args-stub)
790 (define-key calc-mode-map "\C-j" 'calc-over)
792 (mapcar (function
793 (lambda (x)
794 (define-key calc-mode-map (char-to-string x) 'undefined)))
795 "lOW")
796 (mapcar (function
797 (lambda (x)
798 (define-key calc-mode-map (char-to-string x)
799 'calc-missing-key)))
800 (concat "ABCDEFGHIJKLMNPQRSTUVXZabcdfghjkmoprstuvwxyz"
801 ":\\|!()[]<>{},;=~`\C-k\M-k\C-w\M-w\C-y\C-_"))
802 (mapcar (function
803 (lambda (x)
804 (define-key calc-mode-map (char-to-string x) 'calcDigit-start)))
805 "_0123456789.#@")
807 (setq calc-digit-map (make-keymap))
808 (if calc-emacs-type-lucid
809 (map-keymap (function
810 (lambda (keys bind)
811 (define-key calc-digit-map keys
812 (if (eq bind 'undefined)
813 'undefined 'calcDigit-nondigit))))
814 calc-mode-map)
815 (let ((cmap (if calc-emacs-type-19 (nth 1 calc-mode-map) calc-mode-map))
816 (dmap (if calc-emacs-type-19 (nth 1 calc-digit-map)
817 calc-digit-map))
818 (i 0))
819 (while (< i 128)
820 (aset dmap i
821 (if (eq (aref cmap i) 'undefined)
822 'undefined 'calcDigit-nondigit))
823 (setq i (1+ i)))))
824 (mapcar (function
825 (lambda (x)
826 (define-key calc-digit-map (char-to-string x)
827 'calcDigit-key)))
828 "_0123456789.e+-:n#@oh'\"mspM")
829 (mapcar (function
830 (lambda (x)
831 (define-key calc-digit-map (char-to-string x)
832 'calcDigit-letter)))
833 "abcdfgijklqrtuvwxyzABCDEFGHIJKLNOPQRSTUVWXYZ")
834 (define-key calc-digit-map "'" 'calcDigit-algebraic)
835 (define-key calc-digit-map "`" 'calcDigit-edit)
836 (define-key calc-digit-map "\C-g" 'abort-recursive-edit)
838 (mapcar (function
839 (lambda (x)
840 (condition-case err
841 (progn
842 (define-key calc-digit-map x 'calcDigit-backspace)
843 (define-key calc-mode-map x 'calc-pop)
844 (define-key calc-mode-map
845 (if (vectorp x)
846 (if calc-emacs-type-lucid
847 (if (= (length x) 1)
848 (vector (if (consp (aref x 0))
849 (cons 'meta (aref x 0))
850 (list 'meta (aref x 0))))
851 "\e\C-d")
852 (vconcat "\e" x))
853 (concat "\e" x))
854 'calc-pop-above))
855 (error nil))))
856 (if calc-scan-for-dels
857 (append (where-is-internal 'delete-backward-char global-map)
858 (where-is-internal 'backward-delete-char global-map)
859 '("\C-d"))
860 '("\177" "\C-d")))
862 (setq calc-dispatch-map (make-keymap))
863 (mapcar (function
864 (lambda (x)
865 (define-key calc-dispatch-map (char-to-string (car x)) (cdr x))
866 (if (string-match "abcdefhijklnopqrstuwxyz"
867 (char-to-string (car x)))
868 (define-key calc-dispatch-map
869 (char-to-string (- (car x) ?a -1)) (cdr x)))
870 (define-key calc-dispatch-map (format "\e%c" (car x)) (cdr x))))
871 '( ( ?a . calc-embedded-activate )
872 ( ?b . calc-big-or-small )
873 ( ?c . calc )
874 ( ?d . calc-embedded-duplicate )
875 ( ?e . calc-embedded )
876 ( ?f . calc-embedded-new-formula )
877 ( ?g . calc-grab-region )
878 ( ?h . calc-dispatch-help )
879 ( ?i . calc-info )
880 ( ?j . calc-embedded-select )
881 ( ?k . calc-keypad )
882 ( ?l . calc-load-everything )
883 ( ?m . read-kbd-macro )
884 ( ?n . calc-embedded-next )
885 ( ?o . calc-other-window )
886 ( ?p . calc-embedded-previous )
887 ( ?q . quick-calc )
888 ( ?r . calc-grab-rectangle )
889 ( ?s . calc-info-summary )
890 ( ?t . calc-tutorial )
891 ( ?u . calc-embedded-update-formula )
892 ( ?w . calc-embedded-word )
893 ( ?x . calc-quit )
894 ( ?y . calc-copy-to-buffer )
895 ( ?z . calc-user-invocation )
896 ( ?= . calc-embedded-update-formula )
897 ( ?\' . calc-embedded-new-formula )
898 ( ?\` . calc-embedded-edit )
899 ( ?: . calc-grab-sum-down )
900 ( ?_ . calc-grab-sum-across )
901 ( ?0 . calc-reset )
902 ( ?# . calc-same-interface )
903 ( ?? . calc-dispatch-help ) ))
906 (autoload 'calc-extensions "calc-ext")
907 (autoload 'calc-need-macros "calc-macs")
909 ;;;; (Autoloads here)
910 (mapcar (function (lambda (x)
911 (mapcar (function (lambda (func)
912 (autoload func (car x)))) (cdr x))))
915 ("calc-aent" calc-Need-calc-aent calc-alg-digit-entry calc-alg-entry
916 calc-check-user-syntax calc-do-alg-entry calc-do-calc-eval
917 calc-do-quick-calc calc-match-user-syntax math-build-parse-table
918 math-find-user-tokens math-read-expr-list math-read-exprs math-read-if
919 math-read-token math-remove-dashes)
921 ("calc-misc" calc-Need-calc-misc
922 calc-do-handle-whys calc-do-refresh calc-num-prefix-name
923 calc-record-list calc-record-why calc-report-bug calc-roll-down-stack
924 calc-roll-up-stack calc-temp-minibuffer-message calcFunc-floor
925 calcFunc-inv calcFunc-trunc math-concat math-constp math-div2
926 math-div2-bignum math-do-working math-evenp math-fixnatnump
927 math-fixnump math-floor math-imod math-ipow math-looks-negp math-mod
928 math-negp math-posp math-pow math-read-radix-digit math-reject-arg
929 math-trunc math-zerop)
933 (mapcar (function (lambda (x)
934 (mapcar (function (lambda (cmd)
935 (autoload cmd (car x) nil t))) (cdr x))))
938 ("calc-aent" calc-algebraic-entry calc-auto-algebraic-entry
939 calcDigit-algebraic calcDigit-edit)
941 ("calc-misc" another-calc calc-big-or-small calc-dispatch-help
942 calc-help calc-info calc-info-summary calc-inv calc-last-args-stub
943 calc-missing-key calc-mod calc-other-window calc-over calc-percent
944 calc-pop-above calc-power calc-roll-down calc-roll-up
945 calc-shift-Y-prefix-help calc-tutorial calcDigit-letter
946 report-calc-bug))))
948 (calc-init-base)
951 ;;;###autoload (global-set-key "\e#" 'calc-dispatch)
953 ;;;###autoload
954 (defun calc-dispatch (&optional arg)
955 "Invoke the GNU Emacs Calculator. See `calc-dispatch-help' for details."
956 (interactive "P")
957 (sit-for echo-keystrokes)
958 (condition-case err ; look for other keys bound to calc-dispatch
959 (let ((keys (this-command-keys)))
960 (or (not (stringp keys))
961 (string-match "\\`\C-u\\|\\`\e[-0-9#]\\|`[\M--\M-0-\M-9]" keys)
962 (eq (lookup-key calc-dispatch-map keys) 'calc-same-interface)
963 (progn
964 (and (string-match "\\`[\C-@-\C-_]" keys)
965 (symbolp
966 (lookup-key calc-dispatch-map (substring keys 0 1)))
967 (define-key calc-dispatch-map (substring keys 0 1) nil))
968 (define-key calc-dispatch-map keys 'calc-same-interface))))
969 (error nil))
970 (calc-do-dispatch arg))
972 (defvar calc-dispatch-help nil)
973 (defun calc-do-dispatch (arg)
974 (let ((key (calc-read-key-sequence
975 (if calc-dispatch-help
976 "Calc options: Calc, Keypad, Quick, Embed; eXit; Info, Tutorial; Grab; ?=more"
977 (format "%s (Type ? for a list of Calc options)"
978 (key-description (this-command-keys))))
979 calc-dispatch-map)))
980 (setq key (lookup-key calc-dispatch-map key))
981 (message "")
982 (if key
983 (progn
984 (or (commandp key) (calc-extensions))
985 (call-interactively key))
986 (beep))))
988 (defun calc-read-key-sequence (prompt map)
989 (let ((prompt2 (format "%s " (key-description (this-command-keys))))
990 (glob (current-global-map))
991 (loc (current-local-map)))
992 (or (input-pending-p) (message prompt))
993 (let ((key (calc-read-key t)))
994 (calc-unread-command (cdr key))
995 (unwind-protect
996 (progn
997 (use-global-map map)
998 (use-local-map nil)
999 (read-key-sequence
1000 (if (commandp (key-binding (if calc-emacs-type-19
1001 (vector (cdr key))
1002 (char-to-string (cdr key)))))
1003 "" prompt2)))
1004 (use-global-map glob)
1005 (use-local-map loc)))))
1009 (defun calc-mode ()
1010 "Calculator major mode.
1012 This is an RPN calculator featuring arbitrary-precision integer, rational,
1013 floating-point, complex, matrix, and symbolic arithmetic.
1015 RPN calculation: 2 RET 3 + produces 5.
1016 Algebraic style: ' 2+3 RET produces 5.
1018 Basic operators are +, -, *, /, ^, & (reciprocal), % (modulo), n (change-sign).
1020 Press ? repeatedly for more complete help. Press `h i' to read the
1021 Calc manual on-line, `h s' to read the summary, or `h t' for the tutorial.
1023 Notations: 3.14e6 3.14 * 10^6
1024 _23 negative number -23 (or type `23 n')
1025 17:3 the fraction 17/3
1026 5:2:3 the fraction 5 and 2/3
1027 16#12C the integer 12C base 16 = 300 base 10
1028 8#177:100 the fraction 177:100 base 8 = 127:64 base 10
1029 (2, 4) complex number 2 + 4i
1030 (2; 4) polar complex number (r; theta)
1031 [1, 2, 3] vector ([[1, 2], [3, 4]] is a matrix)
1032 [1 .. 4) semi-open interval, 1 <= x < 4
1033 2 +/- 3 (p key) number with mean 2, standard deviation 3
1034 2 mod 3 (M key) number 2 computed modulo 3
1035 <1 jan 91> Date form (enter using ' key)
1038 \\{calc-mode-map}
1040 (interactive)
1041 (mapcar (function
1042 (lambda (v) (set-default v (symbol-value v)))) calc-local-var-list)
1043 (kill-all-local-variables)
1044 (use-local-map (if (eq calc-algebraic-mode 'total)
1045 (progn (calc-extensions) calc-alg-map) calc-mode-map))
1046 (mapcar (function (lambda (v) (make-local-variable v))) calc-local-var-list)
1047 (make-local-variable 'overlay-arrow-position)
1048 (make-local-variable 'overlay-arrow-string)
1049 (setq truncate-lines t)
1050 (setq buffer-read-only t)
1051 (setq major-mode 'calc-mode)
1052 (setq mode-name "Calculator")
1053 (setq calc-stack-top (length (or (memq (assq 'top-of-stack calc-stack)
1054 calc-stack)
1055 (setq calc-stack (list (list 'top-of-stack
1056 1 nil))))))
1057 (setq calc-stack-top (- (length calc-stack) calc-stack-top -1))
1058 (or calc-loaded-settings-file
1059 (null calc-settings-file)
1060 (string-match "\\.emacs" calc-settings-file)
1061 (progn
1062 (setq calc-loaded-settings-file t)
1063 (load calc-settings-file t))) ; t = missing-ok
1064 (if (and (eq window-system 'x) (boundp 'mouse-map))
1065 (substitute-key-definition 'x-paste-text 'calc-x-paste-text
1066 mouse-map))
1067 (let ((p command-line-args))
1068 (while p
1069 (and (equal (car p) "-f")
1070 (string-match "calc" (nth 1 p))
1071 (string-match "full" (nth 1 p))
1072 (setq calc-standalone-flag t))
1073 (setq p (cdr p))))
1074 (run-hooks 'calc-mode-hook)
1075 (calc-refresh t)
1076 (calc-set-mode-line)
1077 ;; The calc-defs variable is a relic. Use calc-define properties instead.
1078 (if (and (boundp 'calc-defs)
1079 calc-defs)
1080 (progn
1081 (message "Evaluating calc-defs...")
1082 (calc-need-macros)
1083 (eval (cons 'progn calc-defs))
1084 (setq calc-defs nil)
1085 (calc-set-mode-line)))
1086 (calc-check-defines))
1088 (defvar calc-check-defines 'calc-check-defines) ; suitable for run-hooks
1089 (defun calc-check-defines ()
1090 (if (symbol-plist 'calc-define)
1091 (let ((plist (copy-sequence (symbol-plist 'calc-define))))
1092 (while (and plist (null (nth 1 plist)))
1093 (setq plist (cdr (cdr plist))))
1094 (if plist
1095 (save-excursion
1096 (calc-extensions)
1097 (calc-need-macros)
1098 (set-buffer "*Calculator*")
1099 (while plist
1100 (put 'calc-define (car plist) nil)
1101 (eval (nth 1 plist))
1102 (setq plist (cdr (cdr plist))))
1103 ;; See if this has added any more calc-define properties.
1104 (calc-check-defines))
1105 (setplist 'calc-define nil)))))
1107 (defun calc-trail-mode (&optional buf)
1108 "Calc Trail mode.
1109 This mode is used by the *Calc Trail* buffer, which records all results
1110 obtained by the GNU Emacs Calculator.
1112 Calculator commands beginning with the `t' key are used to manipulate
1113 the Trail.
1115 This buffer uses the same key map as the *Calculator* buffer; calculator
1116 commands given here will actually operate on the *Calculator* stack."
1117 (interactive)
1118 (fundamental-mode)
1119 (use-local-map calc-mode-map)
1120 (setq major-mode 'calc-trail-mode)
1121 (setq mode-name "Calc Trail")
1122 (setq truncate-lines t)
1123 (setq buffer-read-only t)
1124 (make-local-variable 'overlay-arrow-position)
1125 (make-local-variable 'overlay-arrow-string)
1126 (if buf
1127 (progn
1128 (make-local-variable 'calc-main-buffer)
1129 (setq calc-main-buffer buf)))
1130 (if (= (buffer-size) 0)
1131 (let ((buffer-read-only nil))
1132 (insert "Emacs Calculator v" calc-version " by Dave Gillespie\n")))
1133 (run-hooks 'calc-trail-mode-hook))
1135 (defun calc-create-buffer ()
1136 (set-buffer (get-buffer-create "*Calculator*"))
1137 (or (eq major-mode 'calc-mode)
1138 (calc-mode))
1139 (setq max-lisp-eval-depth (max max-lisp-eval-depth 1000))
1140 (if calc-always-load-extensions
1141 (calc-extensions))
1142 (if calc-language
1143 (progn
1144 (calc-extensions)
1145 (calc-set-language calc-language calc-language-option t))))
1147 ;;;###autoload
1148 (defun calc (&optional arg full-display interactive)
1149 "The Emacs Calculator. Full documentation is listed under \"calc-mode\"."
1150 (interactive "P")
1151 (if arg
1152 (or (eq arg 0)
1153 (progn
1154 (calc-extensions)
1155 (if (= (prefix-numeric-value arg) -1)
1156 (calc-grab-region (region-beginning) (region-end) nil)
1157 (if (= (prefix-numeric-value arg) -2)
1158 (calc-keypad)))))
1159 (if (get-buffer-window "*Calc Keypad*")
1160 (progn
1161 (calc-keypad)
1162 (set-buffer (window-buffer (selected-window)))))
1163 (if (eq major-mode 'calc-mode)
1164 (calc-quit)
1165 (let ((oldbuf (current-buffer)))
1166 (calc-create-buffer)
1167 (setq calc-was-keypad-mode nil)
1168 (if (or (eq full-display t)
1169 (and (null full-display) calc-full-mode))
1170 (switch-to-buffer (current-buffer) t)
1171 (if (get-buffer-window (current-buffer))
1172 (select-window (get-buffer-window (current-buffer)))
1173 (if (and (boundp 'calc-window-hook) calc-window-hook)
1174 (run-hooks 'calc-window-hook)
1175 (let ((w (get-largest-window)))
1176 (if (and pop-up-windows
1177 (> (window-height w)
1178 (+ window-min-height calc-window-height 2)))
1179 (progn
1180 (setq w (split-window w
1181 (- (window-height w)
1182 calc-window-height 2)
1183 nil))
1184 (set-window-buffer w (current-buffer))
1185 (select-window w))
1186 (pop-to-buffer (current-buffer)))))))
1187 (save-excursion
1188 (set-buffer (calc-trail-buffer))
1189 (and calc-display-trail
1190 (= (window-width) (frame-width))
1191 (calc-trail-display 1 t)))
1192 (message "Welcome to the GNU Emacs Calculator! Press `?' or `h' for help, `q' to quit")
1193 (run-hooks 'calc-start-hook)
1194 (and (windowp full-display)
1195 (window-point full-display)
1196 (select-window full-display))
1197 (calc-check-defines)
1198 (and calc-said-hello
1199 (or (interactive-p) interactive)
1200 (progn
1201 (sit-for 2)
1202 (message "")))
1203 (setq calc-said-hello t)))))
1205 ;;;###autoload
1206 (defun full-calc ()
1207 "Invoke the Calculator and give it a full-sized window."
1208 (interactive)
1209 (calc nil t (interactive-p)))
1211 (defun calc-same-interface (arg)
1212 "Invoke the Calculator using the most recent interface (calc or calc-keypad)."
1213 (interactive "P")
1214 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1215 (> (recursion-depth) 0))
1216 (exit-recursive-edit)
1217 (if (eq major-mode 'calc-edit-mode)
1218 (calc-edit-finish arg)
1219 (if (eq major-mode 'MacEdit-mode)
1220 (MacEdit-finish-edit)
1221 (if calc-was-keypad-mode
1222 (calc-keypad)
1223 (calc arg calc-full-mode t))))))
1226 (defun calc-quit (&optional non-fatal)
1227 (interactive)
1228 (and calc-standalone-flag (not non-fatal)
1229 (save-buffers-kill-emacs nil))
1230 (if (and (equal (buffer-name) "*Gnuplot Trail*")
1231 (> (recursion-depth) 0))
1232 (exit-recursive-edit))
1233 (if (eq major-mode 'calc-edit-mode)
1234 (calc-edit-cancel)
1235 (if (eq major-mode 'MacEdit-mode)
1236 (MacEdit-cancel-edit)
1237 (if (and (interactive-p)
1238 calc-embedded-info
1239 (eq (current-buffer) (aref calc-embedded-info 0)))
1240 (calc-embedded nil)
1241 (unless (eq major-mode 'calc-mode)
1242 (calc-create-buffer))
1243 (run-hooks 'calc-end-hook)
1244 (setq calc-undo-list nil calc-redo-list nil)
1245 (mapcar (function (lambda (v) (set-default v (symbol-value v))))
1246 calc-local-var-list)
1247 (let ((buf (current-buffer))
1248 (win (get-buffer-window (current-buffer)))
1249 (kbuf (get-buffer "*Calc Keypad*")))
1250 (delete-windows-on (calc-trail-buffer))
1251 (if (and win
1252 (< (window-height win) (1- (frame-height)))
1253 (= (window-width win) (frame-width)) ; avoid calc-keypad
1254 (not (get-buffer-window "*Calc Keypad*")))
1255 (setq calc-window-height (- (window-height win) 2)))
1256 (progn
1257 (delete-windows-on buf)
1258 (delete-windows-on kbuf))
1259 (bury-buffer buf)
1260 (bury-buffer calc-trail-buffer)
1261 (and kbuf (bury-buffer kbuf)))))))
1263 ;;;###autoload
1264 (defun quick-calc ()
1265 "Do a quick calculation in the minibuffer without invoking full Calculator."
1266 (interactive)
1267 (calc-do-quick-calc))
1269 ;;;###autoload
1270 (defun calc-eval (str &optional separator &rest args)
1271 "Do a quick calculation and return the result as a string.
1272 Return value will either be the formatted result in string form,
1273 or a list containing a character position and an error message in string form."
1274 (calc-do-calc-eval str separator args))
1276 ;;;###autoload
1277 (defun calc-keypad ()
1278 "Invoke the Calculator in \"visual keypad\" mode.
1279 This is most useful in the X window system.
1280 In this mode, click on the Calc \"buttons\" using the left mouse button.
1281 Or, position the cursor manually and do M-x calc-keypad-press."
1282 (interactive)
1283 (calc-extensions)
1284 (calc-do-keypad calc-full-mode (interactive-p)))
1286 ;;;###autoload
1287 (defun full-calc-keypad ()
1288 "Invoke the Calculator in full-screen \"visual keypad\" mode.
1289 See calc-keypad for details."
1290 (interactive)
1291 (calc-extensions)
1292 (calc-do-keypad t (interactive-p)))
1295 (defvar calc-aborted-prefix nil)
1296 (defvar calc-start-time nil)
1297 ;;; Note that modifications to this function may break calc-pass-errors.
1298 (defun calc-do (do-body &optional do-slow)
1299 (calc-check-defines)
1300 (let* ((calc-command-flags nil)
1301 (calc-start-time (and calc-timing (not calc-start-time)
1302 (calc-extensions)
1303 (current-time-string)))
1304 (gc-cons-threshold (max gc-cons-threshold
1305 (if calc-timing 2000000 100000))))
1306 (setq calc-aborted-prefix "")
1307 (unwind-protect
1308 (condition-case err
1309 (save-excursion
1310 (if calc-embedded-info
1311 (calc-embedded-select-buffer)
1312 (calc-select-buffer))
1313 (and (eq calc-algebraic-mode 'total)
1314 (calc-extensions)
1315 (use-local-map calc-alg-map))
1316 (when (and do-slow calc-display-working-message)
1317 (message "Working...")
1318 (calc-set-command-flag 'clear-message))
1319 (funcall do-body)
1320 (setq calc-aborted-prefix nil)
1321 (when (memq 'renum-stack calc-command-flags)
1322 (calc-renumber-stack))
1323 (when (memq 'clear-message calc-command-flags)
1324 (message "")))
1325 (error
1326 (if (and (eq (car err) 'error)
1327 (stringp (nth 1 err))
1328 (string-match "max-specpdl-size\\|max-lisp-eval-depth"
1329 (nth 1 err)))
1330 (error "Computation got stuck or ran too long. Type `M' to increase the limit")
1331 (setq calc-aborted-prefix nil)
1332 (signal (car err) (cdr err)))))
1333 (setq calc-old-aborted-prefix calc-aborted-prefix)
1334 (when calc-aborted-prefix
1335 (calc-record "<Aborted>" calc-aborted-prefix))
1336 (and calc-start-time
1337 (let* ((calc-internal-prec 12)
1338 (calc-date-format nil)
1339 (end-time (current-time-string))
1340 (time (if (equal calc-start-time end-time)
1342 (math-sub
1343 (calcFunc-unixtime (math-parse-date end-time) 0)
1344 (calcFunc-unixtime (math-parse-date calc-start-time)
1345 0)))))
1346 (if (math-lessp 1 time)
1347 (calc-record time "(t)"))))
1348 (or (memq 'no-align calc-command-flags)
1349 (eq major-mode 'calc-trail-mode)
1350 (calc-align-stack-window))
1351 (and (memq 'position-point calc-command-flags)
1352 (if (eq major-mode 'calc-mode)
1353 (progn
1354 (goto-line calc-final-point-line)
1355 (move-to-column calc-final-point-column))
1356 (save-excursion
1357 (calc-select-buffer)
1358 (goto-line calc-final-point-line)
1359 (move-to-column calc-final-point-column))))
1360 (unless (memq 'keep-flags calc-command-flags)
1361 (save-excursion
1362 (calc-select-buffer)
1363 (setq calc-inverse-flag nil
1364 calc-hyperbolic-flag nil
1365 calc-keep-args-flag nil)))
1366 (when (memq 'do-edit calc-command-flags)
1367 (switch-to-buffer (get-buffer-create "*Calc Edit*")))
1368 (calc-set-mode-line)
1369 (when calc-embedded-info
1370 (calc-embedded-finish-command))))
1371 (identity nil)) ; allow a GC after timing is done
1374 (defun calc-set-command-flag (f)
1375 (unless (memq f calc-command-flags)
1376 (setq calc-command-flags (cons f calc-command-flags))))
1378 (defun calc-select-buffer ()
1379 (or (eq major-mode 'calc-mode)
1380 (if calc-main-buffer
1381 (set-buffer calc-main-buffer)
1382 (let ((buf (get-buffer "*Calculator*")))
1383 (if buf
1384 (set-buffer buf)
1385 (error "Calculator buffer not available"))))))
1387 (defun calc-cursor-stack-index (&optional index)
1388 (goto-char (point-max))
1389 (forward-line (- (calc-substack-height (or index 1)))))
1391 (defun calc-stack-size ()
1392 (- (length calc-stack) calc-stack-top))
1394 (defun calc-substack-height (n)
1395 (let ((sum 0)
1396 (stack calc-stack))
1397 (setq n (+ n calc-stack-top))
1398 (while (and (> n 0) stack)
1399 (setq sum (+ sum (nth 1 (car stack)))
1400 n (1- n)
1401 stack (cdr stack)))
1402 sum))
1404 (defun calc-set-mode-line ()
1405 (save-excursion
1406 (calc-select-buffer)
1407 (let* ((fmt (car calc-float-format))
1408 (figs (nth 1 calc-float-format))
1409 (new-mode-string
1410 (format "Calc%s%s: %d %s %-14s"
1411 (if calc-embedded-info "Embed" "")
1412 (if (and (> (length (buffer-name)) 12)
1413 (equal (substring (buffer-name) 0 12)
1414 "*Calculator*"))
1415 (substring (buffer-name) 12)
1417 calc-internal-prec
1418 (capitalize (symbol-name calc-angle-mode))
1419 (concat
1421 ;; Input-related modes
1422 (if (eq calc-algebraic-mode 'total) "Alg* "
1423 (if calc-algebraic-mode "Alg "
1424 (if calc-incomplete-algebraic-mode "Alg[( " "")))
1426 ;; Computational modes
1427 (if calc-symbolic-mode "Symb " "")
1428 (cond ((eq calc-matrix-mode 'matrix) "Matrix ")
1429 ((integerp calc-matrix-mode)
1430 (format "Matrix%d " calc-matrix-mode))
1431 ((eq calc-matrix-mode 'scalar) "Scalar ")
1432 (t ""))
1433 (if (eq calc-complex-mode 'polar) "Polar " "")
1434 (if calc-prefer-frac "Frac " "")
1435 (cond ((null calc-infinite-mode) "")
1436 ((eq calc-infinite-mode 1) "+Inf ")
1437 (t "Inf "))
1438 (cond ((eq calc-simplify-mode 'none) "NoSimp ")
1439 ((eq calc-simplify-mode 'num) "NumSimp ")
1440 ((eq calc-simplify-mode 'binary)
1441 (format "BinSimp%d " calc-word-size))
1442 ((eq calc-simplify-mode 'alg) "AlgSimp ")
1443 ((eq calc-simplify-mode 'ext) "ExtSimp ")
1444 ((eq calc-simplify-mode 'units) "UnitSimp ")
1445 (t ""))
1447 ;; Display modes
1448 (cond ((= calc-number-radix 10) "")
1449 ((= calc-number-radix 2) "Bin ")
1450 ((= calc-number-radix 8) "Oct ")
1451 ((= calc-number-radix 16) "Hex ")
1452 (t (format "Radix%d " calc-number-radix)))
1453 (if calc-leading-zeros "Zero " "")
1454 (cond ((null calc-language) "")
1455 ((eq calc-language 'tex) "TeX ")
1456 (t (concat
1457 (capitalize (symbol-name calc-language))
1458 " ")))
1459 (cond ((eq fmt 'float)
1460 (if (zerop figs) "" (format "Norm%d " figs)))
1461 ((eq fmt 'fix) (format "Fix%d " figs))
1462 ((eq fmt 'sci)
1463 (if (zerop figs) "Sci " (format "Sci%d " figs)))
1464 ((eq fmt 'eng)
1465 (if (zerop figs) "Eng " (format "Eng%d " figs))))
1466 (cond ((not calc-display-just)
1467 (if calc-display-origin
1468 (format "Left%d " calc-display-origin) ""))
1469 ((eq calc-display-just 'right)
1470 (if calc-display-origin
1471 (format "Right%d " calc-display-origin)
1472 "Right "))
1474 (if calc-display-origin
1475 (format "Center%d " calc-display-origin)
1476 "Center ")))
1477 (cond ((integerp calc-line-breaking)
1478 (format "Wid%d " calc-line-breaking))
1479 (calc-line-breaking "")
1480 (t "Wide "))
1482 ;; Miscellaneous other modes/indicators
1483 (if calc-assoc-selections "" "Break ")
1484 (cond ((eq calc-mode-save-mode 'save) "Save ")
1485 ((not calc-embedded-info) "")
1486 ((eq calc-mode-save-mode 'local) "Local ")
1487 ((eq calc-mode-save-mode 'edit) "LocEdit ")
1488 ((eq calc-mode-save-mode 'perm) "LocPerm ")
1489 ((eq calc-mode-save-mode 'global) "Global ")
1490 (t ""))
1491 (if calc-auto-recompute "" "Manual ")
1492 (if (and (fboundp 'calc-gnuplot-alive)
1493 (calc-gnuplot-alive)) "Graph " "")
1494 (if (and calc-embedded-info
1495 (> (calc-stack-size) 0)
1496 (calc-top 1 'sel)) "Sel " "")
1497 (if calc-display-dirty "Dirty " "")
1498 (if calc-inverse-flag "Inv " "")
1499 (if calc-hyperbolic-flag "Hyp " "")
1500 (if calc-keep-args-flag "Keep " "")
1501 (if (/= calc-stack-top 1) "Narrow " "")
1502 (apply 'concat calc-other-modes)))))
1503 (if (equal new-mode-string mode-line-buffer-identification)
1505 (setq mode-line-buffer-identification new-mode-string)
1506 (set-buffer-modified-p (buffer-modified-p))
1507 (and calc-embedded-info (calc-embedded-mode-line-change))))))
1509 (defun calc-align-stack-window ()
1510 (if (eq major-mode 'calc-mode)
1511 (progn
1512 (let ((win (get-buffer-window (current-buffer))))
1513 (if win
1514 (progn
1515 (calc-cursor-stack-index 0)
1516 (vertical-motion (- 2 (window-height win)))
1517 (set-window-start win (point)))))
1518 (calc-cursor-stack-index 0)
1519 (if (looking-at " *\\.$")
1520 (goto-char (1- (match-end 0)))))
1521 (save-excursion
1522 (calc-select-buffer)
1523 (calc-align-stack-window))))
1525 (defun calc-check-stack (n)
1526 (if (> n (calc-stack-size))
1527 (error "Too few elements on stack"))
1528 (if (< n 0)
1529 (error "Invalid argument")))
1531 (defun calc-push-list (vals &optional m sels)
1532 (while vals
1533 (if calc-executing-macro
1534 (calc-push-list-in-macro vals m sels)
1535 (save-excursion
1536 (calc-select-buffer)
1537 (let* ((val (car vals))
1538 (entry (list val 1 (car sels)))
1539 (mm (+ (or m 1) calc-stack-top)))
1540 (calc-cursor-stack-index (1- (or m 1)))
1541 (if (> mm 1)
1542 (setcdr (nthcdr (- mm 2) calc-stack)
1543 (cons entry (nthcdr (1- mm) calc-stack)))
1544 (setq calc-stack (cons entry calc-stack)))
1545 (let ((buffer-read-only nil))
1546 (insert (math-format-stack-value entry) "\n"))
1547 (calc-record-undo (list 'push mm))
1548 (calc-set-command-flag 'renum-stack))))
1549 (setq vals (cdr vals)
1550 sels (cdr sels))))
1552 (defun calc-pop-push-list (n vals &optional m sels)
1553 (if (and calc-any-selections (null sels))
1554 (calc-replace-selections n vals m)
1555 (calc-pop-stack n m sels)
1556 (calc-push-list vals m sels)))
1558 (defun calc-pop-push-record-list (n prefix vals &optional m sels)
1559 (or (and (consp vals)
1560 (or (integerp (car vals))
1561 (consp (car vals))))
1562 (and vals (setq vals (list vals)
1563 sels (and sels (list sels)))))
1564 (calc-check-stack (+ n (or m 1) -1))
1565 (if prefix
1566 (if (cdr vals)
1567 (calc-record-list vals prefix)
1568 (calc-record (car vals) prefix)))
1569 (calc-pop-push-list n vals m sels))
1571 (defun calc-enter-result (n prefix vals &optional m)
1572 (setq calc-aborted-prefix prefix)
1573 (if (and (consp vals)
1574 (or (integerp (car vals))
1575 (consp (car vals))))
1576 (setq vals (mapcar 'calc-normalize vals))
1577 (setq vals (calc-normalize vals)))
1578 (or (and (consp vals)
1579 (or (integerp (car vals))
1580 (consp (car vals))))
1581 (setq vals (list vals)))
1582 (if (equal vals '((nil)))
1583 (setq vals nil))
1584 (calc-pop-push-record-list n prefix vals m)
1585 (calc-handle-whys))
1587 (defun calc-normalize (val)
1588 (if (memq calc-simplify-mode '(nil none num))
1589 (math-normalize val)
1590 (calc-extensions)
1591 (calc-normalize-fancy val)))
1593 (defun calc-handle-whys ()
1594 (if calc-next-why
1595 (calc-do-handle-whys)))
1598 (defun calc-pop-stack (&optional n m sel-ok) ; pop N objs at level M of stack.
1599 (or n (setq n 1))
1600 (or m (setq m 1))
1601 (or calc-keep-args-flag
1602 (let ((mm (+ m calc-stack-top)))
1603 (if (and calc-any-selections (not sel-ok)
1604 (calc-top-selected n m))
1605 (calc-sel-error))
1606 (if calc-executing-macro
1607 (calc-pop-stack-in-macro n mm)
1608 (calc-record-undo (list 'pop mm (calc-top-list n m 'full)))
1609 (save-excursion
1610 (calc-select-buffer)
1611 (let ((buffer-read-only nil))
1612 (if (> mm 1)
1613 (progn
1614 (calc-cursor-stack-index (1- m))
1615 (let ((bot (point)))
1616 (calc-cursor-stack-index (+ n m -1))
1617 (delete-region (point) bot))
1618 (setcdr (nthcdr (- mm 2) calc-stack)
1619 (nthcdr (+ n mm -1) calc-stack)))
1620 (calc-cursor-stack-index n)
1621 (setq calc-stack (nthcdr n calc-stack))
1622 (delete-region (point) (point-max))))
1623 (calc-set-command-flag 'renum-stack))))))
1625 (defun calc-get-stack-element (x)
1626 (cond ((eq sel-mode 'entry)
1628 ((eq sel-mode 'sel)
1629 (nth 2 x))
1630 ((or (null (nth 2 x))
1631 (eq sel-mode 'full)
1632 (not calc-use-selections))
1633 (car x))
1634 (sel-mode
1635 (calc-sel-error))
1636 (t (nth 2 x))))
1638 ;; Get the Nth element of the stack (N=1 is the top element).
1639 (defun calc-top (&optional n sel-mode)
1640 (or n (setq n 1))
1641 (calc-check-stack n)
1642 (calc-get-stack-element (nth (+ n calc-stack-top -1) calc-stack)))
1644 (defun calc-top-n (&optional n sel-mode) ; in case precision has changed
1645 (math-check-complete (calc-normalize (calc-top n sel-mode))))
1647 (defun calc-top-list (&optional n m sel-mode)
1648 (or n (setq n 1))
1649 (or m (setq m 1))
1650 (calc-check-stack (+ n m -1))
1651 (and (> n 0)
1652 (let ((top (copy-sequence (nthcdr (+ m calc-stack-top -1)
1653 calc-stack))))
1654 (setcdr (nthcdr (1- n) top) nil)
1655 (nreverse (mapcar 'calc-get-stack-element top)))))
1657 (defun calc-top-list-n (&optional n m sel-mode)
1658 (mapcar 'math-check-complete
1659 (mapcar 'calc-normalize (calc-top-list n m sel-mode))))
1662 (defun calc-renumber-stack ()
1663 (if calc-line-numbering
1664 (save-excursion
1665 (calc-cursor-stack-index 0)
1666 (let ((lnum 1)
1667 (buffer-read-only nil)
1668 (stack (nthcdr calc-stack-top calc-stack)))
1669 (if (re-search-forward "^[0-9]+[:*]" nil t)
1670 (progn
1671 (beginning-of-line)
1672 (while (re-search-forward "^[0-9]+[:*]" nil t)
1673 (let ((buffer-read-only nil))
1674 (beginning-of-line)
1675 (delete-char 4)
1676 (insert " ")))
1677 (calc-cursor-stack-index 0)))
1678 (while (re-search-backward "^[0-9]+[:*]" nil t)
1679 (delete-char 4)
1680 (if (> lnum 999)
1681 (insert (format "%03d%s" (% lnum 1000)
1682 (if (and (nth 2 (car stack))
1683 calc-use-selections) "*" ":")))
1684 (let ((prefix (int-to-string lnum)))
1685 (insert prefix (if (and (nth 2 (car stack))
1686 calc-use-selections) "*" ":")
1687 (make-string (- 3 (length prefix)) 32))))
1688 (beginning-of-line)
1689 (setq lnum (1+ lnum)
1690 stack (cdr stack))))))
1691 (and calc-embedded-info (calc-embedded-stack-change)))
1693 (defun calc-refresh (&optional align)
1694 (interactive)
1695 (and (eq major-mode 'calc-mode)
1696 (not calc-executing-macro)
1697 (let* ((buffer-read-only nil)
1698 (save-point (point))
1699 (save-mark (condition-case err (mark) (error nil)))
1700 (save-aligned (looking-at "\\.$"))
1701 (thing calc-stack))
1702 (setq calc-any-selections nil
1703 calc-any-evaltos nil)
1704 (erase-buffer)
1705 (insert "--- Emacs Calculator Mode ---\n")
1706 (while thing
1707 (goto-char (point-min))
1708 (forward-line 1)
1709 (insert (math-format-stack-value (car thing)) "\n")
1710 (setq thing (cdr thing)))
1711 (calc-renumber-stack)
1712 (if calc-display-dirty
1713 (calc-wrapper (setq calc-display-dirty nil)))
1714 (and calc-any-evaltos calc-auto-recompute
1715 (calc-wrapper (calc-refresh-evaltos)))
1716 (if (or align save-aligned)
1717 (calc-align-stack-window)
1718 (goto-char save-point))
1719 (if save-mark (set-mark save-mark))))
1720 (and calc-embedded-info (not (eq major-mode 'calc-mode))
1721 (save-excursion
1722 (set-buffer (aref calc-embedded-info 1))
1723 (calc-refresh align)))
1724 (setq calc-refresh-count (1+ calc-refresh-count)))
1727 (defun calc-x-paste-text (arg)
1728 "Move point to mouse position and insert window system cut buffer contents.
1729 If mouse is pressed in Calc window, push cut buffer contents onto the stack."
1730 (x-mouse-select arg)
1731 (if (memq major-mode '(calc-mode calc-trail-mode))
1732 (progn
1733 (calc-wrapper
1734 (calc-extensions)
1735 (let* ((buf (x-get-cut-buffer))
1736 (val (math-read-exprs (calc-clean-newlines buf))))
1737 (if (eq (car-safe val) 'error)
1738 (progn
1739 (setq val (math-read-exprs buf))
1740 (if (eq (car-safe val) 'error)
1741 (error "%s in yanked data" (nth 2 val)))))
1742 (calc-enter-result 0 "Xynk" val))))
1743 (x-paste-text arg)))
1747 ;;;; The Calc Trail buffer.
1749 (defun calc-check-trail-aligned ()
1750 (save-excursion
1751 (let ((win (get-buffer-window (current-buffer))))
1752 (and win
1753 (pos-visible-in-window-p (1- (point-max)) win)))))
1755 (defun calc-trail-buffer ()
1756 (and (or (null calc-trail-buffer)
1757 (null (buffer-name calc-trail-buffer)))
1758 (save-excursion
1759 (setq calc-trail-buffer (get-buffer-create "*Calc Trail*"))
1760 (let ((buf (or (and (not (eq major-mode 'calc-mode))
1761 (get-buffer "*Calculator*"))
1762 (current-buffer))))
1763 (set-buffer calc-trail-buffer)
1764 (or (eq major-mode 'calc-trail-mode)
1765 (calc-trail-mode buf)))))
1766 (or (and calc-trail-pointer
1767 (eq (marker-buffer calc-trail-pointer) calc-trail-buffer))
1768 (save-excursion
1769 (set-buffer calc-trail-buffer)
1770 (goto-line 2)
1771 (setq calc-trail-pointer (point-marker))))
1772 calc-trail-buffer)
1774 (defun calc-record (val &optional prefix)
1775 (setq calc-aborted-prefix nil)
1776 (or calc-executing-macro
1777 (let* ((mainbuf (current-buffer))
1778 (buf (calc-trail-buffer))
1779 (calc-display-raw nil)
1780 (calc-can-abbrev-vectors t)
1781 (fval (if val
1782 (if (stringp val)
1784 (math-showing-full-precision
1785 (math-format-flat-expr val 0)))
1786 "")))
1787 (save-excursion
1788 (set-buffer buf)
1789 (let ((aligned (calc-check-trail-aligned))
1790 (buffer-read-only nil))
1791 (goto-char (point-max))
1792 (cond ((null prefix) (insert " "))
1793 ((and (> (length prefix) 4)
1794 (string-match " " prefix 4))
1795 (insert (substring prefix 0 4) " "))
1796 (t (insert (format "%4s " prefix))))
1797 (insert fval "\n")
1798 (let ((win (get-buffer-window buf)))
1799 (if (and aligned win (not (memq 'hold-trail calc-command-flags)))
1800 (calc-trail-here))
1801 (goto-char (1- (point-max))))))))
1802 val)
1805 (defun calc-trail-display (flag &optional no-refresh)
1806 (interactive "P")
1807 (let ((win (get-buffer-window (calc-trail-buffer))))
1808 (if (setq calc-display-trail
1809 (not (if flag (memq flag '(nil 0)) win)))
1810 (if (null win)
1811 (progn
1812 (if (and (boundp 'calc-trail-window-hook) calc-trail-window-hook)
1813 (run-hooks 'calc-trail-window-hook)
1814 (let ((w (split-window nil (/ (* (window-width) 2) 3) t)))
1815 (set-window-buffer w calc-trail-buffer)))
1816 (calc-wrapper
1817 (setq overlay-arrow-string calc-trail-overlay
1818 overlay-arrow-position calc-trail-pointer)
1819 (or no-refresh
1820 (if (interactive-p)
1821 (calc-do-refresh)
1822 (calc-refresh))))))
1823 (if win
1824 (progn
1825 (delete-window win)
1826 (calc-wrapper
1827 (or no-refresh
1828 (if (interactive-p)
1829 (calc-do-refresh)
1830 (calc-refresh))))))))
1831 calc-trail-buffer)
1833 (defun calc-trail-here ()
1834 (interactive)
1835 (if (eq major-mode 'calc-trail-mode)
1836 (progn
1837 (beginning-of-line)
1838 (if (bobp)
1839 (forward-line 1)
1840 (if (eobp)
1841 (forward-line -1)))
1842 (if (or (bobp) (eobp))
1843 (setq overlay-arrow-position nil) ; trail is empty
1844 (set-marker calc-trail-pointer (point) (current-buffer))
1845 (setq calc-trail-overlay (concat (buffer-substring (point)
1846 (+ (point) 4))
1847 ">")
1848 overlay-arrow-string calc-trail-overlay
1849 overlay-arrow-position calc-trail-pointer)
1850 (forward-char 4)
1851 (let ((win (get-buffer-window (current-buffer))))
1852 (if win
1853 (save-excursion
1854 (forward-line (/ (window-height win) 2))
1855 (forward-line (- 1 (window-height win)))
1856 (set-window-start win (point))
1857 (set-window-point win (+ calc-trail-pointer 4))
1858 (set-buffer calc-main-buffer)
1859 (setq overlay-arrow-string calc-trail-overlay
1860 overlay-arrow-position calc-trail-pointer))))))
1861 (error "Not in Calc Trail buffer")))
1866 ;;;; The Undo list.
1868 (defun calc-record-undo (rec)
1869 (or calc-executing-macro
1870 (if (memq 'undo calc-command-flags)
1871 (setq calc-undo-list (cons (cons rec (car calc-undo-list))
1872 (cdr calc-undo-list)))
1873 (setq calc-undo-list (cons (list rec) calc-undo-list)
1874 calc-redo-list nil)
1875 (calc-set-command-flag 'undo))))
1880 ;;; Arithmetic commands.
1882 (defun calc-binary-op (name func arg &optional ident unary func2)
1883 (setq calc-aborted-prefix name)
1884 (if (null arg)
1885 (calc-enter-result 2 name (cons (or func2 func)
1886 (mapcar 'math-check-complete
1887 (calc-top-list 2))))
1888 (calc-extensions)
1889 (calc-binary-op-fancy name func arg ident unary)))
1891 (defun calc-unary-op (name func arg &optional func2)
1892 (setq calc-aborted-prefix name)
1893 (if (null arg)
1894 (calc-enter-result 1 name (list (or func2 func)
1895 (math-check-complete (calc-top 1))))
1896 (calc-extensions)
1897 (calc-unary-op-fancy name func arg)))
1900 (defun calc-plus (arg)
1901 (interactive "P")
1902 (calc-slow-wrapper
1903 (calc-binary-op "+" 'calcFunc-add arg 0 nil '+)))
1905 (defun calc-minus (arg)
1906 (interactive "P")
1907 (calc-slow-wrapper
1908 (calc-binary-op "-" 'calcFunc-sub arg 0 'neg '-)))
1910 (defun calc-times (arg)
1911 (interactive "P")
1912 (calc-slow-wrapper
1913 (calc-binary-op "*" 'calcFunc-mul arg 1 nil '*)))
1915 (defun calc-divide (arg)
1916 (interactive "P")
1917 (calc-slow-wrapper
1918 (calc-binary-op "/" 'calcFunc-div arg 0 'calcFunc-inv '/)))
1921 (defun calc-change-sign (arg)
1922 (interactive "P")
1923 (calc-wrapper
1924 (calc-unary-op "chs" 'neg arg)))
1928 ;;; Stack management commands.
1930 (defun calc-enter (n)
1931 (interactive "p")
1932 (calc-wrapper
1933 (cond ((< n 0)
1934 (calc-push-list (calc-top-list 1 (- n))))
1935 ((= n 0)
1936 (calc-push-list (calc-top-list (calc-stack-size))))
1938 (calc-push-list (calc-top-list n))))))
1941 (defun calc-pop (n)
1942 (interactive "P")
1943 (calc-wrapper
1944 (let* ((nn (prefix-numeric-value n))
1945 (top (and (null n) (calc-top 1))))
1946 (cond ((and (null n)
1947 (eq (car-safe top) 'incomplete)
1948 (> (length top) (if (eq (nth 1 top) 'intv) 3 2)))
1949 (calc-pop-push-list 1 (let ((tt (copy-sequence top)))
1950 (setcdr (nthcdr (- (length tt) 2) tt) nil)
1951 (list tt))))
1952 ((< nn 0)
1953 (if (and calc-any-selections
1954 (calc-top-selected 1 (- nn)))
1955 (calc-delete-selection (- nn))
1956 (calc-pop-stack 1 (- nn) t)))
1957 ((= nn 0)
1958 (calc-pop-stack (calc-stack-size) 1 t))
1960 (if (and calc-any-selections
1961 (= nn 1)
1962 (calc-top-selected 1 1))
1963 (calc-delete-selection 1)
1964 (calc-pop-stack nn)))))))
1969 ;;;; Reading a number using the minibuffer.
1971 (defun calcDigit-start ()
1972 (interactive)
1973 (calc-wrapper
1974 (if (or calc-algebraic-mode
1975 (and (> calc-number-radix 14) (eq last-command-char ?e)))
1976 (calc-alg-digit-entry)
1977 (calc-unread-command)
1978 (setq calc-aborted-prefix nil)
1979 (let* ((calc-digit-value nil)
1980 (calc-prev-char nil)
1981 (calc-prev-prev-char nil)
1982 (calc-buffer (current-buffer))
1983 (buf (if calc-emacs-type-lucid
1984 (catch 'calc-foo
1985 (catch 'execute-kbd-macro
1986 (throw 'calc-foo
1987 (read-from-minibuffer
1988 "Calc: " "" calc-digit-map)))
1989 (error "Lucid Emacs requires RET after %s"
1990 "digit entry in kbd macro"))
1991 (let ((old-esc (lookup-key global-map "\e")))
1992 (unwind-protect
1993 (progn
1994 (define-key global-map "\e" nil)
1995 (read-from-minibuffer "Calc: " "" calc-digit-map))
1996 (define-key global-map "\e" old-esc))))))
1997 (or calc-digit-value (setq calc-digit-value (math-read-number buf)))
1998 (if (stringp calc-digit-value)
1999 (calc-alg-entry calc-digit-value)
2000 (if calc-digit-value
2001 (calc-push-list (list (calc-record (calc-normalize
2002 calc-digit-value))))))
2003 (if (eq calc-prev-char 'dots)
2004 (progn
2005 (calc-extensions)
2006 (calc-dots)))))))
2008 (defsubst calc-minibuffer-size ()
2009 (- (point-max) (minibuffer-prompt-end)))
2011 (defun calcDigit-nondigit ()
2012 (interactive)
2013 ;; Exercise for the reader: Figure out why this is a good precaution!
2014 (or (boundp 'calc-buffer)
2015 (use-local-map minibuffer-local-map))
2016 (let ((str (minibuffer-contents)))
2017 (setq calc-digit-value (save-excursion
2018 (set-buffer calc-buffer)
2019 (math-read-number str))))
2020 (if (and (null calc-digit-value) (> (calc-minibuffer-size) 0))
2021 (progn
2022 (beep)
2023 (calc-temp-minibuffer-message " [Bad format]"))
2024 (or (memq last-command-char '(32 13))
2025 (progn (setq prefix-arg current-prefix-arg)
2026 (calc-unread-command (if (and (eq last-command-char 27)
2027 (>= last-input-char 128))
2028 last-input-char
2029 nil))))
2030 (exit-minibuffer)))
2033 (defun calc-minibuffer-contains (rex)
2034 (save-excursion
2035 (goto-char (minibuffer-prompt-end))
2036 (looking-at rex)))
2038 (defun calcDigit-key ()
2039 (interactive)
2040 (goto-char (point-max))
2041 (if (or (and (memq last-command-char '(?+ ?-))
2042 (> (buffer-size) 0)
2043 (/= (preceding-char) ?e))
2044 (and (memq last-command-char '(?m ?s))
2045 (not (calc-minibuffer-contains "[-+]?[0-9]+\\.?0*[@oh].*"))
2046 (not (calc-minibuffer-contains "[-+]?\\(1[1-9]\\|[2-9][0-9]\\)#.*"))))
2047 (calcDigit-nondigit)
2048 (if (calc-minibuffer-contains "\\([-+]?\\|.* \\)\\'")
2049 (cond ((memq last-command-char '(?. ?@)) (insert "0"))
2050 ((and (memq last-command-char '(?o ?h ?m))
2051 (not (calc-minibuffer-contains ".*#.*"))) (insert "0"))
2052 ((memq last-command-char '(?: ?e)) (insert "1"))
2053 ((eq last-command-char ?#)
2054 (insert (int-to-string calc-number-radix)))))
2055 (if (and (calc-minibuffer-contains "\\([-+]?[0-9]+#\\|[^:]*:\\)\\'")
2056 (eq last-command-char ?:))
2057 (insert "1"))
2058 (if (and (calc-minibuffer-contains "[-+]?[0-9]+#\\'")
2059 (eq last-command-char ?.))
2060 (insert "0"))
2061 (if (and (calc-minibuffer-contains "[-+]?0*\\([2-9]\\|1[0-4]\\)#\\'")
2062 (eq last-command-char ?e))
2063 (insert "1"))
2064 (if (or (and (memq last-command-char '(?h ?o ?m ?s ?p))
2065 (calc-minibuffer-contains ".*#.*"))
2066 (and (eq last-command-char ?e)
2067 (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2068 (and (eq last-command-char ?n)
2069 (calc-minibuffer-contains "[-+]?\\(2[4-9]\\|[3-9][0-9]\\)#.*")))
2070 (setq last-command-char (upcase last-command-char)))
2071 (cond
2072 ((memq last-command-char '(?_ ?n))
2073 (goto-char (minibuffer-prompt-end))
2074 (if (and (search-forward " +/- " nil t)
2075 (not (search-forward "e" nil t)))
2076 (beep)
2077 (and (not (calc-minibuffer-contains "[-+]?\\(1[5-9]\\|[2-9][0-9]\\)#.*"))
2078 (search-forward "e" nil t))
2079 (if (looking-at "+")
2080 (delete-char 1))
2081 (if (looking-at "-")
2082 (delete-char 1)
2083 (insert "-")))
2084 (goto-char (point-max)))
2085 ((eq last-command-char ?p)
2086 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2087 (calc-minibuffer-contains ".*mod.*")
2088 (calc-minibuffer-contains ".*#.*")
2089 (calc-minibuffer-contains ".*[-+e:]\\'"))
2090 (beep)
2091 (if (not (calc-minibuffer-contains ".* \\'"))
2092 (insert " "))
2093 (insert "+/- ")))
2094 ((and (eq last-command-char ?M)
2095 (not (calc-minibuffer-contains
2096 "[-+]?\\(2[3-9]\\|[3-9][0-9]\\)#.*")))
2097 (if (or (calc-minibuffer-contains ".*\\+/-.*")
2098 (calc-minibuffer-contains ".*mod *[^ ]+")
2099 (calc-minibuffer-contains ".*[-+e:]\\'"))
2100 (beep)
2101 (if (calc-minibuffer-contains ".*mod \\'")
2102 (if calc-previous-modulo
2103 (insert (math-format-flat-expr calc-previous-modulo 0))
2104 (beep))
2105 (if (not (calc-minibuffer-contains ".* \\'"))
2106 (insert " "))
2107 (insert "mod "))))
2109 (insert (char-to-string last-command-char))
2110 (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]*\\)?\\)?\\'")
2111 (let ((radix (string-to-int
2112 (buffer-substring
2113 (match-beginning 2) (match-end 2)))))
2114 (and (>= radix 2)
2115 (<= radix 36)
2116 (or (memq last-command-char '(?# ?: ?. ?e ?+ ?-))
2117 (let ((dig (math-read-radix-digit
2118 (upcase last-command-char))))
2119 (and dig
2120 (< dig radix)))))))
2121 (calc-minibuffer-contains
2122 "[-+]?\\(.*\\+/- *\\|.*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]?\\'"))
2123 (if (and (memq last-command-char '(?@ ?o ?h ?\' ?m))
2124 (string-match " " calc-hms-format))
2125 (insert " "))
2126 (if (and (eq this-command last-command)
2127 (eq last-command-char ?.))
2128 (progn
2129 (calc-extensions)
2130 (calc-digit-dots))
2131 (delete-backward-char 1)
2132 (beep)
2133 (calc-temp-minibuffer-message " [Bad format]"))))))
2134 (setq calc-prev-prev-char calc-prev-char
2135 calc-prev-char last-command-char))
2138 (defun calcDigit-backspace ()
2139 (interactive)
2140 (goto-char (point-max))
2141 (cond ((calc-minibuffer-contains ".* \\+/- \\'")
2142 (backward-delete-char 5))
2143 ((calc-minibuffer-contains ".* mod \\'")
2144 (backward-delete-char 5))
2145 ((calc-minibuffer-contains ".* \\'")
2146 (backward-delete-char 2))
2147 ((eq last-command 'calcDigit-start)
2148 (erase-buffer))
2149 (t (backward-delete-char 1)))
2150 (if (= (calc-minibuffer-size) 0)
2151 (progn
2152 (setq last-command-char 13)
2153 (calcDigit-nondigit))))
2161 ;;;; Arithmetic routines.
2163 ;;; An object as manipulated by one of these routines may take any of the
2164 ;;; following forms:
2166 ;;; integer An integer. For normalized numbers, this format
2167 ;;; is used only for -999999 ... 999999.
2169 ;;; (bigpos N0 N1 N2 ...) A big positive integer, N0 + N1*1000 + N2*10^6 ...
2170 ;;; (bigneg N0 N1 N2 ...) A big negative integer, - N0 - N1*1000 ...
2171 ;;; Each digit N is in the range 0 ... 999.
2172 ;;; Normalized, always at least three N present,
2173 ;;; and the most significant N is nonzero.
2175 ;;; (frac NUM DEN) A fraction. NUM and DEN are small or big integers.
2176 ;;; Normalized, DEN > 1.
2178 ;;; (float NUM EXP) A floating-point number, NUM * 10^EXP;
2179 ;;; NUM is a small or big integer, EXP is a small int.
2180 ;;; Normalized, NUM is not a multiple of 10, and
2181 ;;; abs(NUM) < 10^calc-internal-prec.
2182 ;;; Normalized zero is stored as (float 0 0).
2184 ;;; (cplx REAL IMAG) A complex number; REAL and IMAG are any of above.
2185 ;;; Normalized, IMAG is nonzero.
2187 ;;; (polar R THETA) Polar complex number. Normalized, R > 0 and THETA
2188 ;;; is neither zero nor 180 degrees (pi radians).
2190 ;;; (vec A B C ...) Vector of objects A, B, C, ... A matrix is a
2191 ;;; vector of vectors.
2193 ;;; (hms H M S) Angle in hours-minutes-seconds form. All three
2194 ;;; components have the same sign; H and M must be
2195 ;;; numerically integers; M and S are expected to
2196 ;;; lie in the range [0,60).
2198 ;;; (date N) A date or date/time object. N is an integer to
2199 ;;; store a date only, or a fraction or float to
2200 ;;; store a date and time.
2202 ;;; (sdev X SIGMA) Error form, X +/- SIGMA. When normalized,
2203 ;;; SIGMA > 0. X is any complex number and SIGMA
2204 ;;; is real numbers; or these may be symbolic
2205 ;;; expressions where SIGMA is assumed real.
2207 ;;; (intv MASK LO HI) Interval form. MASK is 0=(), 1=(], 2=[), or 3=[].
2208 ;;; LO and HI are any real numbers, or symbolic
2209 ;;; expressions which are assumed real, and LO < HI.
2210 ;;; For [LO..HI], if LO = HI normalization produces LO,
2211 ;;; and if LO > HI normalization produces [LO..LO).
2212 ;;; For other intervals, if LO > HI normalization
2213 ;;; sets HI equal to LO.
2215 ;;; (mod N M) Number modulo M. When normalized, 0 <= N < M.
2216 ;;; N and M are real numbers.
2218 ;;; (var V S) Symbolic variable. V is a Lisp symbol which
2219 ;;; represents the variable's visible name. S is
2220 ;;; the symbol which actually stores the variable's
2221 ;;; value: (var pi var-pi).
2223 ;;; In general, combining rational numbers in a calculation always produces
2224 ;;; a rational result, but if either argument is a float, result is a float.
2226 ;;; In the following comments, [x y z] means result is x, args must be y, z,
2227 ;;; respectively, where the code letters are:
2229 ;;; O Normalized object (vector or number)
2230 ;;; V Normalized vector
2231 ;;; N Normalized number of any type
2232 ;;; N Normalized complex number
2233 ;;; R Normalized real number (float or rational)
2234 ;;; F Normalized floating-point number
2235 ;;; T Normalized rational number
2236 ;;; I Normalized integer
2237 ;;; B Normalized big integer
2238 ;;; S Normalized small integer
2239 ;;; D Digit (small integer, 0..999)
2240 ;;; L Normalized bignum digit list (without "bigpos" or "bigneg" symbol)
2241 ;;; or normalized vector element list (without "vec")
2242 ;;; P Predicate (truth value)
2243 ;;; X Any Lisp object
2244 ;;; Z "nil"
2246 ;;; Lower-case letters signify possibly un-normalized values.
2247 ;;; "L.D" means a cons of an L and a D.
2248 ;;; [N N; n n] means result will be normalized if argument is.
2249 ;;; Also, [Public] marks routines intended to be called from outside.
2250 ;;; [This notation has been neglected in many recent routines.]
2252 ;;; Reduce an object to canonical (normalized) form. [O o; Z Z] [Public]
2253 (defun math-normalize (a)
2254 (cond
2255 ((not (consp a))
2256 (if (integerp a)
2257 (if (or (>= a 1000000) (<= a -1000000))
2258 (math-bignum a)
2261 ((eq (car a) 'bigpos)
2262 (if (eq (nth (1- (length a)) a) 0)
2263 (let* ((last (setq a (copy-sequence a))) (digs a))
2264 (while (setq digs (cdr digs))
2265 (or (eq (car digs) 0) (setq last digs)))
2266 (setcdr last nil)))
2267 (if (cdr (cdr (cdr a)))
2269 (cond
2270 ((cdr (cdr a)) (+ (nth 1 a) (* (nth 2 a) 1000)))
2271 ((cdr a) (nth 1 a))
2272 (t 0))))
2273 ((eq (car a) 'bigneg)
2274 (if (eq (nth (1- (length a)) a) 0)
2275 (let* ((last (setq a (copy-sequence a))) (digs a))
2276 (while (setq digs (cdr digs))
2277 (or (eq (car digs) 0) (setq last digs)))
2278 (setcdr last nil)))
2279 (if (cdr (cdr (cdr a)))
2281 (cond
2282 ((cdr (cdr a)) (- (+ (nth 1 a) (* (nth 2 a) 1000))))
2283 ((cdr a) (- (nth 1 a)))
2284 (t 0))))
2285 ((eq (car a) 'float)
2286 (math-make-float (math-normalize (nth 1 a)) (nth 2 a)))
2287 ((or (memq (car a) '(frac cplx polar hms date mod sdev intv vec var quote
2288 special-const calcFunc-if calcFunc-lambda
2289 calcFunc-quote calcFunc-condition
2290 calcFunc-evalto))
2291 (integerp (car a))
2292 (and (consp (car a)) (not (eq (car (car a)) 'lambda))))
2293 (calc-extensions)
2294 (math-normalize-fancy a))
2296 (or (and calc-simplify-mode
2297 (calc-extensions)
2298 (math-normalize-nonstandard))
2299 (let ((args (mapcar 'math-normalize (cdr a))))
2300 (or (condition-case err
2301 (let ((func (assq (car a) '( ( + . math-add )
2302 ( - . math-sub )
2303 ( * . math-mul )
2304 ( / . math-div )
2305 ( % . math-mod )
2306 ( ^ . math-pow )
2307 ( neg . math-neg )
2308 ( | . math-concat ) ))))
2309 (or (and var-EvalRules
2310 (progn
2311 (or (eq var-EvalRules math-eval-rules-cache-tag)
2312 (progn
2313 (calc-extensions)
2314 (math-recompile-eval-rules)))
2315 (and (or math-eval-rules-cache-other
2316 (assq (car a) math-eval-rules-cache))
2317 (math-apply-rewrites
2318 (cons (car a) args)
2319 (cdr math-eval-rules-cache)
2320 nil math-eval-rules-cache))))
2321 (if func
2322 (apply (cdr func) args)
2323 (and (or (consp (car a))
2324 (fboundp (car a))
2325 (and (not calc-extensions-loaded)
2326 (calc-extensions)
2327 (fboundp (car a))))
2328 (apply (car a) args)))))
2329 (wrong-number-of-arguments
2330 (calc-record-why "*Wrong number of arguments"
2331 (cons (car a) args))
2332 nil)
2333 (wrong-type-argument
2334 (or calc-next-why (calc-record-why "Wrong type of argument"
2335 (cons (car a) args)))
2336 nil)
2337 (args-out-of-range
2338 (calc-record-why "*Argument out of range" (cons (car a) args))
2339 nil)
2340 (inexact-result
2341 (calc-record-why "No exact representation for result"
2342 (cons (car a) args))
2343 nil)
2344 (math-overflow
2345 (calc-record-why "*Floating-point overflow occurred"
2346 (cons (car a) args))
2347 nil)
2348 (math-underflow
2349 (calc-record-why "*Floating-point underflow occurred"
2350 (cons (car a) args))
2351 nil)
2352 (void-variable
2353 (if (eq (nth 1 err) 'var-EvalRules)
2354 (progn
2355 (setq var-EvalRules nil)
2356 (math-normalize (cons (car a) args)))
2357 (calc-record-why "*Variable is void" (nth 1 err)))))
2358 (if (consp (car a))
2359 (math-dimension-error)
2360 (cons (car a) args))))))))
2364 ;;; True if A is a floating-point real or complex number. [P x] [Public]
2365 (defun math-floatp (a)
2366 (cond ((eq (car-safe a) 'float) t)
2367 ((memq (car-safe a) '(cplx polar mod sdev intv))
2368 (or (math-floatp (nth 1 a))
2369 (math-floatp (nth 2 a))
2370 (and (eq (car a) 'intv) (math-floatp (nth 3 a)))))
2371 ((eq (car-safe a) 'date)
2372 (math-floatp (nth 1 a)))))
2376 ;;; Verify that A is a complete object and return A. [x x] [Public]
2377 (defun math-check-complete (a)
2378 (cond ((integerp a) a)
2379 ((eq (car-safe a) 'incomplete)
2380 (calc-incomplete-error a))
2381 ((consp a) a)
2382 (t (error "Invalid data object encountered"))))
2386 ;;; Coerce integer A to be a bignum. [B S]
2387 (defun math-bignum (a)
2388 (if (>= a 0)
2389 (cons 'bigpos (math-bignum-big a))
2390 (cons 'bigneg (math-bignum-big (- a)))))
2392 (defun math-bignum-big (a) ; [L s]
2393 (if (= a 0)
2395 (cons (% a 1000) (math-bignum-big (/ a 1000)))))
2398 ;;; Build a normalized floating-point number. [F I S]
2399 (defun math-make-float (mant exp)
2400 (if (eq mant 0)
2401 '(float 0 0)
2402 (let* ((ldiff (- calc-internal-prec (math-numdigs mant))))
2403 (if (< ldiff 0)
2404 (setq mant (math-scale-rounding mant ldiff)
2405 exp (- exp ldiff))))
2406 (if (consp mant)
2407 (let ((digs (cdr mant)))
2408 (if (= (% (car digs) 10) 0)
2409 (progn
2410 (while (= (car digs) 0)
2411 (setq digs (cdr digs)
2412 exp (+ exp 3)))
2413 (while (= (% (car digs) 10) 0)
2414 (setq digs (math-div10-bignum digs)
2415 exp (1+ exp)))
2416 (setq mant (math-normalize (cons (car mant) digs))))))
2417 (while (= (% mant 10) 0)
2418 (setq mant (/ mant 10)
2419 exp (1+ exp))))
2420 (if (and (<= exp -4000000)
2421 (<= (+ exp (math-numdigs mant) -1) -4000000))
2422 (signal 'math-underflow nil)
2423 (if (and (>= exp 3000000)
2424 (>= (+ exp (math-numdigs mant) -1) 4000000))
2425 (signal 'math-overflow nil)
2426 (list 'float mant exp)))))
2428 (defun math-div10-bignum (a) ; [l l]
2429 (if (cdr a)
2430 (cons (+ (/ (car a) 10) (* (% (nth 1 a) 10) 100))
2431 (math-div10-bignum (cdr a)))
2432 (list (/ (car a) 10))))
2434 ;;; Coerce A to be a float. [F N; V V] [Public]
2435 (defun math-float (a)
2436 (cond ((Math-integerp a) (math-make-float a 0))
2437 ((eq (car a) 'frac) (math-div (math-float (nth 1 a)) (nth 2 a)))
2438 ((eq (car a) 'float) a)
2439 ((memq (car a) '(cplx polar vec hms date sdev mod))
2440 (cons (car a) (mapcar 'math-float (cdr a))))
2441 (t (math-float-fancy a))))
2444 (defun math-neg (a)
2445 (cond ((not (consp a)) (- a))
2446 ((eq (car a) 'bigpos) (cons 'bigneg (cdr a)))
2447 ((eq (car a) 'bigneg) (cons 'bigpos (cdr a)))
2448 ((memq (car a) '(frac float))
2449 (list (car a) (Math-integer-neg (nth 1 a)) (nth 2 a)))
2450 ((memq (car a) '(cplx vec hms date calcFunc-idn))
2451 (cons (car a) (mapcar 'math-neg (cdr a))))
2452 (t (math-neg-fancy a))))
2455 ;;; Compute the number of decimal digits in integer A. [S I]
2456 (defun math-numdigs (a)
2457 (if (consp a)
2458 (if (cdr a)
2459 (let* ((len (1- (length a)))
2460 (top (nth len a)))
2461 (+ (* len 3) (cond ((>= top 100) 0) ((>= top 10) -1) (t -2))))
2463 (cond ((>= a 100) (+ (math-numdigs (/ a 1000)) 3))
2464 ((>= a 10) 2)
2465 ((>= a 1) 1)
2466 ((= a 0) 0)
2467 ((> a -10) 1)
2468 ((> a -100) 2)
2469 (t (math-numdigs (- a))))))
2471 ;;; Multiply (with truncation toward 0) the integer A by 10^N. [I i S]
2472 (defun math-scale-int (a n)
2473 (cond ((= n 0) a)
2474 ((> n 0) (math-scale-left a n))
2475 (t (math-normalize (math-scale-right a (- n))))))
2477 (defun math-scale-left (a n) ; [I I S]
2478 (if (= n 0)
2480 (if (consp a)
2481 (cons (car a) (math-scale-left-bignum (cdr a) n))
2482 (if (>= n 3)
2483 (if (or (>= a 1000) (<= a -1000))
2484 (math-scale-left (math-bignum a) n)
2485 (math-scale-left (* a 1000) (- n 3)))
2486 (if (= n 2)
2487 (if (or (>= a 10000) (<= a -10000))
2488 (math-scale-left (math-bignum a) 2)
2489 (* a 100))
2490 (if (or (>= a 100000) (<= a -100000))
2491 (math-scale-left (math-bignum a) 1)
2492 (* a 10)))))))
2494 (defun math-scale-left-bignum (a n)
2495 (if (>= n 3)
2496 (while (>= (setq a (cons 0 a)
2497 n (- n 3)) 3)))
2498 (if (> n 0)
2499 (math-mul-bignum-digit a (if (= n 2) 100 10) 0)
2502 (defun math-scale-right (a n) ; [i i S]
2503 (if (= n 0)
2505 (if (consp a)
2506 (cons (car a) (math-scale-right-bignum (cdr a) n))
2507 (if (<= a 0)
2508 (if (= a 0)
2510 (- (math-scale-right (- a) n)))
2511 (if (>= n 3)
2512 (while (and (> (setq a (/ a 1000)) 0)
2513 (>= (setq n (- n 3)) 3))))
2514 (if (= n 2)
2515 (/ a 100)
2516 (if (= n 1)
2517 (/ a 10)
2518 a))))))
2520 (defun math-scale-right-bignum (a n) ; [L L S; l l S]
2521 (if (>= n 3)
2522 (setq a (nthcdr (/ n 3) a)
2523 n (% n 3)))
2524 (if (> n 0)
2525 (cdr (math-mul-bignum-digit a (if (= n 2) 10 100) 0))
2528 ;;; Multiply (with rounding) the integer A by 10^N. [I i S]
2529 (defun math-scale-rounding (a n)
2530 (cond ((>= n 0)
2531 (math-scale-left a n))
2532 ((consp a)
2533 (math-normalize
2534 (cons (car a)
2535 (let ((val (if (< n -3)
2536 (math-scale-right-bignum (cdr a) (- -3 n))
2537 (if (= n -2)
2538 (math-mul-bignum-digit (cdr a) 10 0)
2539 (if (= n -1)
2540 (math-mul-bignum-digit (cdr a) 100 0)
2541 (cdr a)))))) ; n = -3
2542 (if (and val (>= (car val) 500))
2543 (if (cdr val)
2544 (if (eq (car (cdr val)) 999)
2545 (math-add-bignum (cdr val) '(1))
2546 (cons (1+ (car (cdr val))) (cdr (cdr val))))
2547 '(1))
2548 (cdr val))))))
2550 (if (< a 0)
2551 (- (math-scale-rounding (- a) n))
2552 (if (= n -1)
2553 (/ (+ a 5) 10)
2554 (/ (+ (math-scale-right a (- -1 n)) 5) 10))))))
2557 ;;; Compute the sum of A and B. [O O O] [Public]
2558 (defun math-add (a b)
2560 (and (not (or (consp a) (consp b)))
2561 (progn
2562 (setq a (+ a b))
2563 (if (or (<= a -1000000) (>= a 1000000))
2564 (math-bignum a)
2565 a)))
2566 (and (Math-zerop a) (not (eq (car-safe a) 'mod))
2567 (if (and (math-floatp a) (Math-ratp b)) (math-float b) b))
2568 (and (Math-zerop b) (not (eq (car-safe b) 'mod))
2569 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a))
2570 (and (Math-objvecp a) (Math-objvecp b)
2572 (and (Math-integerp a) (Math-integerp b)
2573 (progn
2574 (or (consp a) (setq a (math-bignum a)))
2575 (or (consp b) (setq b (math-bignum b)))
2576 (if (eq (car a) 'bigneg)
2577 (if (eq (car b) 'bigneg)
2578 (cons 'bigneg (math-add-bignum (cdr a) (cdr b)))
2579 (math-normalize
2580 (let ((diff (math-sub-bignum (cdr b) (cdr a))))
2581 (if (eq diff 'neg)
2582 (cons 'bigneg (math-sub-bignum (cdr a) (cdr b)))
2583 (cons 'bigpos diff)))))
2584 (if (eq (car b) 'bigneg)
2585 (math-normalize
2586 (let ((diff (math-sub-bignum (cdr a) (cdr b))))
2587 (if (eq diff 'neg)
2588 (cons 'bigneg (math-sub-bignum (cdr b) (cdr a)))
2589 (cons 'bigpos diff))))
2590 (cons 'bigpos (math-add-bignum (cdr a) (cdr b)))))))
2591 (and (Math-ratp a) (Math-ratp b)
2592 (calc-extensions)
2593 (calc-add-fractions a b))
2594 (and (Math-realp a) (Math-realp b)
2595 (progn
2596 (or (and (consp a) (eq (car a) 'float))
2597 (setq a (math-float a)))
2598 (or (and (consp b) (eq (car b) 'float))
2599 (setq b (math-float b)))
2600 (math-add-float a b)))
2601 (and (calc-extensions)
2602 (math-add-objects-fancy a b))))
2603 (and (calc-extensions)
2604 (math-add-symb-fancy a b))))
2606 (defun math-add-bignum (a b) ; [L L L; l l l]
2607 (if a
2608 (if b
2609 (let* ((a (copy-sequence a)) (aa a) (carry nil) sum)
2610 (while (and aa b)
2611 (if carry
2612 (if (< (setq sum (+ (car aa) (car b))) 999)
2613 (progn
2614 (setcar aa (1+ sum))
2615 (setq carry nil))
2616 (setcar aa (+ sum -999)))
2617 (if (< (setq sum (+ (car aa) (car b))) 1000)
2618 (setcar aa sum)
2619 (setcar aa (+ sum -1000))
2620 (setq carry t)))
2621 (setq aa (cdr aa)
2622 b (cdr b)))
2623 (if carry
2624 (if b
2625 (nconc a (math-add-bignum b '(1)))
2626 (while (eq (car aa) 999)
2627 (setcar aa 0)
2628 (setq aa (cdr aa)))
2629 (if aa
2630 (progn
2631 (setcar aa (1+ (car aa)))
2633 (nconc a '(1))))
2634 (if b
2635 (nconc a b)
2636 a)))
2640 (defun math-sub-bignum (a b) ; [l l l]
2641 (if b
2642 (if a
2643 (let* ((a (copy-sequence a)) (aa a) (borrow nil) sum)
2644 (while (and aa b)
2645 (if borrow
2646 (if (>= (setq diff (- (car aa) (car b))) 1)
2647 (progn
2648 (setcar aa (1- diff))
2649 (setq borrow nil))
2650 (setcar aa (+ diff 999)))
2651 (if (>= (setq diff (- (car aa) (car b))) 0)
2652 (setcar aa diff)
2653 (setcar aa (+ diff 1000))
2654 (setq borrow t)))
2655 (setq aa (cdr aa)
2656 b (cdr b)))
2657 (if borrow
2658 (progn
2659 (while (eq (car aa) 0)
2660 (setcar aa 999)
2661 (setq aa (cdr aa)))
2662 (if aa
2663 (progn
2664 (setcar aa (1- (car aa)))
2666 'neg))
2667 (while (eq (car b) 0)
2668 (setq b (cdr b)))
2669 (if b
2670 'neg
2671 a)))
2672 (while (eq (car b) 0)
2673 (setq b (cdr b)))
2674 (and b
2675 'neg))
2678 (defun math-add-float (a b) ; [F F F]
2679 (let ((ediff (- (nth 2 a) (nth 2 b))))
2680 (if (>= ediff 0)
2681 (if (>= ediff (+ calc-internal-prec calc-internal-prec))
2683 (math-make-float (math-add (nth 1 b)
2684 (if (eq ediff 0)
2685 (nth 1 a)
2686 (math-scale-left (nth 1 a) ediff)))
2687 (nth 2 b)))
2688 (if (>= (setq ediff (- ediff))
2689 (+ calc-internal-prec calc-internal-prec))
2691 (math-make-float (math-add (nth 1 a)
2692 (math-scale-left (nth 1 b) ediff))
2693 (nth 2 a))))))
2695 ;;; Compute the difference of A and B. [O O O] [Public]
2696 (defun math-sub (a b)
2697 (if (or (consp a) (consp b))
2698 (math-add a (math-neg b))
2699 (setq a (- a b))
2700 (if (or (<= a -1000000) (>= a 1000000))
2701 (math-bignum a)
2702 a)))
2704 (defun math-sub-float (a b) ; [F F F]
2705 (let ((ediff (- (nth 2 a) (nth 2 b))))
2706 (if (>= ediff 0)
2707 (if (>= ediff (+ calc-internal-prec calc-internal-prec))
2709 (math-make-float (math-add (Math-integer-neg (nth 1 b))
2710 (if (eq ediff 0)
2711 (nth 1 a)
2712 (math-scale-left (nth 1 a) ediff)))
2713 (nth 2 b)))
2714 (if (>= (setq ediff (- ediff))
2715 (+ calc-internal-prec calc-internal-prec))
2717 (math-make-float (math-add (nth 1 a)
2718 (Math-integer-neg
2719 (math-scale-left (nth 1 b) ediff)))
2720 (nth 2 a))))))
2723 ;;; Compute the product of A and B. [O O O] [Public]
2724 (defun math-mul (a b)
2726 (and (not (consp a)) (not (consp b))
2727 (< a 1000) (> a -1000) (< b 1000) (> b -1000)
2728 (* a b))
2729 (and (Math-zerop a) (not (eq (car-safe b) 'mod))
2730 (if (Math-scalarp b)
2731 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
2732 (calc-extensions)
2733 (math-mul-zero a b)))
2734 (and (Math-zerop b) (not (eq (car-safe a) 'mod))
2735 (if (Math-scalarp a)
2736 (if (and (math-floatp a) (Math-ratp b)) (math-float b) b)
2737 (calc-extensions)
2738 (math-mul-zero b a)))
2739 (and (Math-objvecp a) (Math-objvecp b)
2741 (and (Math-integerp a) (Math-integerp b)
2742 (progn
2743 (or (consp a) (setq a (math-bignum a)))
2744 (or (consp b) (setq b (math-bignum b)))
2745 (math-normalize
2746 (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
2747 (if (cdr (cdr a))
2748 (if (cdr (cdr b))
2749 (math-mul-bignum (cdr a) (cdr b))
2750 (math-mul-bignum-digit (cdr a) (nth 1 b) 0))
2751 (math-mul-bignum-digit (cdr b) (nth 1 a) 0))))))
2752 (and (Math-ratp a) (Math-ratp b)
2753 (calc-extensions)
2754 (calc-mul-fractions a b))
2755 (and (Math-realp a) (Math-realp b)
2756 (progn
2757 (or (and (consp a) (eq (car a) 'float))
2758 (setq a (math-float a)))
2759 (or (and (consp b) (eq (car b) 'float))
2760 (setq b (math-float b)))
2761 (math-make-float (math-mul (nth 1 a) (nth 1 b))
2762 (+ (nth 2 a) (nth 2 b)))))
2763 (and (calc-extensions)
2764 (math-mul-objects-fancy a b))))
2765 (and (calc-extensions)
2766 (math-mul-symb-fancy a b))))
2768 (defun math-infinitep (a &optional undir)
2769 (while (and (consp a) (memq (car a) '(* / neg)))
2770 (if (or (not (eq (car a) '*)) (math-infinitep (nth 1 a)))
2771 (setq a (nth 1 a))
2772 (setq a (nth 2 a))))
2773 (and (consp a)
2774 (eq (car a) 'var)
2775 (memq (nth 2 a) '(var-inf var-uinf var-nan))
2776 (if (and undir (eq (nth 2 a) 'var-inf))
2777 '(var uinf var-uinf)
2778 a)))
2780 ;;; Multiply digit lists A and B. [L L L; l l l]
2781 (defun math-mul-bignum (a b)
2782 (and a b
2783 (let* ((sum (if (<= (car b) 1)
2784 (if (= (car b) 0)
2785 (list 0)
2786 (copy-sequence a))
2787 (math-mul-bignum-digit a (car b) 0)))
2788 (sump sum) c d aa ss prod)
2789 (while (setq b (cdr b))
2790 (setq ss (setq sump (or (cdr sump) (setcdr sump (list 0))))
2791 d (car b)
2793 aa a)
2794 (while (progn
2795 (setcar ss (% (setq prod (+ (+ (car ss) (* (car aa) d))
2796 c)) 1000))
2797 (setq aa (cdr aa)))
2798 (setq c (/ prod 1000)
2799 ss (or (cdr ss) (setcdr ss (list 0)))))
2800 (if (>= prod 1000)
2801 (if (cdr ss)
2802 (setcar (cdr ss) (+ (/ prod 1000) (car (cdr ss))))
2803 (setcdr ss (list (/ prod 1000))))))
2804 sum)))
2806 ;;; Multiply digit list A by digit D. [L L D D; l l D D]
2807 (defun math-mul-bignum-digit (a d c)
2808 (if a
2809 (if (<= d 1)
2810 (and (= d 1) a)
2811 (let* ((a (copy-sequence a)) (aa a) prod)
2812 (while (progn
2813 (setcar aa (% (setq prod (+ (* (car aa) d) c)) 1000))
2814 (cdr aa))
2815 (setq aa (cdr aa)
2816 c (/ prod 1000)))
2817 (if (>= prod 1000)
2818 (setcdr aa (list (/ prod 1000))))
2820 (and (> c 0)
2821 (list c))))
2824 ;;; Compute the integer (quotient . remainder) of A and B, which may be
2825 ;;; small or big integers. Type and consistency of truncation is undefined
2826 ;;; if A or B is negative. B must be nonzero. [I.I I I] [Public]
2827 (defun math-idivmod (a b)
2828 (if (eq b 0)
2829 (math-reject-arg a "*Division by zero"))
2830 (if (or (consp a) (consp b))
2831 (if (and (natnump b) (< b 1000))
2832 (let ((res (math-div-bignum-digit (cdr a) b)))
2833 (cons
2834 (math-normalize (cons (car a) (car res)))
2835 (cdr res)))
2836 (or (consp a) (setq a (math-bignum a)))
2837 (or (consp b) (setq b (math-bignum b)))
2838 (let ((res (math-div-bignum (cdr a) (cdr b))))
2839 (cons
2840 (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
2841 (car res)))
2842 (math-normalize (cons (car a) (cdr res))))))
2843 (cons (/ a b) (% a b))))
2845 (defun math-quotient (a b) ; [I I I] [Public]
2846 (if (and (not (consp a)) (not (consp b)))
2847 (if (= b 0)
2848 (math-reject-arg a "*Division by zero")
2849 (/ a b))
2850 (if (and (natnump b) (< b 1000))
2851 (if (= b 0)
2852 (math-reject-arg a "*Division by zero")
2853 (math-normalize (cons (car a)
2854 (car (math-div-bignum-digit (cdr a) b)))))
2855 (or (consp a) (setq a (math-bignum a)))
2856 (or (consp b) (setq b (math-bignum b)))
2857 (let* ((alen (1- (length a)))
2858 (blen (1- (length b)))
2859 (d (/ 1000 (1+ (nth (1- blen) (cdr b)))))
2860 (res (math-div-bignum-big (math-mul-bignum-digit (cdr a) d 0)
2861 (math-mul-bignum-digit (cdr b) d 0)
2862 alen blen)))
2863 (math-normalize (cons (if (eq (car a) (car b)) 'bigpos 'bigneg)
2864 (car res)))))))
2867 ;;; Divide a bignum digit list by another. [l.l l L]
2868 ;;; The following division algorithm is borrowed from Knuth vol. II, sec. 4.3.1
2869 (defun math-div-bignum (a b)
2870 (if (cdr b)
2871 (let* ((alen (length a))
2872 (blen (length b))
2873 (d (/ 1000 (1+ (nth (1- blen) b))))
2874 (res (math-div-bignum-big (math-mul-bignum-digit a d 0)
2875 (math-mul-bignum-digit b d 0)
2876 alen blen)))
2877 (if (= d 1)
2879 (cons (car res)
2880 (car (math-div-bignum-digit (cdr res) d)))))
2881 (let ((res (math-div-bignum-digit a (car b))))
2882 (cons (car res) (list (cdr res))))))
2884 ;;; Divide a bignum digit list by a digit. [l.D l D]
2885 (defun math-div-bignum-digit (a b)
2886 (if a
2887 (let* ((res (math-div-bignum-digit (cdr a) b))
2888 (num (+ (* (cdr res) 1000) (car a))))
2889 (cons
2890 (cons (/ num b) (car res))
2891 (% num b)))
2892 '(nil . 0)))
2894 (defun math-div-bignum-big (a b alen blen) ; [l.l l L]
2895 (if (< alen blen)
2896 (cons nil a)
2897 (let* ((res (math-div-bignum-big (cdr a) b (1- alen) blen))
2898 (num (cons (car a) (cdr res)))
2899 (res2 (math-div-bignum-part num b blen)))
2900 (cons
2901 (cons (car res2) (car res))
2902 (cdr res2)))))
2904 (defun math-div-bignum-part (a b blen) ; a < b*1000 [D.l l L]
2905 (let* ((num (+ (* (or (nth blen a) 0) 1000) (or (nth (1- blen) a) 0)))
2906 (den (nth (1- blen) b))
2907 (guess (min (/ num den) 999)))
2908 (math-div-bignum-try a b (math-mul-bignum-digit b guess 0) guess)))
2910 (defun math-div-bignum-try (a b c guess) ; [D.l l l D]
2911 (let ((rem (math-sub-bignum a c)))
2912 (if (eq rem 'neg)
2913 (math-div-bignum-try a b (math-sub-bignum c b) (1- guess))
2914 (cons guess rem))))
2917 ;;; Compute the quotient of A and B. [O O N] [Public]
2918 (defun math-div (a b)
2920 (and (Math-zerop b)
2921 (calc-extensions)
2922 (math-div-by-zero a b))
2923 (and (Math-zerop a) (not (eq (car-safe b) 'mod))
2924 (if (Math-scalarp b)
2925 (if (and (math-floatp b) (Math-ratp a)) (math-float a) a)
2926 (calc-extensions)
2927 (math-div-zero a b)))
2928 (and (Math-objvecp a) (Math-objvecp b)
2930 (and (Math-integerp a) (Math-integerp b)
2931 (let ((q (math-idivmod a b)))
2932 (if (eq (cdr q) 0)
2933 (car q)
2934 (if calc-prefer-frac
2935 (progn
2936 (calc-extensions)
2937 (math-make-frac a b))
2938 (math-div-float (math-make-float a 0)
2939 (math-make-float b 0))))))
2940 (and (Math-ratp a) (Math-ratp b)
2941 (calc-extensions)
2942 (calc-div-fractions a b))
2943 (and (Math-realp a) (Math-realp b)
2944 (progn
2945 (or (and (consp a) (eq (car a) 'float))
2946 (setq a (math-float a)))
2947 (or (and (consp b) (eq (car b) 'float))
2948 (setq b (math-float b)))
2949 (math-div-float a b)))
2950 (and (calc-extensions)
2951 (math-div-objects-fancy a b))))
2952 (and (calc-extensions)
2953 (math-div-symb-fancy a b))))
2955 (defun math-div-float (a b) ; [F F F]
2956 (let ((ldiff (max (- (1+ calc-internal-prec)
2957 (- (math-numdigs (nth 1 a)) (math-numdigs (nth 1 b))))
2958 0)))
2959 (math-make-float (math-quotient (math-scale-int (nth 1 a) ldiff) (nth 1 b))
2960 (- (- (nth 2 a) (nth 2 b)) ldiff))))
2966 ;;; Format the number A as a string. [X N; X Z] [Public]
2967 (defun math-format-stack-value (entry)
2968 (setq calc-selection-cache-entry calc-selection-cache-default-entry)
2969 (let* ((a (car entry))
2970 (math-comp-selected (nth 2 entry))
2971 (c (cond ((null a) "<nil>")
2972 ((eq calc-display-raw t) (format "%s" a))
2973 ((stringp a) a)
2974 ((eq a 'top-of-stack) ".")
2975 (calc-prepared-composition
2976 calc-prepared-composition)
2977 ((and (Math-scalarp a)
2978 (memq calc-language '(nil flat unform))
2979 (null math-comp-selected))
2980 (math-format-number a))
2981 (t (calc-extensions)
2982 (math-compose-expr a 0))))
2983 (off (math-stack-value-offset c))
2984 s w)
2985 (and math-comp-selected (setq calc-any-selections t))
2986 (setq w (cdr off)
2987 off (car off))
2988 (if (> off 0)
2989 (setq c (math-comp-concat (make-string off ? ) c)))
2990 (or (equal calc-left-label "")
2991 (setq c (math-comp-concat (if (eq a 'top-of-stack)
2992 (make-string (length calc-left-label) ? )
2993 calc-left-label)
2994 c)))
2995 (if calc-line-numbering
2996 (setq c (math-comp-concat (if (eq calc-language 'big)
2997 (if math-comp-selected
2998 '(tag t "1: ") "1: ")
2999 " ")
3000 c)))
3001 (or (equal calc-right-label "")
3002 (eq a 'top-of-stack)
3003 (progn
3004 (calc-extensions)
3005 (setq c (list 'horiz c
3006 (make-string (max (- w (math-comp-width c)
3007 (length calc-right-label)) 0) ? )
3008 '(break -1)
3009 calc-right-label))))
3010 (setq s (if (stringp c)
3011 (if calc-display-raw
3012 (prin1-to-string c)
3014 (math-composition-to-string c w)))
3015 (if calc-language-output-filter
3016 (setq s (funcall calc-language-output-filter s)))
3017 (if (eq calc-language 'big)
3018 (setq s (concat s "\n"))
3019 (if calc-line-numbering
3020 (progn
3021 (aset s 0 ?1)
3022 (aset s 1 ?:))))
3023 (setcar (cdr entry) (calc-count-lines s))
3026 (defun math-stack-value-offset (c)
3027 (let* ((num (if calc-line-numbering 4 0))
3028 (wid (calc-window-width))
3029 off)
3030 (if calc-display-just
3031 (progn
3032 (calc-extensions)
3033 (math-stack-value-offset-fancy))
3034 (setq off (or calc-display-origin 0))
3035 (if (integerp calc-line-breaking)
3036 (setq wid calc-line-breaking)))
3037 (cons (max (- off (length calc-left-label)) 0)
3038 (+ wid num))))
3040 (defun calc-count-lines (s)
3041 (let ((pos 0)
3042 (num 1))
3043 (while (setq newpos (string-match "\n" s pos))
3044 (setq pos (1+ newpos)
3045 num (1+ num)))
3046 num))
3048 (defun math-format-value (a &optional w)
3049 (if (and (Math-scalarp a)
3050 (memq calc-language '(nil flat unform)))
3051 (math-format-number a)
3052 (calc-extensions)
3053 (let ((calc-line-breaking nil))
3054 (math-composition-to-string (math-compose-expr a 0) w))))
3056 (defun calc-window-width ()
3057 (if calc-embedded-info
3058 (let ((win (get-buffer-window (aref calc-embedded-info 0))))
3059 (1- (if win (window-width win) (frame-width))))
3060 (- (window-width (get-buffer-window (current-buffer)))
3061 (if calc-line-numbering 5 1))))
3063 (defun math-comp-concat (c1 c2)
3064 (if (and (stringp c1) (stringp c2))
3065 (concat c1 c2)
3066 (list 'horiz c1 c2)))
3070 ;;; Format an expression as a one-line string suitable for re-reading.
3072 (defun math-format-flat-expr (a prec)
3073 (cond
3074 ((or (not (or (consp a) (integerp a)))
3075 (eq calc-display-raw t))
3076 (let ((print-escape-newlines t))
3077 (concat "'" (prin1-to-string a))))
3078 ((Math-scalarp a)
3079 (let ((calc-group-digits nil)
3080 (calc-point-char ".")
3081 (calc-frac-format (if (> (length (car calc-frac-format)) 1)
3082 '("::" nil) '(":" nil)))
3083 (calc-complex-format nil)
3084 (calc-hms-format "%s@ %s' %s\"")
3085 (calc-language nil))
3086 (math-format-number a)))
3088 (calc-extensions)
3089 (math-format-flat-expr-fancy a prec))))
3093 ;;; Format a number as a string.
3094 (defun math-format-number (a &optional prec) ; [X N] [Public]
3095 (cond
3096 ((eq calc-display-raw t) (format "%s" a))
3097 ((and (nth 1 calc-frac-format) (Math-integerp a))
3098 (calc-extensions)
3099 (math-format-number (math-adjust-fraction a)))
3100 ((integerp a)
3101 (if (not (or calc-group-digits calc-leading-zeros))
3102 (if (= calc-number-radix 10)
3103 (int-to-string a)
3104 (if (< a 0)
3105 (concat "-" (math-format-number (- a)))
3106 (calc-extensions)
3107 (if math-radix-explicit-format
3108 (if calc-radix-formatter
3109 (funcall calc-radix-formatter
3110 calc-number-radix
3111 (if (= calc-number-radix 2)
3112 (math-format-binary a)
3113 (math-format-radix a)))
3114 (format "%d#%s" calc-number-radix
3115 (if (= calc-number-radix 2)
3116 (math-format-binary a)
3117 (math-format-radix a))))
3118 (math-format-radix a))))
3119 (math-format-number (math-bignum a))))
3120 ((stringp a) a)
3121 ((not (consp a)) (prin1-to-string a))
3122 ((eq (car a) 'bigpos) (math-format-bignum (cdr a)))
3123 ((eq (car a) 'bigneg) (concat "-" (math-format-bignum (cdr a))))
3124 ((and (eq (car a) 'float) (= calc-number-radix 10))
3125 (if (Math-integer-negp (nth 1 a))
3126 (concat "-" (math-format-number (math-neg a)))
3127 (let ((mant (nth 1 a))
3128 (exp (nth 2 a))
3129 (fmt (car calc-float-format))
3130 (figs (nth 1 calc-float-format))
3131 (point calc-point-char)
3132 str)
3133 (if (and (eq fmt 'fix)
3134 (or (and (< figs 0) (setq figs (- figs)))
3135 (> (+ exp (math-numdigs mant)) (- figs))))
3136 (progn
3137 (setq mant (math-scale-rounding mant (+ exp figs))
3138 str (if (integerp mant)
3139 (int-to-string mant)
3140 (math-format-bignum-decimal (cdr mant))))
3141 (if (<= (length str) figs)
3142 (setq str (concat (make-string (1+ (- figs (length str))) ?0)
3143 str)))
3144 (if (> figs 0)
3145 (setq str (concat (substring str 0 (- figs)) point
3146 (substring str (- figs))))
3147 (setq str (concat str point)))
3148 (when calc-group-digits
3149 (require 'calc-ext)
3150 (setq str (math-group-float str))))
3151 (if (< figs 0)
3152 (setq figs (+ calc-internal-prec figs)))
3153 (if (> figs 0)
3154 (let ((adj (- figs (math-numdigs mant))))
3155 (if (< adj 0)
3156 (setq mant (math-scale-rounding mant adj)
3157 exp (- exp adj)))))
3158 (setq str (if (integerp mant)
3159 (int-to-string mant)
3160 (math-format-bignum-decimal (cdr mant))))
3161 (let* ((len (length str))
3162 (dpos (+ exp len)))
3163 (if (and (eq fmt 'float)
3164 (<= dpos (+ calc-internal-prec calc-display-sci-high))
3165 (>= dpos (+ calc-display-sci-low 2)))
3166 (progn
3167 (cond
3168 ((= dpos 0)
3169 (setq str (concat "0" point str)))
3170 ((and (<= exp 0) (> dpos 0))
3171 (setq str (concat (substring str 0 dpos) point
3172 (substring str dpos))))
3173 ((> exp 0)
3174 (setq str (concat str (make-string exp ?0) point)))
3175 (t ; (< dpos 0)
3176 (setq str (concat "0" point
3177 (make-string (- dpos) ?0) str))))
3178 (when calc-group-digits
3179 (require 'calc-ext)
3180 (setq str (math-group-float str))))
3181 (let* ((eadj (+ exp len))
3182 (scale (if (eq fmt 'eng)
3183 (1+ (math-mod (+ eadj 300002) 3))
3184 1)))
3185 (if (> scale (length str))
3186 (setq str (concat str (make-string (- scale (length str))
3187 ?0))))
3188 (if (< scale (length str))
3189 (setq str (concat (substring str 0 scale) point
3190 (substring str scale))))
3191 (when calc-group-digits
3192 (require 'calc-ext)
3193 (setq str (math-group-float str)))
3194 (setq str (format (if (memq calc-language '(math maple))
3195 (if (and prec (> prec 191))
3196 "(%s*10.^%d)" "%s*10.^%d")
3197 "%se%d")
3198 str (- eadj scale)))))))
3199 str)))
3201 (calc-extensions)
3202 (math-format-number-fancy a prec))))
3204 (defun math-format-bignum (a) ; [X L]
3205 (if (and (= calc-number-radix 10)
3206 (not calc-leading-zeros)
3207 (not calc-group-digits))
3208 (math-format-bignum-decimal a)
3209 (calc-extensions)
3210 (math-format-bignum-fancy a)))
3212 (defun math-format-bignum-decimal (a) ; [X L]
3213 (if a
3214 (let ((s ""))
3215 (while (cdr (cdr a))
3216 (setq s (concat (format "%06d" (+ (* (nth 1 a) 1000) (car a))) s)
3217 a (cdr (cdr a))))
3218 (concat (int-to-string (+ (* (or (nth 1 a) 0) 1000) (car a))) s))
3219 "0"))
3223 ;;; Parse a simple number in string form. [N X] [Public]
3224 (defun math-read-number (s)
3225 (math-normalize
3226 (cond
3228 ;; Integers (most common case)
3229 ((string-match "\\` *\\([0-9]+\\) *\\'" s)
3230 (let ((digs (math-match-substring s 1)))
3231 (if (and (eq calc-language 'c)
3232 (> (length digs) 1)
3233 (eq (aref digs 0) ?0))
3234 (math-read-number (concat "8#" digs))
3235 (if (<= (length digs) 6)
3236 (string-to-int digs)
3237 (cons 'bigpos (math-read-bignum digs))))))
3239 ;; Clean up the string if necessary
3240 ((string-match "\\`\\(.*\\)[ \t\n]+\\([^\001]*\\)\\'" s)
3241 (math-read-number (concat (math-match-substring s 1)
3242 (math-match-substring s 2))))
3244 ;; Plus and minus signs
3245 ((string-match "^[-_+]\\(.*\\)$" s)
3246 (let ((val (math-read-number (math-match-substring s 1))))
3247 (and val (if (eq (aref s 0) ?+) val (math-neg val)))))
3249 ;; Forms that require extensions module
3250 ((string-match "[^-+0-9eE.]" s)
3251 (calc-extensions)
3252 (math-read-number-fancy s))
3254 ;; Decimal point
3255 ((string-match "^\\([0-9]*\\)\\.\\([0-9]*\\)$" s)
3256 (let ((int (math-match-substring s 1))
3257 (frac (math-match-substring s 2)))
3258 (let ((ilen (length int))
3259 (flen (length frac)))
3260 (let ((int (if (> ilen 0) (math-read-number int) 0))
3261 (frac (if (> flen 0) (math-read-number frac) 0)))
3262 (and int frac (or (> ilen 0) (> flen 0))
3263 (list 'float
3264 (math-add (math-scale-int int flen) frac)
3265 (- flen)))))))
3267 ;; "e" notation
3268 ((string-match "^\\(.*\\)[eE]\\([-+]?[0-9]+\\)$" s)
3269 (let ((mant (math-match-substring s 1))
3270 (exp (math-match-substring s 2)))
3271 (let ((mant (if (> (length mant) 0) (math-read-number mant) 1))
3272 (exp (if (<= (length exp) (if (memq (aref exp 0) '(?+ ?-)) 8 7))
3273 (string-to-int exp))))
3274 (and mant exp (Math-realp mant) (> exp -4000000) (< exp 4000000)
3275 (let ((mant (math-float mant)))
3276 (list 'float (nth 1 mant) (+ (nth 2 mant) exp)))))))
3278 ;; Syntax error!
3279 (t nil))))
3281 (defun math-match-substring (s n)
3282 (if (match-beginning n)
3283 (substring s (match-beginning n) (match-end n))
3284 ""))
3286 (defun math-read-bignum (s) ; [l X]
3287 (if (> (length s) 3)
3288 (cons (string-to-int (substring s -3))
3289 (math-read-bignum (substring s 0 -3)))
3290 (list (string-to-int s))))
3293 (defconst math-tex-ignore-words
3294 '( ("\\hbox") ("\\mbox") ("\\text") ("\\left") ("\\right")
3295 ("\\,") ("\\>") ("\\:") ("\\;") ("\\!") ("\\ ")
3296 ("\\quad") ("\\qquad") ("\\hfil") ("\\hfill")
3297 ("\\displaystyle") ("\\textstyle") ("\\dsize") ("\\tsize")
3298 ("\\scriptstyle") ("\\scriptscriptstyle") ("\\ssize") ("\\sssize")
3299 ("\\rm") ("\\bf") ("\\it") ("\\sl")
3300 ("\\roman") ("\\bold") ("\\italic") ("\\slanted")
3301 ("\\cal") ("\\mit") ("\\Cal") ("\\Bbb") ("\\frak") ("\\goth")
3302 ("\\evalto")
3303 ("\\matrix" mat) ("\\bmatrix" mat) ("\\pmatrix" mat)
3304 ("\\cr" punc ";") ("\\\\" punc ";") ("\\*" punc "*")
3305 ("\\{" punc "[") ("\\}" punc "]")
3308 (defconst math-eqn-ignore-words
3309 '( ("roman") ("bold") ("italic") ("mark") ("lineup") ("evalto")
3310 ("left" ("floor") ("ceil"))
3311 ("right" ("floor") ("ceil"))
3312 ("arc" ("sin") ("cos") ("tan") ("sinh") ("cosh") ("tanh"))
3313 ("size" n) ("font" n) ("fwd" n) ("back" n) ("up" n) ("down" n)
3314 ("above" punc ",")
3317 (defconst math-standard-opers
3318 '( ( "_" calcFunc-subscr 1200 1201 )
3319 ( "%" calcFunc-percent 1100 -1 )
3320 ( "u+" ident -1 1000 )
3321 ( "u-" neg -1 1000 197 )
3322 ( "u!" calcFunc-lnot -1 1000 )
3323 ( "mod" mod 400 400 185 )
3324 ( "+/-" sdev 300 300 185 )
3325 ( "!!" calcFunc-dfact 210 -1 )
3326 ( "!" calcFunc-fact 210 -1 )
3327 ( "^" ^ 201 200 )
3328 ( "**" ^ 201 200 )
3329 ( "*" * 196 195 )
3330 ( "2x" * 196 195 )
3331 ( "/" / 190 191 )
3332 ( "%" % 190 191 )
3333 ( "\\" calcFunc-idiv 190 191 )
3334 ( "+" + 180 181 )
3335 ( "-" - 180 181 )
3336 ( "|" | 170 171 )
3337 ( "<" calcFunc-lt 160 161 )
3338 ( ">" calcFunc-gt 160 161 )
3339 ( "<=" calcFunc-leq 160 161 )
3340 ( ">=" calcFunc-geq 160 161 )
3341 ( "=" calcFunc-eq 160 161 )
3342 ( "==" calcFunc-eq 160 161 )
3343 ( "!=" calcFunc-neq 160 161 )
3344 ( "&&" calcFunc-land 110 111 )
3345 ( "||" calcFunc-lor 100 101 )
3346 ( "?" (math-read-if) 91 90 )
3347 ( "!!!" calcFunc-pnot -1 85 )
3348 ( "&&&" calcFunc-pand 80 81 )
3349 ( "|||" calcFunc-por 75 76 )
3350 ( ":=" calcFunc-assign 51 50 )
3351 ( "::" calcFunc-condition 45 46 )
3352 ( "=>" calcFunc-evalto 40 41 )
3353 ( "=>" calcFunc-evalto 40 -1 )))
3354 (defvar math-expr-opers math-standard-opers)
3356 ;;;###autoload
3357 (defun calc-grab-region (top bot arg)
3358 "Parse the region as a vector of numbers and push it on the Calculator stack."
3359 (interactive "r\nP")
3360 (calc-extensions)
3361 (calc-do-grab-region top bot arg))
3363 ;;;###autoload
3364 (defun calc-grab-rectangle (top bot arg)
3365 "Parse a rectangle as a matrix of numbers and push it on the Calculator stack."
3366 (interactive "r\nP")
3367 (calc-extensions)
3368 (calc-do-grab-rectangle top bot arg))
3370 (defun calc-grab-sum-down (top bot arg)
3371 "Parse a rectangle as a matrix of numbers and sum its columns."
3372 (interactive "r\nP")
3373 (calc-extensions)
3374 (calc-do-grab-rectangle top bot arg 'calcFunc-reduced))
3376 (defun calc-grab-sum-across (top bot arg)
3377 "Parse a rectangle as a matrix of numbers and sum its rows."
3378 (interactive "r\nP")
3379 (calc-extensions)
3380 (calc-do-grab-rectangle top bot arg 'calcFunc-reducea))
3383 ;;;###autoload
3384 (defun calc-embedded (arg &optional end obeg oend)
3385 "Start Calc Embedded mode on the formula surrounding point."
3386 (interactive "P")
3387 (calc-extensions)
3388 (calc-do-embedded arg end obeg oend))
3390 ;;;###autoload
3391 (defun calc-embedded-activate (&optional arg cbuf)
3392 "Scan the current editing buffer for all embedded := and => formulas.
3393 Also looks for the equivalent TeX words, \\gets and \\evalto."
3394 (interactive "P")
3395 (calc-do-embedded-activate arg cbuf))
3398 (defun calc-user-invocation ()
3399 (interactive)
3400 (or (stringp calc-invocation-macro)
3401 (error "Use `Z I' inside Calc to define a `M-# Z' keyboard macro"))
3402 (execute-kbd-macro calc-invocation-macro nil))
3407 ;;; User-programmability.
3409 ;;;###autoload
3410 (defmacro defmath (func args &rest body) ; [Public]
3411 (calc-extensions)
3412 (math-do-defmath func args body))
3415 ;;; Functions needed for Lucid Emacs support.
3417 (defun calc-read-key (&optional optkey)
3418 (cond (calc-emacs-type-lucid
3419 (let ((event (next-command-event)))
3420 (let ((key (event-to-character event t t)))
3421 (or key optkey (error "Expected a plain keystroke"))
3422 (cons key event))))
3423 (calc-emacs-type-gnu19
3424 (let ((key (read-event)))
3425 (cons key key)))
3427 (let ((key (read-char)))
3428 (cons key key)))))
3430 (defun calc-unread-command (&optional input)
3431 (if (featurep 'xemacs)
3432 (setq unread-command-event
3433 (if (integerp input) (character-to-event input)
3434 (or input last-command-event)))
3435 (push (or input last-command-event) unread-command-events)))
3437 (defun calc-clear-unread-commands ()
3438 (if (featurep 'xemacs)
3439 (calc-emacs-type-lucid (setq unread-command-event nil))
3440 (setq unread-command-events nil)))
3442 (if calc-always-load-extensions
3443 (progn
3444 (calc-extensions)
3445 (calc-load-everything)))
3448 (run-hooks 'calc-load-hook)
3450 ;;; calc.el ends here