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