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