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