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